Modern Apps git

← Modern-Apps.git

email: decode RFC 2231 attachment filenames, not unnamed

Commit
b8566aa9da10840f02c705bf5840415f6c8302e4
Author
Vayun Mathur <[email protected]>
When
2026-12-01 19:03 UTC (4 days ago)
Parents
417f858
Bug: MimeParser stored Content-Type/Content-Disposition parameters
verbatim, so the RFC 2231 forms mail clients must use for
non-ASCII or long filenames (RFC 2047 is not allowed inside a
parameter) were keyed as filename* / filename*0* / filename*1*.
DispositionInfo.filename and the Content-Type name fallback only
look up filename/name, so every such attachment was recorded
as "unnamed" and downloaded under that name, losing its real
name and extension.

Fix: collapse RFC 2231 forms in parseHeaderParams before the
parameters reach any caller. Single extended values
(filename*=UTF-8''%E2%82%AC.pdf) are charset- and percent-
decoded, continuations are reassembled in segment order
(concatenating encoded segments before percent-decoding, so a
multi-byte character split across segments survives), plain
ASCII continuations are joined, and a decoded value supersedes
a plain fallback sent alongside it. HeaderParamParser now
preserves quoted values verbatim instead of trimming them, so
a continuation segment ending in a space keeps it; only
unquoted values carry syntax padding.

User-visible effect: attachments with non-ASCII or long
filenames keep their sender-given names instead of arriving
as "unnamed".

Verified: new MimeRfc2231Test failed 5 of 6 cases before the
fix and passes after; the full :email:testDevUnitTest suite
passes. ktlint main/test source sets are clean (the
ktlintCheck failure is pre-existing androidTest backlog).

Diff

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 6543fd8d0c..69dd0bb693 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@@ -482,7 +482,116 @@ object MimeParser {     private fun parseHeaderParams(paramStr: String): Map<String, String> {         val parser = HeaderParamParser(paramStr)         parser.parse()-        return parser.result+        return assembleRfc2231Params(parser.result)+    }++    /**+     * Collapse RFC 2231 parameter forms into the plain parameter they+     * encode. MUAs must not RFC 2047-encode parameter values, so a+     * non-ASCII or long filename arrives as `filename*=UTF-8''%E2%82%AC.pdf`+     * or split as `filename*0*=UTF-8''%E2%82%AC` / `filename*1*=.pdf`+     * (plain `filename*0=`/`filename*1=` for long ASCII values). Keyed+     * verbatim, none of those is `filename`, so the attachment was+     * stored as "unnamed". A plain fallback parameter sent alongside+     * an extended one is superseded by the decoded value.+     */+    private fun assembleRfc2231Params(raw: Map<String, String>): Map<String, String> {+        if (raw.keys.none { it.contains('*') }) return raw+        val result = mutableMapOf<String, String>()+        val extended = mutableMapOf<String, String>()+        val continuations = mutableMapOf<String, MutableMap<Int, Pair<String, Boolean>>>()+        val segmentPattern = Regex("""^(.+)\*(\d+)(\*)?$""")+        for ((key, value) in raw) {+            val lower = key.lowercase()+            val segment = segmentPattern.matchEntire(lower)+            when {+                segment != null -> continuations.getOrPut(segment.groupValues[1]) { mutableMapOf() }[+                    segment.groupValues[2].toInt(),+                ] = value to segment.groupValues[3].isNotEmpty()+                lower.endsWith("*") -> extended[lower.dropLast(1)] = value+                else -> result[key] = value+            }+        }+        for ((base, segments) in continuations) putDecoded(result, base, decodeRfc2231Segments(segments))+        for ((base, value) in extended) putDecoded(result, base, decodeRfc2231Value(value))+        return result+    }++    private fun putDecoded(result: MutableMap<String, String>, base: String, decoded: String) {+        result.keys.filter { it.equals(base, ignoreCase = true) }.forEach { result.remove(it) }+        result[base] = decoded+    }++    private fun decodeRfc2231Value(value: String): String {+        val (charset, encoded) = splitRfc2231Charset(value)+        return decodeCharset(percentDecodeBytes(encoded), charset)+    }++    private fun decodeRfc2231Segments(segments: Map<Int, Pair<String, Boolean>>): String {+        val ordered = segments.entries.sortedBy { it.key }+        val first = ordered.firstOrNull()?.value+        var charset = "utf-8"+        val allEncoded = ordered.all { it.value.second }+        val out = ByteArrayOutputStream()+        if (allEncoded) {+            // Concatenate before decoding: a multi-byte character may be+            // split across the segment boundary between its %XX bytes.+            val joined = StringBuilder()+            ordered.forEachIndexed { idx, entry ->+                if (idx == 0) {+                    val (cs, encoded) = splitRfc2231Charset(entry.value.first)+                    charset = cs+                    joined.append(encoded)+                } else {+                    joined.append(entry.value.first)+                }+            }+            out.write(percentDecodeBytes(joined.toString()))+        } else {+            ordered.forEachIndexed { idx, entry ->+                val (value, encoded) = entry.value+                if (idx == 0 && encoded) {+                    val (cs, rest) = splitRfc2231Charset(value)+                    charset = cs+                    out.write(percentDecodeBytes(rest))+                } else if (encoded) {+                    out.write(percentDecodeBytes(value))+                } else {+                    out.write(value.toByteArray(Charsets.ISO_8859_1))+                }+            }+            if (first?.second == false && charset == "utf-8") charset = "iso-8859-1"+        }+        return decodeCharset(out.toByteArray(), charset)+    }++    /** Split an RFC 2231 `charset'lang'value` prefix; no prefix means UTF-8 bytes. */+    private fun splitRfc2231Charset(value: String): Pair<String, String> {+        val firstQuote = value.indexOf('\'')+        val secondQuote = if (firstQuote == -1) -1 else value.indexOf('\'', firstQuote + 1)+        if (firstQuote <= 0 || secondQuote == -1) return "utf-8" to value+        return value.substring(0, firstQuote).ifBlank { "utf-8" } to value.substring(secondQuote + 1)+    }++    private fun percentDecodeBytes(encoded: String): ByteArray {+        val out = ByteArrayOutputStream()+        var i = 0+        while (i < encoded.length) {+            val hi = if (encoded[i] == '%' && i + 2 <= encoded.lastIndex) {+                Character.digit(encoded[i + 1], QP_HEX_RADIX)+            } else {+                -1+            }+            val lo = if (hi >= 0) Character.digit(encoded[i + 2], QP_HEX_RADIX) else -1+            if (hi >= 0 && lo >= 0) {+                out.write(hi * QP_HEX_RADIX + lo)+                i += QP_HEX_PAIR_LEN+            } else {+                out.write(encoded[i].code and 0xFF)+                i+++            }+        }+        return out.toByteArray()     }      private class HeaderParamParser(private val paramStr: String) {@@ -492,6 +601,8 @@ object MimeParser {         private var valSb = StringBuilder()         private var inKey = true         private var inQuotes = false+        private var quotedValue = false+        private var afterClosingQuote = false         private var currentKey = ""          fun parse() {@@ -501,7 +612,7 @@ object MimeParser {                 i++             }             if (!inKey && currentKey.isNotBlank()) {-                result[currentKey.trim()] = valSb.toString().trim().removeSurrounding("\"")+                result[currentKey.trim()] = finishValue()             }         } @@ -521,21 +632,36 @@ object MimeParser {         private fun parseValueChar(c: Char) {             if (!inQuotes && c == '"') {                 inQuotes = true+                quotedValue = true+                afterClosingQuote = false+                // Space between '=' and the opening quote is syntax, not value.+                if (valSb.isBlank()) valSb = StringBuilder()             } else if (inQuotes && c == '"') {                 inQuotes = false+                afterClosingQuote = true             } else if (!inQuotes && c == ';') {                 commitValue()+            } else if (afterClosingQuote && (c == ' ' || c == '\t')) {+                // Space between the closing quote and ';' is syntax too;+                // quoted content itself (incl. edge spaces a continuation+                // segment may end with) must survive verbatim.             } else {+                afterClosingQuote = false                 valSb.append(c)             }         } +        /** A quoted value is exact; only unquoted values carry syntax padding. */+        private fun finishValue(): String =+            if (quotedValue) valSb.toString() else valSb.toString().trim().removeSurrounding("\"")+         private fun commitValue() {-            val v = valSb.toString().trim().removeSurrounding("\"")-            if (currentKey.isNotBlank()) result[currentKey.trim()] = v+            if (currentKey.isNotBlank()) result[currentKey.trim()] = finishValue()             currentKey = ""             keySb = StringBuilder()             valSb = StringBuilder()+            quotedValue = false+            afterClosingQuote = false             inKey = true         }     }
email/src/test/java/com/vayunmathur/email/mime/MimeRfc2231Test.kt
diff --git a/email/src/test/java/com/vayunmathur/email/mime/MimeRfc2231Test.kt b/email/src/test/java/com/vayunmathur/email/mime/MimeRfc2231Test.ktnew file mode 100644index 0000000000..b5996ff4e3--- /dev/null+++ b/email/src/test/java/com/vayunmathur/email/mime/MimeRfc2231Test.kt@@ -0,0 +1,67 @@+package com.vayunmathur.email.mime++import com.vayunmathur.email.network.imap.MimeParser+import kotlin.test.Test+import kotlin.test.assertEquals++/**+ * RFC 2231 parameter encodings: the form MUAs use for non-ASCII and long+ * attachment filenames, where RFC 2047 encoding is not allowed inside a+ * parameter. Before the fix the parser keyed these as `filename*` /+ * `filename*0*`, so [MimeParser.DispositionInfo.filename] found nothing+ * and every such attachment was stored as "unnamed".+ */+class MimeRfc2231Test {++    @Test+    fun `single segment extended filename is charset and percent decoded`() {+        val disp = MimeParser.parseDisposition(+            "attachment; filename*=UTF-8''%E2%82%AC%20rates.pdf",+        )+        assertEquals("€ rates.pdf", disp?.filename)+    }++    @Test+    fun `extended continuations reassemble a split utf8 filename`() {+        val disp = MimeParser.parseDisposition(+            "attachment; filename*0*=UTF-8''%E2%82%AC%20rates; filename*1*=%20final.pdf",+        )+        assertEquals("€ rates final.pdf", disp?.filename)+    }++    @Test+    fun `plain continuations reassemble a long ascii filename`() {+        val disp = MimeParser.parseDisposition(+            "attachment; filename*0=\"quarterly results \"; filename*1=\"2026 final.pdf\"",+        )+        assertEquals("quarterly results 2026 final.pdf", disp?.filename)+    }++    @Test+    fun `extended content type name decodes too`() {+        val ct = MimeParser.parseContentType(+            "application/pdf; name*=UTF-8''caf%C3%A9%20menu.pdf",+        )+        assertEquals("café menu.pdf", ct.params["name"])+    }++    @Test+    fun `plain filename with a literal percent is untouched`() {+        val disp = MimeParser.parseDisposition(+            "attachment; filename=\"100% legit.pdf\"",+        )+        assertEquals("100% legit.pdf", disp?.filename)+    }++    @Test+    fun `parsed attachment carries the decoded rfc2231 filename`() {+        val raw = "Content-Type: multipart/mixed; boundary=m\r\n\r\n" ++            "--m\r\nContent-Type: application/pdf\r\n" ++            "Content-Disposition: attachment; filename*=UTF-8''%E2%82%AC%20rates.pdf\r\n\r\n12345\r\n" ++            "--m--\r\n"+        val root = MimeParser.parsePart(raw.toByteArray(Charsets.UTF_8), "")+        val (_, _, attachments) = MimeParser.collectBodyAndAttachments(root, 7L, "a@b", "INBOX")+        assertEquals(1, attachments.size)+        assertEquals("€ rates.pdf", attachments[0].fileName)+    }+}