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 89646b6a7cd5cd8d3e8bcfd0908a56ec3f63e905
Author: Benoit TELLIER <[email protected]>
AuthorDate: Sat Nov 21 20:13:22 2026 +0100

    [FIX] DateTimeFieldLenientImpl: a comment between the tokens of a date 
reads as one space
    
    RFC 5322 allows CFWS between the tokens of a date, and the strict
    parser reads "09:55:06 (c) -0600" or "2:5()EST" with their zone. The
    lenient parser only removed comments around the colons of the time:
    its zone sections read one optional space, so a zone after a comment
    was not read, and zoneLeftUnread tolerated the "(": the date was read
    as GMT, off by the zone offset.
    
    A run of blanks and comments between two tokens now reads as one
    space, and the comments around the colons of the time are removed
    the same way: nested comments and quoted pairs included
    ("09:55((c)):06 -0600" lost its seconds and zone). The end of each
    comment is found once, so the normalization stays linear. The fast
    path takes a trailing comment only when the value ends with it: a
    text after it ("(c)0", "(a) -0600 (b)") is left to the formatter,
    which now sees it.
---
 .../mime4j/field/DateTimeFieldLenientImpl.java     | 122 +++++++++++++++++----
 .../field/DateTimeFieldLenientFastPathTest.java    |   2 +-
 .../mime4j/field/LenientDateTimeFieldTest.java     |  42 ++++++-
 3 files changed, 143 insertions(+), 23 deletions(-)

diff --git 
a/dom/src/main/java/org/apache/james/mime4j/field/DateTimeFieldLenientImpl.java 
b/dom/src/main/java/org/apache/james/mime4j/field/DateTimeFieldLenientImpl.java
index 6ca03670..4ce8c534 100644
--- 
a/dom/src/main/java/org/apache/james/mime4j/field/DateTimeFieldLenientImpl.java
+++ 
b/dom/src/main/java/org/apache/james/mime4j/field/DateTimeFieldLenientImpl.java
@@ -37,6 +37,7 @@ import java.time.format.DateTimeFormatter;
 import java.time.format.DateTimeFormatterBuilder;
 import java.time.format.ResolverStyle;
 import java.time.format.SignStyle;
+import java.util.Arrays;
 import java.util.Date;
 import java.util.HashMap;
 import java.util.Locale;
@@ -197,7 +198,7 @@ public class DateTimeFieldLenientImpl extends AbstractField 
implements DateTimeF
         }
         try {
             // RFC 5322 FWS: any run of white space reads as one space
-            String normalized = 
signUnsignedOffset(normalizeShortYear(removeCfwsAroundTimeColons(collapseWhiteSpace(text))));
+            String normalized = 
signUnsignedOffset(normalizeShortYear(removeCommentsBetweenTokens(removeCfwsAroundTimeColons(collapseWhiteSpace(text)))));
             ParsePosition position = new ParsePosition(0);
             Instant instant = Instant.from(RFC_5322.parse(normalized, 
position));
             if (zoneLeftUnread(normalized, position.getIndex())) {
@@ -324,8 +325,9 @@ public class DateTimeFieldLenientImpl extends AbstractField 
implements DateTimeF
         }
         p += 5;
 
-        // Then the end of the value, or a comment " (UTC)" that RFC_5322 does 
not read either
-        return p == s.length() || (isChar(s, p, ' ') && isChar(s, p + 1, '('));
+        // Then the end of the value, or a comment " (UTC)" that RFC_5322 does 
not read either: a
+        // text after it ("(c)0", "(a) -0600 (b)") is left to RFC_5322
+        return p == s.length() || (isChar(s, p, ' ') && isChar(s, p + 1, '(') 
&& commentEnd(s, p + 1) == s.length());
     }
 
     private static boolean isChar(final String s, final int pos, final char c) 
{
@@ -387,23 +389,24 @@ public class DateTimeFieldLenientImpl extends 
AbstractField implements DateTimeF
     /**
      * RFC 5322 obs-hour, obs-minute and obs-second allow CFWS around the 
colons of the time
      * (<code>09:55: 06</code>, <code>09:55:(c)06</code>), as the strict 
parser reads them. Applied
-     * to a text whose white space is collapsed. Nested comments are not 
removed: the value is then
-     * not read, see {@link #zoneLeftUnread}. A linear scan: a regex loop over 
the comments
-     * recursed once per comment, and a run of them overflowed the stack.
+     * to a text whose white space is collapsed. Nested comments and quoted 
pairs included, as by
+     * {@link #commentEnds}; an unclosed comment is not removed. A linear 
scan: a regex loop over
+     * the comments recursed once per comment, and a run of them overflowed 
the stack.
      */
     private static String removeCfwsAroundTimeColons(final String text) {
         if (text.indexOf('(') < 0 && text.indexOf(": ") < 0 && text.indexOf(" 
:") < 0) {
             return text;
         }
+        int[] ends = text.indexOf('(') < 0 ? null : commentEnds(text);
         StringBuilder sb = new StringBuilder(text.length());
         int i = 0;
         while (i < text.length()) {
             char c = text.charAt(i++);
             sb.append(c);
             if (c >= '0' && c <= '9') {
-                int colon = skipCfws(text, i);
+                int colon = skipCfws(text, i, ends);
                 if (colon < text.length() && text.charAt(colon) == ':') {
-                    int next = skipCfws(text, colon + 1);
+                    int next = skipCfws(text, colon + 1, ends);
                     if (next < text.length() && text.charAt(next) >= '0' && 
text.charAt(next) <= '9') {
                         sb.append(':');
                         i = next;
@@ -414,23 +417,85 @@ public class DateTimeFieldLenientImpl extends 
AbstractField implements DateTimeF
         return sb.toString();
     }
 
-    /** Skips blanks and comments without nesting; returns the first position 
after them. */
-    private static int skipCfws(final String text, final int from) {
+    /**
+     * RFC 5322 allows CFWS between the tokens of a date, as the strict parser 
reads them: a run of
+     * blanks and comments between two tokens (<code>09:55:06 (c) 
-0600</code>, <code>2:5()EST</code>,
+     * <code>21(c)Nov</code>, <code>06 ((c)) -0600</code>) reads as one space. 
Applied after
+     * {@link #removeCfwsAroundTimeColons}. An unclosed comment is not 
removed. Linear: the end of
+     * each comment is found once, by {@link #commentEnds}.
+     */
+    private static String removeCommentsBetweenTokens(final String text) {
+        if (text.indexOf('(') < 0) {
+            return text;
+        }
+        int[] ends = commentEnds(text);
+        StringBuilder sb = new StringBuilder(text.length());
+        int i = 0;
+        while (i < text.length()) {
+            char c = text.charAt(i++);
+            sb.append(c);
+            if (isAsciiLetterOrDigit(c) && i < text.length() && 
(text.charAt(i) == '(' || text.charAt(i) == ' ')) {
+                int next = skipCfws(text, i, ends);
+                if (next < text.length() && holdsComment(text, i, next) && 
isTokenStart(text.charAt(next))) {
+                    sb.append(' ');
+                    i = next;
+                }
+            }
+        }
+        return sb.toString();
+    }
+
+    /** The position after the comment, nested or not, that opens at 
<code>from</code>; -1 if unclosed. */
+    private static int commentEnd(final String text, final int from) {
+        int depth = 0;
+        for (int p = from; p < text.length(); p++) {
+            char c = text.charAt(p);
+            if (c == '\\') {
+                p++;
+            } else if (c == '(') {
+                depth++;
+            } else if (c == ')' && --depth == 0) {
+                return p + 1;
+            }
+        }
+        return -1;
+    }
+
+    /**
+     * For each "(" opening a comment, nested or not, the position after its 
")"; -1 for an unclosed
+     * one, or a "(" that is not a comment opening (escaped). A quoted pair 
escapes the character
+     * after it in a comment.
+     */
+    private static int[] commentEnds(final String text) {
+        int[] ends = new int[text.length()];
+        Arrays.fill(ends, -1);
+        int[] opens = new int[text.length()];
+        int depth = 0;
+        for (int p = 0; p < text.length(); p++) {
+            char c = text.charAt(p);
+            if (depth > 0 && c == '\\') {
+                p++;
+            } else if (c == '(') {
+                opens[depth++] = p;
+            } else if (c == ')' && depth > 0) {
+                ends[opens[--depth]] = p + 1;
+            }
+        }
+        return ends;
+    }
+
+    /**
+     * Skips blanks and comments, nested ones included; returns the first 
position after them.
+     * <code>ends</code> is null for a text without comment.
+     */
+    private static int skipCfws(final String text, final int from, final int[] 
ends) {
         int p = from;
         while (p < text.length()) {
             char c = text.charAt(p);
             if (c == ' ') {
                 p++;
-            } else if (c == '(') {
-                int close = p + 1;
-                while (close < text.length() && text.charAt(close) != '(' && 
text.charAt(close) != ')') {
-                    close++;
-                }
-                if (close >= text.length() || text.charAt(close) != ')') {
-                    // nested or unclosed comment: not removed
-                    return p;
-                }
-                p = close + 1;
+            } else if (c == '(' && ends != null && ends[p] > 0) {
+                p = ends[p];
             } else {
                 return p;
             }
@@ -438,6 +503,23 @@ public class DateTimeFieldLenientImpl extends 
AbstractField implements DateTimeF
         return p;
     }
 
+    private static boolean holdsComment(final String text, final int from, 
final int to) {
+        for (int p = from; p < to; p++) {
+            if (text.charAt(p) == '(') {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    private static boolean isAsciiLetterOrDigit(final char c) {
+        return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' 
&& c <= 'Z');
+    }
+
+    private static boolean isTokenStart(final char c) {
+        return c == '+' || c == '-' || isAsciiLetterOrDigit(c);
+    }
+
     /**
      * An offset without its sign right after the time ("22:23:35.882 0000", 
MIME4J-219) reads as
      * a positive one: the obs-zone sections do not read digits.
diff --git 
a/dom/src/test/java/org/apache/james/mime4j/field/DateTimeFieldLenientFastPathTest.java
 
b/dom/src/test/java/org/apache/james/mime4j/field/DateTimeFieldLenientFastPathTest.java
index 6a2fca99..aa628356 100644
--- 
a/dom/src/test/java/org/apache/james/mime4j/field/DateTimeFieldLenientFastPathTest.java
+++ 
b/dom/src/test/java/org/apache/james/mime4j/field/DateTimeFieldLenientFastPathTest.java
@@ -81,7 +81,7 @@ public class DateTimeFieldLenientFastPathTest {
         Random random = new Random(42);
         String alphabet = "0123456789 
:+-,()JanFebMarAprDecMonTueGMTUTESTPDTZ.\t";
         String[] seeds = {"Tue, 26 Apr 2022 02:27:54 +0000", "4 Oct 2001 20:12 
-0700", "29 Feb 2024 23:59:59",
-            "Sun, 31 Dec 9999 23:59:59 -1759 (comment)"};
+            "Sun, 31 Dec 9999 23:59:59 -1759 (comment)", "Tue, 26 Apr 2022 
02:27:54 +0000 (a) (b)"};
         List<String> fastPathTaken = new ArrayList<>();
         for (int i = 0; i < 500_000; i++) {
             StringBuilder s = new 
StringBuilder(seeds[random.nextInt(seeds.length)]);
diff --git 
a/dom/src/test/java/org/apache/james/mime4j/field/LenientDateTimeFieldTest.java 
b/dom/src/test/java/org/apache/james/mime4j/field/LenientDateTimeFieldTest.java
index bb7e0490..85aab58c 100644
--- 
a/dom/src/test/java/org/apache/james/mime4j/field/LenientDateTimeFieldTest.java
+++ 
b/dom/src/test/java/org/apache/james/mime4j/field/LenientDateTimeFieldTest.java
@@ -213,8 +213,13 @@ public class LenientDateTimeFieldTest {
 
     @Test
     public void unreadSecondsGiveNoDate() throws Exception {
-        // a nested comment is not removed: rather no date than one without 
its seconds and zone
-        Assert.assertNull(parse("Date: Fri, 21 Nov 1997 09:55:((x))06 
-0600").getDate());
+        // a nested comment is read as the strict parser does
+        Date strict = DateTimeFieldImpl.PARSER.parse(
+            RawFieldParser.DEFAULT.parseField(ContentUtil.encode("Date: Fri, 
21 Nov 1997 09:55:((x))06 -0600")), null).getDate();
+        Assert.assertEquals(Date.from(Instant.parse("1997-11-21T15:55:06Z")), 
strict);
+        Assert.assertEquals(strict, parse("Date: Fri, 21 Nov 1997 
09:55:((x))06 -0600").getDate());
+        // an unclosed one is not removed: rather no date than one without its 
seconds and zone
+        Assert.assertNull(parse("Date: Fri, 21 Nov 1997 09:55:((x)06 
-0600").getDate());
     }
     @Test
     public void numericZoneOfOtherThanFourDigitsShouldBeRejected() throws 
Exception {
@@ -231,6 +236,39 @@ public class LenientDateTimeFieldTest {
         Assert.assertEquals(1577913803000L, parse("Date: 1 Jan 2020 21:23:23 
Z").getDate().getTime());
     }
 
+    @Test
+    public void zoneAfterACommentShouldBeReadLikeTheStrictParser() throws 
Exception {
+        String[] values = {"Fri, 21 Nov 1997 09:55:06 (c) -0600", "Fri, 21 Nov 
1997 09:55:06(c)-0600",
+            "Fri, 21 Nov 1997 09:55:06 ((c)) -0600", "Fri, 21 Nov 1997 
09:55:06 (a\\)b) -0600",
+            "Fri, 21 Nov 1997 09:55:06 (a) (b) -0600", "21(c)Nov 1997 09:55:06 
-0600", "21 Nov 1997 09:55:06()CST",
+            "Fri, 21 Nov 1997 09:55((c)):06 -0600", "Fri, 21 Nov 1997 
09:55(a\\)b):06 -0600", "Fri, 21 Nov 1997 09:55(\\():06 -0600"};
+        for (String value : values) {
+            Date strict = DateTimeFieldImpl.PARSER.parse(
+                RawFieldParser.DEFAULT.parseField(ContentUtil.encode("Date: " 
+ value)), null).getDate();
+            Assert.assertEquals(value, 
Date.from(Instant.parse("1997-11-21T15:55:06Z")), strict);
+            Assert.assertEquals(value, strict, parse("Date: " + 
value).getDate());
+        }
+        Assert.assertEquals(Date.from(Instant.parse("2020-01-01T07:05:00Z")), 
parse("Date: 1 Jan 20 2:5()EST").getDate());
+        // a trailing comment, or a military zone after a comment, is still 
read as before
+        Assert.assertEquals(Date.from(Instant.parse("1997-11-21T15:55:06Z")), 
parse("Date: Fri, 21 Nov 1997 09:55:06 -0600 (CST)").getDate());
+        Assert.assertEquals(Date.from(Instant.parse("1997-11-21T09:55:06Z")), 
parse("Date: Fri, 21 Nov 1997 09:55:06 (c) Z").getDate());
+        // after a trailing comment, a text is read: the fast path leaves it 
to the formatter
+        for (String value : new String[] {"Tue, 26 Apr 2022 02:27:54 +0000 (a) 
-0600 (b)", "Tue, 26 Apr 2022 02:27:54 +0000 (a)0(b)"}) {
+            Assert.assertNull(value, 
DateTimeFieldLenientImpl.parseCommonForm(value));
+            Assert.assertNull(value, 
DateTimeFieldLenientImpl.parseWithFormatter(value));
+        }
+    }
+
+    @Test(timeout = 10000)
+    public void manyUnclosedCommentsAfterTokensAreLinear() {
+        StringBuilder value = new StringBuilder("1 Jan 2020 10:00:00 ");
+        for (int i = 0; i < 100_000; i++) {
+            value.append("1(");
+        }
+        // the digit left after the time is a zone not read: no date
+        Assert.assertNull(dateOf(value.toString()));
+    }
+
     static Date dateOf(final String body) {
         return DateTimeFieldLenientImpl.PARSER.parse(new RawField("Date", 
body), null).getDate();
     }


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to