securemail: decode real-world MIME so mail from Proton/Gmail is readable
- Commit
f5cf271d3fedc6059860034dbaad66b57277e171- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-02 04:28 UTC (1 month ago)
- Parents
6da6a7e
Mail from Proton showed up as a wall of base64 or =E2=80=94 soup with raw "Content-Type: text/html" headers in the body. parseMime() only understood the app's own composer output: it read single-line From/ Subject, ignored Content-Transfer-Encoding, and treated everything after the first blank line as text. Other providers send quoted-printable or base64 bodies, HTML-only or multipart/alternative trees, folded headers and RFC 2047 encoded-word subjects. parseMime() is now a small real MIME reader (still pure Kotlin for domain/, java.util.Base64 rather than android.util): - Headers are unfolded; Subject/From decode =?charset?B|Q?...?= words. - Bodies honour Content-Transfer-Encoding (quoted-printable incl. soft line breaks, base64) and the declared charset. - multipart/* is walked recursively, preferring text/plain, then nested multiparts, then text/html; HTML-only mail is reduced to readable text (style/script/head stripped, block tags -> newlines, common entities). - Our own composer format parses exactly as before. Proton's "encrypted" lock on that message refers to its own at-rest encryption: the captured message was plain text/plain quoted-printable (no PGP), and the server correctly flagged it unencrypted. Proton never requested our WKD key, so that is a separate issue (a cached "no key" result from before WKD was fixed). Verified: MimeCodecTest adds the real Proton QP reply (with a soft line break splitting an address), base64 HTML-only, multipart/alternative, encoded-word subject and the composer format (9 tests pass); full securemail unit tests, lint clean, detekt unchanged at 40.
Diff
securemail/src/main/java/com/vayunmathur/securemail/domain/mail/MimeCodec.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/domain/mail/MimeCodec.kt b/securemail/src/main/java/com/vayunmathur/securemail/domain/mail/MimeCodec.ktindex 1d76aa4b87..d36c8e3cb7 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/domain/mail/MimeCodec.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/domain/mail/MimeCodec.kt@@ -59,41 +59,146 @@ object MimeCodec { private const val ARMOR_BEGIN = "-----BEGIN PGP MESSAGE-----" /**- * Minimal parser for the MIME skeleton the composer emits (headers +- * trailing `--boundary--`). Returns (subject, body, from). The payload is- * already authenticated PGP plaintext at this point; this only splits it.+ * Parses a MIME message into (subject, body, from): our own composer's+ * text/plain, and whatever other providers send (Proton, Gmail): folded+ * headers, RFC 2047 encoded-words, quoted-printable/base64 bodies in any+ * charset, and multipart trees. Plain text is preferred; HTML-only mail is+ * reduced to readable text. */ fun parseMime(mime: String): Triple<String, String, String> {- val lines = mime.lines()- var from = ""- var subject = ""- var i = 0- while (i < lines.size && lines[i].isNotBlank()) {- val line = lines[i]- when {- line.startsWith("From:", ignoreCase = true) ->- from = line.substringAfter(':').trim()- line.startsWith("Subject:", ignoreCase = true) ->- subject = line.substringAfter(':').trim()+ val (headers, body) = splitEntity(mime)+ return Triple(+ decodeWords(headers["subject"].orEmpty()),+ readableBody(headers, body).trimEnd(),+ decodeWords(headers["from"].orEmpty()),+ )+ }++ /** Header map (lowercase names, unfolded values; first occurrence wins) + raw body. */+ private fun splitEntity(entity: String): Pair<Map<String, String>, String> {+ val text = entity.replace("\r\n", "\n")+ val end = text.indexOf("\n\n").takeIf { it >= 0 }+ val headerBlock = if (end == null) text else text.substring(0, end)+ val body = if (end == null) "" else text.substring(end + 2)+ val headers = mutableMapOf<String, String>()+ var name: String? = null+ val value = StringBuilder()+ fun flush() {+ name?.let { headers.putIfAbsent(it, value.toString().trim()) }+ }+ for (line in headerBlock.split("\n")) {+ if ((line.startsWith(" ") || line.startsWith("\t")) && name != null) {+ value.append(' ').append(line.trim())+ } else {+ flush()+ val colon = line.indexOf(':')+ name = if (colon > 0) line.substring(0, colon).trim().lowercase() else null+ value.setLength(0)+ if (colon > 0) value.append(line.substring(colon + 1)) }- i++ }- // Skip the blank line plus the multipart preamble (boundary markers and- // the Version part); the body is the last text block before --boundary--.- val body = StringBuilder()- var inBody = false- for (line in lines.drop(i)) {- if (line.startsWith("--maemail-")) {- inBody = false- continue+ flush()+ return headers to body+ }++ private fun readableBody(headers: Map<String, String>, body: String): String {+ val type = headers["content-type"].orEmpty()+ val mediaType = type.substringBefore(';').trim().lowercase().ifEmpty { "text/plain" }+ if (mediaType.startsWith("multipart/")) {+ val boundary = param(type, "boundary") ?: return body+ val parts = multipartParts(body, boundary).map { splitEntity(it) }+ fun typeOf(h: Map<String, String>) =+ h["content-type"].orEmpty().substringBefore(';').trim().lowercase().ifEmpty { "text/plain" }+ val chosen = parts.firstOrNull { typeOf(it.first) == "text/plain" }+ ?: parts.firstOrNull { typeOf(it.first).startsWith("multipart/") }+ ?: parts.firstOrNull { typeOf(it.first) == "text/html" }+ ?: return ""+ return readableBody(chosen.first, chosen.second)+ }+ val decoded = decodeTransfer(body, headers["content-transfer-encoding"], param(type, "charset"))+ return if (mediaType == "text/html") htmlToText(decoded) else decoded+ }++ private fun multipartParts(body: String, boundary: String): List<String> {+ val parts = mutableListOf<String>()+ var current: StringBuilder? = null+ for (line in body.split("\n")) {+ val trimmed = line.trimEnd()+ when (trimmed) {+ "--$boundary--" -> {+ current?.let { parts += it.toString() }+ return parts+ }+ "--$boundary" -> {+ current?.let { parts += it.toString() }+ current = StringBuilder()+ }+ else -> current?.append(line)?.append('\n') }- if (line.startsWith("Content-Type: text/plain", ignoreCase = true)) {- inBody = false // headers of the part follow; blank line starts text- continue+ }+ current?.let { parts += it.toString() }+ return parts+ }++ private fun param(headerValue: String, key: String): String? =+ headerValue.split(';').drop(1).map { it.trim() }+ .firstOrNull { it.lowercase().startsWith("$key=") }+ ?.substringAfter('=')?.trim()?.trim('"')++ private fun charsetOf(name: String?): java.nio.charset.Charset =+ runCatching { java.nio.charset.Charset.forName(name ?: "UTF-8") }.getOrDefault(Charsets.UTF_8)++ private fun decodeTransfer(body: String, encoding: String?, charset: String?): String =+ when (encoding?.trim()?.lowercase()) {+ "base64" -> runCatching {+ String(java.util.Base64.getMimeDecoder().decode(body.trim()), charsetOf(charset))+ }.getOrDefault(body)+ "quoted-printable" -> String(decodeQuotedPrintable(body, underscoreIsSpace = false), charsetOf(charset))+ else -> body+ }++ private fun decodeQuotedPrintable(text: String, underscoreIsSpace: Boolean): ByteArray {+ val out = java.io.ByteArrayOutputStream()+ val src = text.replace("=\n", "")+ var i = 0+ while (i < src.length) {+ val c = src[i]+ val hex = if (c == '=' && i + 2 < src.length) src.substring(i + 1, i + 3).toIntOrNull(16) else null+ when {+ hex != null -> { out.write(hex); i += 3 }+ c == '_' && underscoreIsSpace -> { out.write(' '.code); i++ }+ else -> { out.write(c.toString().toByteArray(Charsets.UTF_8)); i++ } }- if (inBody) body.appendLine(line)- if (line.isBlank()) inBody = true }- return Triple(subject, body.toString().trimEnd(), from)+ return out.toByteArray() }++ /** RFC 2047 encoded-words (`=?charset?B|Q?text?=`), e.g. non-ASCII subjects. */+ private fun decodeWords(value: String): String =+ Regex("""=\?([^?]+)\?([BbQq])\?([^?]*)\?=(\s+(?==\?))?""").replace(value) { m ->+ val (charset, enc, data) = m.destructured+ runCatching {+ val bytes = if (enc.equals("B", ignoreCase = true)) {+ java.util.Base64.getDecoder().decode(data)+ } else {+ decodeQuotedPrintable(data, underscoreIsSpace = true)+ }+ String(bytes, charsetOf(charset))+ }.getOrDefault(m.value)+ }++ private fun htmlToText(html: String): String = html+ .replace(Regex("(?is)<(style|script|head)[^>]*>.*?</\\1>"), "")+ .replace(Regex("(?i)<br\\s*/?>"), "\n")+ .replace(Regex("(?i)</(p|div|tr|li|h[1-6]|blockquote)>"), "\n")+ .replace(Regex("<[^>]+>"), "")+ .replace(" ", " ").replace("<", "<").replace(">", ">")+ .replace(""", "\"").replace("'", "'").replace("'", "'")+ .replace(Regex("&#(\\d+);")) { m ->+ m.groupValues[1].toIntOrNull()?.let { String(Character.toChars(it)) } ?: m.value+ }+ .replace("&", "&")+ .replace(Regex("[ \\t]+\n"), "\n")+ .replace(Regex("\n{3,}"), "\n\n")+ .trim() }
securemail/src/test/java/com/vayunmathur/securemail/domain/mail/MimeCodecTest.kt
diff --git a/securemail/src/test/java/com/vayunmathur/securemail/domain/mail/MimeCodecTest.kt b/securemail/src/test/java/com/vayunmathur/securemail/domain/mail/MimeCodecTest.ktindex 8b64a43f97..46f3c95e2a 100644--- a/securemail/src/test/java/com/vayunmathur/securemail/domain/mail/MimeCodecTest.kt+++ b/securemail/src/test/java/com/vayunmathur/securemail/domain/mail/MimeCodecTest.kt@@ -55,4 +55,64 @@ class MimeCodecTest { fun nonPgpMimeIsRejected() { assertNull(MimeCodec.extractPgpPayloadB64("Content-Type: text/plain\r\n\r\nhello\r\n".toByteArray())) }++ @Test+ fun protonQuotedPrintableReply() {+ val (subject, body, from) = MimeCodec.parseMime(+ "From: vayun12 <[email protected]>\r\n" ++ "Subject: Re: H2\r\n" ++ "MIME-Version: 1.0\r\n" ++ "Content-Type: text/plain; charset=utf-8\r\n" ++ "Content-Transfer-Encoding: quoted-printable\r\n" ++ "\r\n" ++ "hello there =E2=80=94 caf=C3=A9\r\n" ++ "\r\n" ++ "On Sunday, [email protected] <vayun1234=\r\n" ++ "[email protected]> wrote:\r\n",+ )+ assertEquals("Re: H2", subject)+ assertEquals("vayun12 <[email protected]>", from)+ assertEquals("hello there \u2014 caf\u00e9\n\nOn Sunday, [email protected] <[email protected]> wrote:", body)+ }++ @Test+ fun base64HtmlOnlyBecomesText() {+ val html = "<html><head><style>p{}</style></head><body><p>Hi there</p><div>2 < 3 & ok</div></body></html>"+ val b64 = java.util.Base64.getMimeEncoder().encodeToString(html.toByteArray())+ val (_, body, _) = MimeCodec.parseMime(+ "Subject: x\r\nContent-Type: text/html; charset=utf-8\r\nContent-Transfer-Encoding: base64\r\n\r\n$b64\r\n",+ )+ assertEquals("Hi there\n2 < 3 & ok", body)+ }++ @Test+ fun multipartAlternativePrefersPlainText() {+ val (_, body, _) = MimeCodec.parseMime(+ "Subject: x\r\n" ++ "Content-Type: multipart/alternative;\r\n boundary=\"b1\"\r\n" ++ "\r\n" ++ "--b1\r\nContent-Type: text/html\r\n\r\n<p>html version</p>\r\n" ++ "--b1\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nplain version\r\n" ++ "--b1--\r\n",+ )+ assertEquals("plain version", body)+ }++ @Test+ fun encodedWordSubject() {+ val (subject, _, _) = MimeCodec.parseMime(+ "Subject: =?UTF-8?B?Q2Fmw6k=?= =?utf-8?Q?_ol=C3=A9?=\r\nContent-Type: text/plain\r\n\r\nx\r\n",+ )+ assertEquals("Caf\u00e9 ol\u00e9", subject)+ }++ @Test+ fun ownComposerFormat() {+ val (subject, body, from) = MimeCodec.parseMime(+ "From: [email protected]\r\nSubject: Hello\r\nMIME-Version: 1.0\r\n" ++ "Content-Type: text/plain; charset=utf-8; protected-headers=\"v1\"\r\n" ++ "Content-Transfer-Encoding: 8bit\r\n\r\nline one\r\nline two\r\n",+ )+ assertEquals(Triple("Hello", "line one\nline two", "[email protected]"), Triple(subject, body, from))+ } }