Modern Apps git

← Modern-Apps.git

email: attachment downloads decode the transfer encoding instead of saving wire bytes

Commit
33f56708b1dc75180c623cf37f45421e934b12ec
Author
Vayun Mathur <[email protected]>
When
2026-12-01 07:01 UTC (5 days ago)
Parents
e8d9f76
ImapClient.downloadAttachment fetched BODY.PEEK[section]
and wrote the result straight to Downloads — but IMAP
returns the part still base64/quoted-printable encoded, so
most real attachments landed as encoding text: for the
multipart message whose stored Attachment row records size 4
(decoded), the download wrote the 8 ASCII bytes of
'AAECAw==' — wrong bytes, contradicting the app's own size.

The download path bypassed the only transfer decoder (the
message parser decodes CTE; the raw section fetch was never
parsed and had no CTE source). downloadAttachment now also
fetches the part's MIME header (BODY[section.MIME], or the
message HEADER block for a single-part message) and writes
only bytes decoded via the new MimeParser.
decodeAttachmentBytes, which reuses the existing decodeCte
(base64/QP/identity). Two regression tests pin base64 -> the
original 4 bytes with size matching the stored row, and
quoted-printable plus 7bit passthrough. Threading, search,
outbox and sync tombstones were audited and cleared.
Verified: :email:testDevUnitTest 592 tests pass; lint errors
are pre-existing on untouched files.

Diff

email/src/main/java/com/vayunmathur/email/network/imap/ImapClient.kt
diff --git a/email/src/main/java/com/vayunmathur/email/network/imap/ImapClient.kt b/email/src/main/java/com/vayunmathur/email/network/imap/ImapClient.ktindex 767db17012..16c9ff0017 100644--- a/email/src/main/java/com/vayunmathur/email/network/imap/ImapClient.kt+++ b/email/src/main/java/com/vayunmathur/email/network/imap/ImapClient.kt@@ -408,8 +408,19 @@ object ImapClient {     ): String = withConnection(server, user, auth) { conn ->         conn.select(folderName)         val section = partIdToSection(partId)-        val bytes = conn.fetch.uidFetchPartBytes(uid, section)+        val encoded = conn.fetch.uidFetchPartBytes(uid, section)             ?: throw IllegalStateException("Part $partId ($section) not found UID $uid")+        // BODY[section] returns the part still transfer-encoded, so fetch+        // the part's MIME header too and decode before saving: writing the+        // wire octets saved base64/QP text instead of the sender's file.+        // A single-part message (blank partId) carries its encoding in the+        // message header block rather than a section.MIME part header.+        val mimeHeader = if (partId.isBlank()) {+            conn.fetch.uidFetchPartBytes(uid, "HEADER")+        } else {+            conn.fetch.uidFetchPartBytes(uid, "$section.MIME")+        }+        val bytes = MimeParser.decodeAttachmentBytes(encoded, mimeHeader)         val resolver = context.contentResolver         val values = ContentValues().apply {             put(android.provider.MediaStore.MediaColumns.DISPLAY_NAME, fileName)
email/src/main/java/com/vayunmathur/email/network/imap/MimeParser.kt
diff --git a/email/src/main/java/com/vayunmathur/email/network/imap/MimeParser.kt b/email/src/main/java/com/vayunmathur/email/network/imap/MimeParser.ktindex c85039c179..6543fd8d0c 100644--- a/email/src/main/java/com/vayunmathur/email/network/imap/MimeParser.kt+++ b/email/src/main/java/com/vayunmathur/email/network/imap/MimeParser.kt@@ -298,6 +298,20 @@ object MimeParser {         return extractCidMapInternal(context, root, uid)     } +    /**+     * Transfer-decode one fetched attachment part. An IMAP `BODY[section]`+     * fetch returns the part still encoded (base64 / quoted-printable), so+     * writing those octets straight to a file saves the encoding text+     * instead of the file the sender sent; [mimeHeaderBytes] is that+     * part's `BODY[section.MIME]` header block, which carries its+     * Content-Transfer-Encoding. A missing header means 7bit identity.+     */+    fun decodeAttachmentBytes(partBytes: ByteArray, mimeHeaderBytes: ByteArray?): ByteArray {+        val headers = mimeHeaderBytes?.let { parseHeaderBlockBytes(it) } ?: emptyMap()+        val cte = (headers["content-transfer-encoding"] ?: "7bit").lowercase().trim()+        return decodeCte(partBytes, cte)+    }+     private fun extractCidMapInternal(context: Context, root: ParsedPart, uid: Long): Map<String, File> {         val dir = File(context.cacheDir, "cid/$uid").also { it.mkdirs() }         val collector = CidCollector(dir)
email/src/test/java/com/vayunmathur/email/mime/MimeParserRobolectricTest.kt
diff --git a/email/src/test/java/com/vayunmathur/email/mime/MimeParserRobolectricTest.kt b/email/src/test/java/com/vayunmathur/email/mime/MimeParserRobolectricTest.ktindex 563e94e33a..1f09fdc101 100644--- a/email/src/test/java/com/vayunmathur/email/mime/MimeParserRobolectricTest.kt+++ b/email/src/test/java/com/vayunmathur/email/mime/MimeParserRobolectricTest.kt@@ -98,6 +98,41 @@ class MimeParserRobolectricTest {         assertTrue(parsed.emlAttachments.isEmpty())     } +    @Test+    fun `decodeAttachmentBytes decodes base64 instead of saving encoding text`() {+        // Exact failing input for the download path: the file the sender+        // sent is bytes 00 01 02 03, carried on the wire (and returned by+        // BODY[2]) as the base64 text "AAECAw==", with the part's MIME+        // header naming base64. Only the decoded bytes are the file; the+        // stored Attachment.size (4, from parseMessage) proves it.+        val raw = "From: a@b\r\nSubject: Bin\r\nContent-Type: multipart/mixed; boundary=m\r\n\r\n" ++            "--m\r\nContent-Type: text/plain\r\n\r\nBody text\r\n" ++            "--m\r\nContent-Type: application/octet-stream; name=\"a.bin\"\r\n" ++            "Content-Disposition: attachment; filename=\"a.bin\"\r\n" ++            "Content-Transfer-Encoding: base64\r\n\r\nAAECAw==\r\n--m--\r\n"+        val messageBytes = raw.toByteArray(Charsets.UTF_8)+        val attachment = MimeParser.parseMessage(messageBytes, 9L, "[email protected]", "INBOX").third.single()+        assertEquals("a.bin", attachment.fileName)+        assertEquals(4L, attachment.size)+        val mimeHeader = "Content-Type: application/octet-stream; name=\"a.bin\"\r\n" ++            "Content-Transfer-Encoding: base64\r\n\r\n"+        val decoded = MimeParser.decodeAttachmentBytes("AAECAw==".toByteArray(Charsets.US_ASCII), mimeHeader.toByteArray(Charsets.UTF_8))+        assertTrue(decoded.contentEquals(byteArrayOf(0, 1, 2, 3)), "expected decoded file bytes, got ${decoded.toList()}")+        assertEquals(attachment.size, decoded.size.toLong())+    }++    @Test+    fun `decodeAttachmentBytes decodes quoted printable and passes 7bit through`() {+        val qpHeader = "Content-Type: text/csv\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\n"+        val decoded = MimeParser.decodeAttachmentBytes(+            "hello=20world".toByteArray(Charsets.US_ASCII),+            qpHeader.toByteArray(Charsets.UTF_8),+        )+        assertEquals("hello world", String(decoded, Charsets.UTF_8))+        val plain = "already plain".toByteArray(Charsets.US_ASCII)+        assertTrue(MimeParser.decodeAttachmentBytes(plain, null).contentEquals(plain))+    }+     @Test     fun `extractCidMap reconciles meta files on second call`() {         val png = b64("XYZ")