This is an automated email from the ASF dual-hosted git repository. chibenwa pushed a commit to branch master in repository https://gitbox.apache.org/repos/asf/james-mime4j.git
commit faa30d2714ab087c9d708cf2cd3438ccb4e08dbe Author: Benoit TELLIER <[email protected]> AuthorDate: Tue Dec 1 19:44:56 2026 +0100 [PERF] DecoderUtil: decode a well-formed encoded word without the stream pipeline Each encoded word built a QuotedPrintableInputStream / Base64InputStream (ThreadLocal recycler lookups, recycled buffers), copied the text to bytes and again to expand '_', drained into a trimmed array, then into a ByteArrayOutputStream copied once more by toByteArray(): for a 20-60 byte word, about as much as the decoding (~30% of decodeEncodedWords). A well-formed Q word (printable US-ASCII but blanks, '_', '=' + two hex digits) and a well-formed B word (groups of four base64 chars, a final "=" / "==") are now decoded straight from the String into an unsynchronized byte sink, turned into a String without a copy. Any other text keeps the stream path, its lenient treatment and its DecodeMonitor warnings. A body without "=?" allocates nothing. --- .../org/apache/james/mime4j/codec/DecoderUtil.java | 213 +++++++++++++++++---- .../apache/james/mime4j/codec/DecoderUtilTest.java | 67 +++++++ 2 files changed, 244 insertions(+), 36 deletions(-) diff --git a/core/src/main/java/org/apache/james/mime4j/codec/DecoderUtil.java b/core/src/main/java/org/apache/james/mime4j/codec/DecoderUtil.java index 5a5bd70d..4867a172 100644 --- a/core/src/main/java/org/apache/james/mime4j/codec/DecoderUtil.java +++ b/core/src/main/java/org/apache/james/mime4j/codec/DecoderUtil.java @@ -20,7 +20,6 @@ package org.apache.james.mime4j.codec; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; @@ -52,6 +51,144 @@ public class DecoderUtil { return br; } + private static final int[] BASE64_DECODE = new int[128]; + + static { + Arrays.fill(BASE64_DECODE, -1); + for (int i = 0; i < Base64OutputStream.BASE64_TABLE.length; i++) { + BASE64_DECODE[Base64OutputStream.BASE64_TABLE[i]] = i; + } + } + + /** + * The decoded bytes of the adjacent encoded words of a same charset. Unlike a + * ByteArrayOutputStream, it is not synchronized and its content is turned into a String + * without being copied first. + */ + private static final class ByteSink { + private byte[] buf = new byte[64]; + private int len = 0; + + void ensure(int extra) { + if (len + extra > buf.length) { + buf = Arrays.copyOf(buf, Math.max(buf.length * 2, len + extra)); + } + } + + void write(byte[] bytes) { + ensure(bytes.length); + System.arraycopy(bytes, 0, buf, len, bytes.length); + len += bytes.length; + } + + String drainToString(Charset charset) { + String s = new String(buf, 0, len, charset); + len = 0; + return s; + } + } + + /** + * Decodes a well-formed 'Q' encoded text straight into <code>out</code>: printable US-ASCII + * but blanks, '_' for a space, '=' followed by two hex digits. Anything else (blanks, line + * breaks, controls, non US-ASCII chars, a malformed or truncated '=') returns false without + * writing anything, and is left to the stream decoder, its lenient treatment and its + * DecodeMonitor warnings. On the text accepted here, both decode the same bytes. + */ + private static boolean decodeQInto(String text, ByteSink out) { + final int n = text.length(); + int decodedLen = 0; + for (int i = 0; i < n; i++) { + char c = text.charAt(i); + if (c == '=') { + if (i + 2 >= n || hexValue(text.charAt(i + 1)) < 0 || hexValue(text.charAt(i + 2)) < 0) { + return false; + } + i += 2; + } else if (c <= ' ' || c >= 0x7F) { + return false; + } + decodedLen++; + } + out.ensure(decodedLen); + final byte[] buf = out.buf; + int j = out.len; + for (int i = 0; i < n; i++) { + char c = text.charAt(i); + if (c == '=') { + buf[j++] = (byte) ((hexValue(text.charAt(i + 1)) << 4) | hexValue(text.charAt(i + 2))); + i += 2; + } else if (c == '_') { + buf[j++] = ' '; + } else { + buf[j++] = (byte) c; + } + } + out.len = j; + return true; + } + + private static int hexValue(char c) { + if (c >= '0' && c <= '9') { + return c - '0'; + } else if (c >= 'A' && c <= 'F') { + return c - 'A' + 10; + } else if (c >= 'a' && c <= 'f') { + return c - 'a' + 10; + } + return -1; + } + + /** + * Decodes a well-formed 'B' encoded text straight into <code>out</code>: groups of four + * base64 chars, the last one possibly ending with "=" or "==". Anything else (a length that + * is not a multiple of four, blanks, line breaks, chars out of the alphabet, a misplaced pad) + * returns false without writing anything, and is left to the stream decoder. As the stream + * decoder, the unused bits of a padded group are ignored. + */ + private static boolean decodeBInto(String text, ByteSink out) { + final int n = text.length(); + if (n == 0 || (n & 3) != 0) { + return false; + } + int pad = 0; + if (text.charAt(n - 1) == '=') { + pad = text.charAt(n - 2) == '=' ? 2 : 1; + } + for (int i = 0; i < n - pad; i++) { + char c = text.charAt(i); + if (c >= 128 || BASE64_DECODE[c] < 0) { + return false; + } + } + out.ensure(n / 4 * 3 - pad); + final byte[] buf = out.buf; + int j = out.len; + final int fullEnd = pad == 0 ? n : n - 4; + int i = 0; + for (; i < fullEnd; i += 4) { + int data = BASE64_DECODE[text.charAt(i)] << 18 + | BASE64_DECODE[text.charAt(i + 1)] << 12 + | BASE64_DECODE[text.charAt(i + 2)] << 6 + | BASE64_DECODE[text.charAt(i + 3)]; + buf[j++] = (byte) (data >>> 16); + buf[j++] = (byte) (data >>> 8); + buf[j++] = (byte) data; + } + if (pad == 2) { + int data = BASE64_DECODE[text.charAt(i)] << 6 | BASE64_DECODE[text.charAt(i + 1)]; + buf[j++] = (byte) (data >>> 4); + } else if (pad == 1) { + int data = BASE64_DECODE[text.charAt(i)] << 12 + | BASE64_DECODE[text.charAt(i + 1)] << 6 + | BASE64_DECODE[text.charAt(i + 2)]; + buf[j++] = (byte) (data >>> 10); + buf[j++] = (byte) (data >>> 2); + } + out.len = j; + return true; + } + /** * Decodes quoted-printable encoded data. * @@ -126,11 +263,15 @@ public class DecoderUtil { */ static String decodeB(String encodedText, String charset, DecodeMonitor monitor) throws UnsupportedEncodingException { - byte[] decodedBytes = decodeBase64(encodedText, monitor); + byte[] decodedBytes = decodeByteAryB(encodedText, monitor); return new String(decodedBytes, charset); } static byte[] decodeByteAryB(String encodedText, DecodeMonitor monitor) throws UnsupportedEncodingException { + ByteSink sink = new ByteSink(); + if (decodeBInto(encodedText, sink)) { + return Arrays.copyOf(sink.buf, sink.len); + } return decodeBase64(encodedText, monitor); } @@ -146,11 +287,15 @@ public class DecoderUtil { */ static String decodeQ(String encodedText, String charset, DecodeMonitor monitor) throws UnsupportedEncodingException { - byte[] decodedBytes = decodeQuotedPrintable(replaceUnderscores(encodedText), monitor); + byte[] decodedBytes = decodeByteAryQ(encodedText, monitor); return new String(decodedBytes, charset); } static byte[] decodeByteAryQ(String encodedText, DecodeMonitor monitor) throws UnsupportedEncodingException { + ByteSink sink = new ByteSink(); + if (decodeQInto(encodedText, sink)) { + return Arrays.copyOf(sink.buf, sink.len); + } return decodeQuotedPrintable(replaceUnderscores(encodedText), monitor); } @@ -225,8 +370,13 @@ public class DecoderUtil { monitor = DecodeMonitor.SILENT; } - ByteArrayOutputStream out = new ByteArrayOutputStream(); - StringBuilder sb = new StringBuilder(); + if (body.indexOf("=?") < 0) { + // no encoded word: nothing to allocate + return body; + } + + ByteSink out = new ByteSink(); + StringBuilder sb = new StringBuilder(body.length()); int position = 0; String mimeCharset =""; String encoding =""; @@ -282,18 +432,8 @@ public class DecoderUtil { position = encodedTextEnd + 2; continue; } - byte []decoded; - - decoded = tryDecodeEncodedWord(mimeCurCharset, curEncoding, encodedText, monitor, fallback, charsetOverrides); - if (decoded != null) { - if (0 < decoded.length) { - try { - out.write(decoded); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - } else { + if (!tryDecodeEncodedWord(mimeCurCharset, curEncoding, encodedText, monitor, fallback, + charsetOverrides, out)) { sb.append(body, startPattern, encodedTextEnd + 2); } position = encodedTextEnd + 2; @@ -304,55 +444,56 @@ public class DecoderUtil { return sb.toString(); } - private static void appendStringBuffer(Charset fallback, Map<Charset, Charset> charsetOverrides, ByteArrayOutputStream out, StringBuilder sb, String mimeCharset) { - if (0 < out.size()) { - byte[] byTemp = out.toByteArray(); + private static void appendStringBuffer(Charset fallback, Map<Charset, Charset> charsetOverrides, ByteSink out, StringBuilder sb, String mimeCharset) { + if (0 < out.len) { Charset charset = lookupCharset(mimeCharset, fallback, charsetOverrides); - sb.append(new String(byTemp, charset)); - out.reset(); + sb.append(out.drainToString(charset)); } } - // return null on error - private static byte[] tryDecodeEncodedWord( + // Writes the decoded bytes into out; returns false on error, out left unchanged + private static boolean tryDecodeEncodedWord( final String mimeCharset, final String encoding, final String encodedText, final DecodeMonitor monitor, final Charset fallback, - final Map<Charset, Charset> charsetOverrides) { + final Map<Charset, Charset> charsetOverrides, + final ByteSink out) { Charset charset = lookupCharset(mimeCharset, fallback, charsetOverrides); if (charset == null) { monitor(monitor, mimeCharset, encoding, encodedText, "leaving word encoded", "Mime charser '", mimeCharset, "' doesn't have a corresponding Java charset"); - return null; + return false; } if (encodedText.length() == 0) { monitor(monitor, mimeCharset, encoding, encodedText, "leaving word encoded", "Missing encoded text in encoded word"); - return null; + return false; } try { if (encoding.equalsIgnoreCase("Q")) { - return decodeByteAryQ(encodedText, monitor); + // well-formed words skip the stream pipeline; the others keep its lenient treatment + if (!decodeQInto(encodedText, out)) { + out.write(decodeQuotedPrintable(replaceUnderscores(encodedText), monitor)); + } + return true; } else if (encoding.equalsIgnoreCase("B")) { - return decodeByteAryB(encodedText, monitor); + if (!decodeBInto(encodedText, out)) { + out.write(decodeBase64(encodedText, monitor)); + } + return true; } else { monitor(monitor, mimeCharset, encoding, encodedText, "leaving word encoded", "Warning: Unknown encoding in encoded word"); - return null; + return false; } - } catch (UnsupportedEncodingException e) { - // should not happen because of isDecodingSupported check above - monitor(monitor, mimeCharset, encoding, encodedText, "leaving word encoded", - "Unsupported encoding (", e.getMessage(), ") in encoded word"); - return null; } catch (RuntimeException e) { monitor(monitor, mimeCharset, encoding, encodedText, "leaving word encoded", "Could not decode (", e.getMessage(), ") encoded word"); - return null; + return false; } } diff --git a/core/src/test/java/org/apache/james/mime4j/codec/DecoderUtilTest.java b/core/src/test/java/org/apache/james/mime4j/codec/DecoderUtilTest.java index 816ab944..204f742c 100644 --- a/core/src/test/java/org/apache/james/mime4j/codec/DecoderUtilTest.java +++ b/core/src/test/java/org/apache/james/mime4j/codec/DecoderUtilTest.java @@ -22,9 +22,15 @@ package org.apache.james.mime4j.codec; import org.junit.Assert; import org.junit.Test; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.util.HashMap; +import java.util.Random; public class DecoderUtilTest { @@ -234,4 +240,65 @@ public class DecoderUtilTest { DecoderUtil.decodeEncodedWords(input, DecodeMonitor.SILENT, null), DecoderUtil.decodeEncodedWords(input, (DecodeMonitor) null, null)); } + + // The fast path of well-formed words must decode the bytes the stream decoders decode + @Test + public void decodeByteAryQShouldMatchTheStreamDecoder() throws IOException { + Random random = new Random(42); + String alphabet = "=_?aZ09fFgG \t\r\n!~\u007f\u00e9"; + for (int round = 0; round < 20000; round++) { + String text = randomText(random, alphabet + "=4e=C3=a9"); + byte[] expected = drain(new QuotedPrintableInputStream( + new ByteArrayInputStream(text.replace("_", "=20").getBytes(StandardCharsets.US_ASCII)), DecodeMonitor.SILENT)); + Assert.assertArrayEquals(text, expected, DecoderUtil.decodeByteAryQ(text, DecodeMonitor.SILENT)); + } + } + + @Test + public void decodeByteAryBShouldMatchTheStreamDecoder() throws IOException { + Random random = new Random(42); + String alphabet = "ABCXYZabxyz0189+/==== \r\n-_.\u00e9"; + for (int round = 0; round < 20000; round++) { + String text = randomText(random, alphabet); + byte[] expected = drain(new Base64InputStream( + new ByteArrayInputStream(text.getBytes(StandardCharsets.US_ASCII)), DecodeMonitor.SILENT)); + Assert.assertArrayEquals(text, expected, DecoderUtil.decodeByteAryB(text, DecodeMonitor.SILENT)); + } + } + + @Test + public void decodeEncodedWordsShouldDecodeWellFormedPaddedBase64() { + Assert.assertEquals("a", DecoderUtil.decodeEncodedWords("=?us-ascii?B?YQ==?=", DecodeMonitor.STRICT)); + Assert.assertEquals("ab", DecoderUtil.decodeEncodedWords("=?us-ascii?B?YWI=?=", DecodeMonitor.STRICT)); + Assert.assertEquals("abc", DecoderUtil.decodeEncodedWords("=?us-ascii?B?YWJj?=", DecodeMonitor.STRICT)); + } + + @Test + public void decodeEncodedWordsShouldStillWarnOnMalformedQ() { + Assert.assertThrows(IllegalArgumentException.class, + () -> DecoderUtil.decodeEncodedWords("=?us-ascii?Q?a\rb?=", DecodeMonitor.STRICT)); + Assert.assertThrows(IllegalArgumentException.class, + () -> DecoderUtil.decodeEncodedWords("=?us-ascii?B?YWJ?=", DecodeMonitor.STRICT)); + } + + private static String randomText(Random random, String alphabet) { + int length = random.nextInt(13); + StringBuilder sb = new StringBuilder(length); + for (int i = 0; i < length; i++) { + sb.append(alphabet.charAt(random.nextInt(alphabet.length()))); + } + return sb.toString(); + } + + private static byte[] drain(InputStream is) throws IOException { + try (InputStream in = is) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] buf = new byte[64]; + int n; + while ((n = in.read(buf)) != -1) { + out.write(buf, 0, n); + } + return out.toByteArray(); + } + } } --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
