Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add compatibility with rfc2822 comments #733

Merged
merged 2 commits into from Jul 24, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -34,6 +34,7 @@ Versions with only mechanical changes will be omitted from the following list.
* Remove libc dependency from Cargo.toml.
* Add the `and_local_timezone` method to `NaiveDateTime`
* Fix the behavior of `Duration::abs()` for negative durations with non-zero nanos
* Add compatibility with rfc2822 comments (#733)

## 0.4.19

Expand Down
26 changes: 22 additions & 4 deletions src/format/parse.rs
Expand Up @@ -53,7 +53,10 @@ fn parse_rfc2822<'a>(parsed: &mut Parsed, mut s: &'a str) -> ParseResult<(&'a st

// an adapted RFC 2822 syntax from Section 3.3 and 4.3:
//
// date-time = [ day-of-week "," ] date 1*S time *S
// c-char = <any char except '(', ')' and '\\'>
// c-escape = "\" <any char>
// comment = "(" *(comment / c-char / c-escape) ")" *S
// date-time = [ day-of-week "," ] date 1*S time *S *comment
// day-of-week = *S day-name *S
// day-name = "Mon" / "Tue" / "Wed" / "Thu" / "Fri" / "Sat" / "Sun"
// date = day month year
Expand All @@ -79,9 +82,10 @@ fn parse_rfc2822<'a>(parsed: &mut Parsed, mut s: &'a str) -> ParseResult<(&'a st
//
// - we do not recognize a folding white space (FWS) or comment (CFWS).
// for our purposes, instead, we accept any sequence of Unicode
// white space characters (denoted here to `S`). any actual RFC 2822
// parser is expected to parse FWS and/or CFWS themselves and replace
// it with a single SP (`%x20`); this is legitimate.
// white space characters (denoted here to `S`). For comments, we accept
// any text within parentheses while respecting escaped parentheses.
// Any actual RFC 2822 parser is expected to parse FWS and/or CFWS themselves
// and replace it with a single SP (`%x20`); this is legitimate.
//
// - two-digit year < 50 should be interpreted by adding 2000.
// two-digit year >= 50 or three-digit year should be interpreted
Expand Down Expand Up @@ -145,6 +149,14 @@ fn parse_rfc2822<'a>(parsed: &mut Parsed, mut s: &'a str) -> ParseResult<(&'a st
parsed.set_offset(i64::from(offset))?;
}

// optional comments
s = s.trim_left();
while let Ok((s_out, ())) = scan::comment_2822(s) {
// Trim left after every found comment, as comments are allowed to have whitespace
// between them
s = s_out.trim_left();
}

Ok((s, ()))
}

Expand Down Expand Up @@ -817,6 +829,12 @@ fn test_rfc2822() {
("Tue, 20 Jan 2015 17:35:20 -0800", Ok("Tue, 20 Jan 2015 17:35:20 -0800")), // normal case
("Fri, 2 Jan 2015 17:35:20 -0800", Ok("Fri, 02 Jan 2015 17:35:20 -0800")), // folding whitespace
("Fri, 02 Jan 2015 17:35:20 -0800", Ok("Fri, 02 Jan 2015 17:35:20 -0800")), // leading zero
("Tue, 20 Jan 2015 17:35:20 -0800 (UTC)", Ok("Tue, 20 Jan 2015 17:35:20 -0800")), // trailing comment
(
"Tue, 20 Jan 2015 17:35:20 -0800 ( (UTC ) (\\( (a)\\(( \\t ) ) \\\\( \\) ))",
Ok("Tue, 20 Jan 2015 17:35:20 -0800"),
), // complex trailing comment
("Tue, 20 Jan 2015 17:35:20 -0800 (UTC\\)", Err(TOO_LONG)), // incorrect comment, not enough closing parentheses
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems like TOO_SHORT is more optimal in this case (admittedly obscure) - but it seems like actually getting TOO_SHORT at this stage might not be trivial, unless we early return from scan::comment_2822. Potentially the logic could be that if there is at least one ( then it makes sense to early return the TOO_SHORT if it is never closed. Alternatively, the parser could be more permissive and just remove all the comment characters and return the parsed date if the rest is in the correct format - let me know what your thoughts are here?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I had the same thought, but for one, it's indeed not trivial to change that; and further, it's not completely clear. Technically "Tue, 20 Jan 2015 17:35:20 -0800 (" could be both too short or too long. "Tue, 20 Jan 2015 17:35:20 -0800 x", for example, is definitely too long, so one could argue that the first one is also a valid string plus " (". So I'd argue that "a comment" is everything that parses as a comment, and "too long" is everything attached to the timestamp that doesn't parse as a comment. Which includes " (".

Copy link
Contributor Author

@Finomnis Finomnis Jul 16, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think just accepting everything is the right choice, at least not with your current code structure. parse.rs just parses a single rfc2822 datetime string, and the way it is currently written means it could be used as a part of a more complex parser. So I wouldn't allow just everything, otherwise I think the entire TOO_LONG value would be pointless and we could simply accept all the strings that start with a valid rfc2822 datetime.

If you want me to change something, then what I would agree with most is to short-circuit TOO_SHORT. But that also wouldn't be true the way the code is written right now, because the parse_rfc2822 conceptually is supposed to attempt to parse a rfc2822 datetime string + return the leftover input that wasn't part of the rfc2822 datetime. And it does exactly that in the case of "Tue, 20 Jan 2015 17:35:20 -0800 (", because "Tue, 20 Jan 2015 17:35:20 -0800" is a valid rfc2822 string and " (" is a valid rest. It just wasn't able to consume " (", which is totally valid.

So if we want to change something, it must be somewhere in the method parse_internal. And this one currently is written so that it always returns TOO_LONG whenever any tokens are left over from parsing. So I'm not sure how TOO_SHORT would conceptually fit the current code structure.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @Finomnis - really good point about the rfc2822 item being able to be reused within other formats, we definitely shouldn't break that so it looks like it is best to leave it as is.

("20 Jan 2015 17:35:20 -0800", Ok("Tue, 20 Jan 2015 17:35:20 -0800")), // no day of week
("20 JAN 2015 17:35:20 -0800", Ok("Tue, 20 Jan 2015 17:35:20 -0800")), // upper case month
("Tue, 20 Jan 2015 17:35 -0800", Ok("Tue, 20 Jan 2015 17:35:00 -0800")), // no second
Expand Down
73 changes: 73 additions & 0 deletions src/format/scan.rs
Expand Up @@ -348,3 +348,76 @@ pub(super) fn timezone_offset_2822(s: &str) -> ParseResult<(&str, Option<i32>)>
pub(super) fn timezone_name_skip(s: &str) -> ParseResult<(&str, ())> {
Ok((s.trim_left_matches(|c: char| !c.is_whitespace()), ()))
}

/// Tries to consume an RFC2822 comment
pub(super) fn comment_2822(mut s: &str) -> ParseResult<(&str, ())> {
macro_rules! next_char {
() => {{
let c = s.bytes().nth(0).ok_or(TOO_SHORT)?;
s = &s[1..];
c
}};
}

// Make sure the first letter is a `(`
if b'(' != next_char!() {
Err(INVALID)?;
}

let mut depth = 1; // start with 1 as we already encountered a '('
loop {
match next_char!() {
// If we encounter `\`, ignore the next character as it is escaped.
b'\\' => {
next_char!();
}

// If we encounter `(`, open a parantheses context.
b'(' => {
depth += 1;
}

// If we encounter `)`, close a parentheses context.
// If all are closed, we found the end of the comment.
b')' => {
depth -= 1;
if depth == 0 {
break;
}
}

// Ignore all other characters
_ => (),
};
}

Ok((s, ()))
}

#[cfg(test)]
#[test]
fn test_rfc2822_comments() {
let testdata = [
("", Err(TOO_SHORT)),
("x", Err(INVALID)),
("(", Err(TOO_SHORT)),
("()", Ok("")),
("()z", Ok("z")),
("(x)", Ok("")),
("(())", Ok("")),
("((()))", Ok("")),
("(x(x(x)x)x)", Ok("")),
("( x ( x ( x ) x ) x )", Ok("")),
("(\\)", Err(TOO_SHORT)),
("(\\()", Ok("")),
("(\\))", Ok("")),
("(\\\\)", Ok("")),
("(()())", Ok("")),
("( x ( x ) x ( x ) x )", Ok("")),
];

for (test_in, expected) in testdata {
let actual = comment_2822(test_in).map(|(s, _)| s);
assert_eq!(expected, actual);
}
}