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 4099a687e87733cb610fb30b87840427682994e3 Author: Benoit TELLIER <[email protected]> AuthorDate: Sat Nov 21 20:17:02 2026 +0100 [FIX] Fields: a Content-Type or Content-Disposition too long for the default reader is rejected EncoderUtil#encodeHeaderParameter makes each line of a parameter fit, splitting a long value into RFC 2231 sections, but nothing bounds their sum: a non-ASCII filename of 1500 characters became 133 percent-encoded sections, a field over 10000 bytes. MimeTokenStream with MimeConfig.DEFAULT then stops on MaxHeaderLengthLimitException, and the rest of the header and the body are lost. The Fields builders that encode parameters now throw an IllegalArgumentException when the field, folded as written, is longer than the maximum header length of MimeConfig.DEFAULT, measured as the readers measure it. The longest accepted field is read back. --- .../java/org/apache/james/mime4j/field/Fields.java | 44 ++++++++- .../mime4j/internal/AbstractEntityBuilder.java | 8 ++ .../field/FieldsDefaultMaxHeaderLenTest.java | 102 +++++++++++++++++++++ 3 files changed, 150 insertions(+), 4 deletions(-) diff --git a/dom/src/main/java/org/apache/james/mime4j/field/Fields.java b/dom/src/main/java/org/apache/james/mime4j/field/Fields.java index 3881a98e..2790db54 100644 --- a/dom/src/main/java/org/apache/james/mime4j/field/Fields.java +++ b/dom/src/main/java/org/apache/james/mime4j/field/Fields.java @@ -45,8 +45,10 @@ import org.apache.james.mime4j.dom.field.ParsedField; import org.apache.james.mime4j.dom.field.UnstructuredField; import org.apache.james.mime4j.field.address.AddressFormatter; import org.apache.james.mime4j.stream.Field; +import org.apache.james.mime4j.stream.MimeConfig; import org.apache.james.mime4j.stream.NameValuePair; import org.apache.james.mime4j.stream.RawField; +import org.apache.james.mime4j.util.ByteSequence; import org.apache.james.mime4j.util.MimeUtil; /** @@ -90,6 +92,8 @@ public class Fields { * map containing content-type parameters such as * <code>"boundary"</code>. * @return the newly created <i>Content-Type</i> field. + * @throws IllegalArgumentException if the field would be longer than the + * default maximum header length of the readers ({@link MimeConfig#DEFAULT}). */ public static ContentTypeField contentType(String mimeType, Map<String, String> parameters) { @@ -107,7 +111,7 @@ public class Fields { sb.append(EncoderUtil.encodeHeaderParameter(entry.getKey(), entry.getValue(), false)); } - String contentType = sb.toString(); + String contentType = checkDefaultMaxHeaderLen(FieldName.CONTENT_TYPE, sb.toString()); return contentType(contentType); } } @@ -122,6 +126,8 @@ public class Fields { * @param parameters * list of content-type parameter name/value pairs. * @return the newly created <i>Content-Type</i> field. + * @throws IllegalArgumentException if the field would be longer than the + * default maximum header length of the readers ({@link MimeConfig#DEFAULT}). */ public static ContentTypeField contentType(String mimeType, Iterable<NameValuePair> parameters) { @@ -140,7 +146,7 @@ public class Fields { // no Content-Type parser decodes RFC 2231 sections: a value too long for a line is rejected sb.append(EncoderUtil.encodeHeaderParameter(name, value != null ? value : "", false)); } - String contentType = sb.toString(); + String contentType = checkDefaultMaxHeaderLen(FieldName.CONTENT_TYPE, sb.toString()); return contentType(contentType); } } @@ -202,6 +208,8 @@ public class Fields { * map containing disposition parameters such as * <code>"filename"</code>. * @return the newly created <i>Content-Disposition</i> field. + * @throws IllegalArgumentException if the field would be longer than the + * default maximum header length of the readers ({@link MimeConfig#DEFAULT}). */ public static ContentDispositionField contentDisposition( String dispositionType, Map<String, String> parameters) { @@ -218,7 +226,7 @@ public class Fields { sb.append(EncoderUtil.encodeHeaderParameter(entry.getKey(), entry.getValue(), true)); } - String contentDisposition = sb.toString(); + String contentDisposition = checkDefaultMaxHeaderLen(FieldName.CONTENT_DISPOSITION, sb.toString()); return contentDisposition(contentDisposition); } } @@ -233,6 +241,8 @@ public class Fields { * @param parameters * list of disposition parameter name/value pairs. * @return the newly created <i>Content-Disposition</i> field. + * @throws IllegalArgumentException if the field would be longer than the + * default maximum header length of the readers ({@link MimeConfig#DEFAULT}). */ public static ContentDispositionField contentDisposition( String dispositionType, Iterable<NameValuePair> parameters) { @@ -250,7 +260,7 @@ public class Fields { String value = param.getValue(); sb.append(EncoderUtil.encodeHeaderParameter(name, value != null ? value : "", true)); } - String contentDisposition = sb.toString(); + String contentDisposition = checkDefaultMaxHeaderLen(FieldName.CONTENT_DISPOSITION, sb.toString()); return contentDisposition(contentDisposition); } } @@ -709,6 +719,32 @@ public class Fields { } + /** + * The parameters of a field are encoded so that each line fits (RFC 2231 sections for a long + * value), but nothing bounds their sum: a field longer than {@link MimeConfig#getMaxHeaderLen()} + * of {@link MimeConfig#DEFAULT} is rejected by the readers with the default configuration, which + * then lose the rest of the message. It is measured once folded as written, each line end + * counted as one byte, as by the readers. + * + * @throws IllegalArgumentException if the written field would be longer + */ + private static String checkDefaultMaxHeaderLen(String fieldName, String body) { + ByteSequence raw = new RawField(fieldName, body).getSafeRaw(); + // the line end after the last line + int measured = raw.length() + 1; + for (int i = 0; i + 1 < raw.length(); i++) { + if (raw.byteAt(i) == '\r' && raw.byteAt(i + 1) == '\n') { + measured--; + } + } + int max = MimeConfig.DEFAULT.getMaxHeaderLen(); + if (max > 0 && measured > max) { + throw new IllegalArgumentException(fieldName + " field too long (" + measured + + " bytes) to be read back with the default maximum header length (" + max + ")"); + } + return body; + } + private static <F extends ParsedField> F parse(FieldParser<F> parser, String fieldName, String fieldBody) { RawField rawField = new RawField(fieldName, fieldBody); diff --git a/dom/src/main/java/org/apache/james/mime4j/internal/AbstractEntityBuilder.java b/dom/src/main/java/org/apache/james/mime4j/internal/AbstractEntityBuilder.java index ef987690..2c8d0ffa 100644 --- a/dom/src/main/java/org/apache/james/mime4j/internal/AbstractEntityBuilder.java +++ b/dom/src/main/java/org/apache/james/mime4j/internal/AbstractEntityBuilder.java @@ -277,6 +277,8 @@ public abstract class AbstractEntityBuilder { * @param mimeType MIME type of this message * the MIME type to use. * @param parameters content type parameters to use. + * @throws IllegalArgumentException if the field would be longer than the default maximum + * header length of the readers, see {@link Fields}. */ public AbstractEntityBuilder setContentType(String mimeType, NameValuePair... parameters) { if (mimeType == null) { @@ -352,6 +354,8 @@ public abstract class AbstractEntityBuilder { * @param filename * filename parameter value or <code>null</code> if the * parameter should not be included. + * @throws IllegalArgumentException if the field would be longer than the default maximum + * header length of the readers, see {@link Fields}. */ public AbstractEntityBuilder setContentDisposition(String dispositionType, String filename) { if (dispositionType == null) { @@ -376,6 +380,8 @@ public abstract class AbstractEntityBuilder { * @param size * size parameter value or <code>-1</code> if the parameter * should not be included. + * @throws IllegalArgumentException if the field would be longer than the default maximum + * header length of the readers, see {@link Fields}. */ public AbstractEntityBuilder setContentDisposition(String dispositionType, String filename, long size) { @@ -409,6 +415,8 @@ public abstract class AbstractEntityBuilder { * @param readDate * read-date parameter value or <code>null</code> if the * parameter should not be included. + * @throws IllegalArgumentException if the field would be longer than the default maximum + * header length of the readers, see {@link Fields}. */ public AbstractEntityBuilder setContentDisposition(String dispositionType, String filename, long size, Date creationDate, Date modificationDate, Date readDate) { diff --git a/dom/src/test/java/org/apache/james/mime4j/field/FieldsDefaultMaxHeaderLenTest.java b/dom/src/test/java/org/apache/james/mime4j/field/FieldsDefaultMaxHeaderLenTest.java new file mode 100644 index 00000000..e2c4c254 --- /dev/null +++ b/dom/src/test/java/org/apache/james/mime4j/field/FieldsDefaultMaxHeaderLenTest.java @@ -0,0 +1,102 @@ +/**************************************************************** + * Licensed to the Apache Software Foundation (ASF) under one * + * or more contributor license agreements. See the NOTICE file * + * distributed with this work for additional information * + * regarding copyright ownership. The ASF licenses this file * + * to you under the Apache License, Version 2.0 (the * + * "License"); you may not use this file except in compliance * + * with the License. You may obtain a copy of the License at * + * * + * http://www.apache.org/licenses/LICENSE-2.0 * + * * + * Unless required by applicable law or agreed to in writing, * + * software distributed under the License is distributed on an * + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * + * KIND, either express or implied. See the License for the * + * specific language governing permissions and limitations * + * under the License. * + ****************************************************************/ + +package org.apache.james.mime4j.field; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.Collections; + +import org.apache.james.mime4j.dom.Message; +import org.apache.james.mime4j.dom.field.ContentDispositionField; +import org.apache.james.mime4j.dom.field.ContentTypeField; +import org.apache.james.mime4j.message.DefaultMessageBuilder; +import org.apache.james.mime4j.message.DefaultMessageWriter; +import org.apache.james.mime4j.stream.NameValuePair; +import org.junit.Test; + +public class FieldsDefaultMaxHeaderLenTest { + + private static String repeat(char c, int count) { + StringBuilder sb = new StringBuilder(count); + for (int i = 0; i < count; i++) { + sb.append(c); + } + return sb.toString(); + } + + private static Message writeAndRead(ContentDispositionField disposition) throws Exception { + Message message = Message.Builder.of() + .setField(disposition) + .setField(Fields.subject("sentinel")) + .setBody("SENTINEL-BODY", StandardCharsets.US_ASCII) + .build(); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + new DefaultMessageWriter().writeMessage(message, out); + return new DefaultMessageBuilder().parseMessage(new ByteArrayInputStream(out.toByteArray())); + } + + @Test + public void longNonAsciiFilenameShouldBeRejectedRatherThanWrittenUnreadable() { + String name = repeat('é', 1500); + + assertThatThrownBy(() -> Fields.contentDisposition("attachment", name)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> Fields.contentDisposition("attachment", + Collections.singletonList(new NameValuePair("filename", name)))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + public void longestAcceptedFilenameShouldBeReadBackWithTheDefaultConfig() throws Exception { + int longest = 0; + for (int length = 1000; length < 20000; length++) { + try { + Fields.contentDisposition("attachment", repeat('é', length)); + longest = length; + } catch (IllegalArgumentException e) { + break; + } + } + assertThat(longest).isGreaterThan(1000); + String name = repeat('é', longest); + + Message parsed = writeAndRead(Fields.contentDisposition("attachment", name)); + + assertThat(((ContentDispositionField) parsed.getHeader().getField("Content-Disposition")).getFilename()).isEqualTo(name); + assertThat(parsed.getSubject()).isEqualTo("sentinel"); + } + + @Test + public void longContentTypeParameterShouldBeRejected() { + String value = repeat('a', 900) + " " + repeat('b', 900); + StringBuilder many = new StringBuilder(); + for (int i = 0; i < 6; i++) { + many.append(value).append(' '); + } + assertThatThrownBy(() -> Fields.contentType("text/plain", Collections.singletonMap("x", many.toString()))) + .isInstanceOf(IllegalArgumentException.class); + ContentTypeField fine = Fields.contentType("text/plain", Collections.singletonMap("x", value)); + assertThat(fine.getParameter("x")).isEqualTo(value); + } +} --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
