parse-net 0.9.2

Grammar for Internet message fields: RFC 9110 field syntax, media types, RFC 9651 Structured Fields, HTTP and RFC 5322 dates, negotiation, entity tags, ranges, Content-Disposition, Cache-Control, Forwarded, auth challenges, and the email lexical layer. no_std, no allocation, sans-IO, zero dependencies.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
//! [`Limits`], the work and size bounds every parser enforces, and
//! [`DuplicatePolicy`].

/// The work and size bounds every parser enforces.
///
/// Every bound is checked before the work it governs, and none allocates:
/// they bound loops. The defaults meet every minimum RFC 9651 section 3 sets
/// for parsers, so a conforming sender is never refused by default.
///
/// | Bound | Default | Source |
/// |---|---|---|
/// | list members | 1024 | RFC 9651 section 3.1 minimum |
/// | inner list members | 256 | RFC 9651 section 3.1.1 minimum |
/// | parameters per item or field | 256 (RFC 9110 parameters under `DuplicatePolicy::Refuse`: at most 64, [`param::MAX_CHECKED_PARAMS`](crate::param::MAX_CHECKED_PARAMS)) | RFC 9651 section 3.1.2 minimum |
/// | dictionary members | 1024 | RFC 9651 section 3.2 minimum |
/// | key length | 256 | RFC 9651 minimum is 64 |
/// | string length (decoded) | 1024 | RFC 9651 section 3.3.3 minimum |
/// | token length | 512 | RFC 9651 section 3.3.4 minimum |
/// | byte sequence length (decoded) | 16384 | RFC 9651 section 3.3.5 minimum |
/// | empty list elements | 16 | RFC 9110 section 5.6.1.2: "a reasonable number" |
/// | comment depth | 8 | none in the RFC |
/// | ranges | 16 | RFC 9110 section 14.2 permits refusal |
/// | RFC 2231 sections | 32 | none in the RFC |
/// | encoded words per field | 64 | none in the RFC |
/// | forwarded hops | 16 | none in the RFC |
///
/// A setter may set a bound below the RFC minimum: that is the caller
/// tightening deliberately, and it makes the parser non-conforming for that
/// field.
///
/// # Examples
///
/// ```
/// use parse_net::{list, ErrorKind, Limits};
///
/// const STRICT: Limits = Limits::DEFAULT.max_list_members(64).max_params(16);
/// let err = list::parse(b"a, b, c", &Limits::DEFAULT.max_list_members(2)).unwrap_err();
/// assert_eq!((err.kind(), err.offset()), (ErrorKind::TooManyMembers, 6));
/// # let _ = STRICT;
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Limits {
    pub(crate) list_members: u16,
    pub(crate) inner_list_members: u16,
    pub(crate) params: u16,
    pub(crate) dictionary_members: u16,
    pub(crate) key_len: u16,
    pub(crate) string_len: u16,
    pub(crate) token_len: u16,
    pub(crate) byte_seq_len: u32,
    pub(crate) empty_elements: u16,
    pub(crate) comment_depth: u8,
    pub(crate) ranges: u16,
    pub(crate) rfc2231_sections: u8,
    pub(crate) encoded_words: u16,
    pub(crate) hops: u8,
    pub(crate) allow_leap_second: bool,
    pub(crate) duplicate_params: DuplicatePolicy,
}

/// The size of the stack array that reassembles RFC 2231 sections.
pub(crate) const MAX_RFC2231_SECTIONS: u8 = 32;

impl Limits {
    /// The defaults in the table above.
    ///
    /// # Examples
    ///
    /// ```
    /// use parse_net::Limits;
    ///
    /// assert_eq!(Limits::DEFAULT, Limits::default());
    /// let l = parse_net::list::parse(b"a, b, c", &Limits::DEFAULT)?;
    /// assert_eq!(l.len(), 3);
    /// # Ok::<(), parse_net::ParseError>(())
    /// ```
    pub const DEFAULT: Self = Self {
        list_members: 1024,
        inner_list_members: 256,
        params: 256,
        dictionary_members: 1024,
        key_len: 256,
        string_len: 1024,
        token_len: 512,
        byte_seq_len: 16384,
        empty_elements: 16,
        comment_depth: 8,
        ranges: 16,
        rfc2231_sections: MAX_RFC2231_SECTIONS,
        encoded_words: 64,
        hops: 16,
        allow_leap_second: false,
        duplicate_params: DuplicatePolicy::Refuse,
    };

    /// The defaults; the same as [`Limits::DEFAULT`].
    ///
    /// # Examples
    ///
    /// ```
    /// use parse_net::Limits;
    ///
    /// const LIMITS: Limits = Limits::new();
    /// assert_eq!(LIMITS, Limits::DEFAULT);
    /// ```
    #[must_use]
    pub const fn new() -> Self {
        Self::DEFAULT
    }

    /// The most members a list may have (default 1024).
    ///
    /// # Examples
    ///
    /// ```
    /// use parse_net::{list, ErrorKind, Limits};
    ///
    /// let two = Limits::DEFAULT.max_list_members(2);
    /// assert_eq!(list::parse(b"a, b", &two)?.len(), 2);
    /// assert_eq!(list::parse(b"a, b, c", &two).unwrap_err().kind(), ErrorKind::TooManyMembers);
    /// # Ok::<(), parse_net::ParseError>(())
    /// ```
    #[must_use]
    pub const fn max_list_members(self, n: u16) -> Self {
        Self {
            list_members: n,
            ..self
        }
    }

    /// The most members a Structured Field inner list may have (default 256).
    ///
    /// # Examples
    ///
    /// ```
    /// use parse_net::{sfv::Parser, ErrorKind, Limits};
    ///
    /// let p = Parser::new(Limits::DEFAULT.max_inner_list_members(2));
    /// assert!(p.list(b"(a b), c").is_ok());
    /// assert_eq!(p.list(b"(a b c)").unwrap_err().kind(), ErrorKind::TooManyMembers);
    /// ```
    #[must_use]
    pub const fn max_inner_list_members(self, n: u16) -> Self {
        Self {
            inner_list_members: n,
            ..self
        }
    }

    /// The most parameters an item or a field may have (default 256).
    ///
    /// RFC 9110 parameters read under [`DuplicatePolicy::Refuse`] stop at
    /// [`MAX_CHECKED_PARAMS`](crate::param::MAX_CHECKED_PARAMS) (64) whatever
    /// this says: the repeat check keeps their names on the stack (D-072).
    ///
    /// # Examples
    ///
    /// ```
    /// use parse_net::{param, ErrorKind, Limits};
    ///
    /// let one = Limits::DEFAULT.max_params(1);
    /// assert_eq!(param::parse(b";a=1", &one)?.0.len(), 1);
    /// assert_eq!(param::parse(b";a=1;b=2", &one).unwrap_err().kind(), ErrorKind::TooManyMembers);
    /// # Ok::<(), parse_net::ParseError>(())
    /// ```
    #[must_use]
    pub const fn max_params(self, n: u16) -> Self {
        Self { params: n, ..self }
    }

    /// The most members a Structured Field dictionary may have (default 1024).
    ///
    /// # Examples
    ///
    /// ```
    /// use parse_net::{sfv::Parser, ErrorKind, Limits};
    ///
    /// let p = Parser::new(Limits::DEFAULT.max_dictionary_members(1));
    /// assert!(p.dictionary(b"a=1").is_ok());
    /// assert_eq!(p.dictionary(b"a=1, b=2").unwrap_err().kind(), ErrorKind::TooManyMembers);
    /// ```
    #[must_use]
    pub const fn max_dictionary_members(self, n: u16) -> Self {
        Self {
            dictionary_members: n,
            ..self
        }
    }

    /// The longest Structured Field key (default 256).
    ///
    /// # Examples
    ///
    /// ```
    /// use parse_net::{sfv::Parser, ErrorKind, Limits};
    ///
    /// let p = Parser::new(Limits::DEFAULT.max_key_len(3));
    /// assert!(p.dictionary(b"abc=1").is_ok());
    /// assert_eq!(p.dictionary(b"abcd=1").unwrap_err().kind(), ErrorKind::TooLong);
    /// ```
    #[must_use]
    pub const fn max_key_len(self, n: u16) -> Self {
        Self { key_len: n, ..self }
    }

    /// The longest Structured Field string, decoded (default 1024).
    ///
    /// # Examples
    ///
    /// ```
    /// use parse_net::{sfv::Parser, ErrorKind, Limits};
    ///
    /// let p = Parser::new(Limits::DEFAULT.max_string_len(3));
    /// assert!(p.item(b"\"a\\\"b\"").is_ok());
    /// assert_eq!(p.item(b"\"abcd\"").unwrap_err().kind(), ErrorKind::TooLong);
    /// ```
    #[must_use]
    pub const fn max_string_len(self, n: u16) -> Self {
        Self {
            string_len: n,
            ..self
        }
    }

    /// The longest Structured Field token (default 512).
    ///
    /// # Examples
    ///
    /// ```
    /// use parse_net::{sfv::Parser, ErrorKind, Limits};
    ///
    /// let p = Parser::new(Limits::DEFAULT.max_token_len(4));
    /// assert!(p.item(b"gzip").is_ok());
    /// assert_eq!(p.item(b"deflate").unwrap_err().kind(), ErrorKind::TooLong);
    /// ```
    #[must_use]
    pub const fn max_token_len(self, n: u16) -> Self {
        Self {
            token_len: n,
            ..self
        }
    }

    /// The longest Structured Field byte sequence, decoded (default 16384).
    ///
    /// # Examples
    ///
    /// ```
    /// use parse_net::{sfv::Parser, ErrorKind, Limits};
    ///
    /// let p = Parser::new(Limits::DEFAULT.max_byte_seq_len(3));
    /// assert!(p.item(b":AQID:").is_ok());
    /// assert_eq!(p.item(b":AQIDBA==:").unwrap_err().kind(), ErrorKind::TooLong);
    /// ```
    #[must_use]
    pub const fn max_byte_seq_len(self, n: u32) -> Self {
        Self {
            byte_seq_len: n,
            ..self
        }
    }

    /// The most empty list elements accepted in one field (default 16).
    ///
    /// # Examples
    ///
    /// ```
    /// use parse_net::{list, ErrorKind, Limits};
    ///
    /// let one = Limits::DEFAULT.max_empty_elements(1);
    /// assert_eq!(list::parse(b"a, , b", &one)?.len(), 2);
    /// assert_eq!(list::parse(b"a, , , b", &one).unwrap_err().kind(), ErrorKind::TooManyEmptyElements);
    /// # Ok::<(), parse_net::ParseError>(())
    /// ```
    #[must_use]
    pub const fn max_empty_elements(self, n: u16) -> Self {
        Self {
            empty_elements: n,
            ..self
        }
    }

    /// The deepest comment nesting accepted (default 8).
    ///
    /// # Examples
    ///
    /// ```
    /// use parse_net::{text::parse_comment, ErrorKind, Limits};
    ///
    /// let flat = Limits::DEFAULT.max_comment_depth(1);
    /// assert!(parse_comment(b"(a)", &flat).is_ok());
    /// assert_eq!(parse_comment(b"(a(b))", &flat).unwrap_err().kind(), ErrorKind::CommentTooDeep);
    /// ```
    #[must_use]
    pub const fn max_comment_depth(self, n: u8) -> Self {
        Self {
            comment_depth: n,
            ..self
        }
    }

    /// The most ranges a `Range` field may request (default 16).
    ///
    /// # Examples
    ///
    /// ```
    /// use parse_net::{range, ByteRange, Limits, RangeOutcome};
    ///
    /// let h = range::parse(b"bytes=0-9, 20-29", &Limits::DEFAULT)?;
    /// let mut out = [ByteRange { start: 0, end: 0 }; 4];
    /// assert_eq!(range::resolve(&h, 100, false, &Limits::DEFAULT, &mut out), RangeOutcome::Ranges(2));
    /// assert_eq!(range::resolve(&h, 100, false, &Limits::DEFAULT.max_ranges(1), &mut out), RangeOutcome::Ignore);
    /// # Ok::<(), parse_net::ParseError>(())
    /// ```
    #[must_use]
    pub const fn max_ranges(self, n: u16) -> Self {
        Self { ranges: n, ..self }
    }

    /// The most RFC 2231 sections in one parameter (default 32). Values above
    /// 32, the size of the reassembly array, are stored as 32.
    ///
    /// # Examples
    ///
    /// ```
    /// use parse_net::{mail, ErrorKind, Limits};
    ///
    /// let two = Limits::DEFAULT.max_rfc2231_sections(2);
    /// assert!(mail::parse_mime_params(b"; t*0=a; t*1=b", &two).is_ok());
    /// let err = mail::parse_mime_params(b"; t*0=a; t*1=b; t*2=c", &two).unwrap_err();
    /// assert_eq!(err.kind(), ErrorKind::TooManySections);
    /// ```
    #[must_use]
    pub const fn max_rfc2231_sections(self, n: u8) -> Self {
        let n = if n > MAX_RFC2231_SECTIONS {
            MAX_RFC2231_SECTIONS
        } else {
            n
        };
        Self {
            rfc2231_sections: n,
            ..self
        }
    }

    /// The most RFC 2047 encoded words in one field (default 64).
    ///
    /// # Examples
    ///
    /// ```
    /// use parse_net::{mail, ErrorKind, Limits};
    ///
    /// let one = Limits::DEFAULT.max_encoded_words(1);
    /// let mut buf = [0u8; 16];
    /// assert_eq!(mail::decode_words(b"=?utf-8?q?a?=", &one, &mut buf)?, "a");
    /// let err = mail::decode_words(b"=?utf-8?q?a?= =?utf-8?q?b?=", &one, &mut buf).unwrap_err();
    /// assert_eq!(err.kind(), ErrorKind::TooManyMembers);
    /// # Ok::<(), parse_net::ParseError>(())
    /// ```
    #[must_use]
    pub const fn max_encoded_words(self, n: u16) -> Self {
        Self {
            encoded_words: n,
            ..self
        }
    }

    /// The most hops in a forwarded chain (default 16).
    ///
    /// # Examples
    ///
    /// ```
    /// use parse_net::{forwarded, ErrorKind, Limits};
    ///
    /// let lines = [&b"192.0.2.1, 198.51.100.2"[..]];
    /// assert!(forwarded::parse_x_forwarded_for(&lines, &Limits::DEFAULT).is_ok());
    /// let err = forwarded::parse_x_forwarded_for(&lines, &Limits::DEFAULT.max_hops(1)).unwrap_err();
    /// assert_eq!(err.kind(), ErrorKind::TooManyHops);
    /// ```
    #[must_use]
    pub const fn max_hops(self, n: u8) -> Self {
        Self { hops: n, ..self }
    }

    /// Whether HTTP-date accepts second `60` (read as 59). Off by default.
    ///
    /// # Examples
    ///
    /// ```
    /// use parse_net::{HttpDate, Limits};
    ///
    /// let leap = b"Sun, 06 Nov 1994 08:49:60 GMT";
    /// assert!(HttpDate::parse_at_with(leap, 0, &Limits::DEFAULT).is_err());
    /// let d = HttpDate::parse_at_with(leap, 0, &Limits::DEFAULT.allow_leap_second(true))?;
    /// assert_eq!(d, HttpDate::parse_imf_fixdate(b"Sun, 06 Nov 1994 08:49:59 GMT")?);
    /// # Ok::<(), parse_net::ParseError>(())
    /// ```
    #[must_use]
    pub const fn allow_leap_second(self, yes: bool) -> Self {
        Self {
            allow_leap_second: yes,
            ..self
        }
    }

    /// What parameter parsers do with a repeated name (default
    /// [`DuplicatePolicy::Refuse`]).
    ///
    /// # Examples
    ///
    /// ```
    /// use parse_net::{param, DuplicatePolicy, Limits};
    ///
    /// assert!(param::parse(b";a=1;a=2", &Limits::DEFAULT).is_err());
    /// let last = Limits::DEFAULT.duplicate_params(DuplicatePolicy::Last);
    /// let (p, _) = param::parse(b";a=1;a=2", &last)?;
    /// assert!(p.get("a").is_some_and(|v| v.eq_bytes(b"2")));
    /// # Ok::<(), parse_net::ParseError>(())
    /// ```
    #[must_use]
    pub const fn duplicate_params(self, p: DuplicatePolicy) -> Self {
        Self {
            duplicate_params: p,
            ..self
        }
    }
}

impl Default for Limits {
    fn default() -> Self {
        Self::DEFAULT
    }
}

/// What a parameter parser does when a name repeats.
///
/// Names compare ASCII case-insensitively. [`Refuse`](Self::Refuse), the
/// default, fails with [`ErrorKind::DuplicateParameter`](crate::ErrorKind::DuplicateParameter)
/// at the repeated name: a field one component reads first-wins and another
/// last-wins is a known attack. [`First`](Self::First) and
/// [`Last`](Self::Last) exist for fields whose RFC states the rule.
/// Structured Fields always use last-wins, as RFC 9651 requires.
///
/// # Examples
///
/// ```
/// use parse_net::{param, DuplicatePolicy, Limits};
///
/// let limits = Limits::DEFAULT.duplicate_params(DuplicatePolicy::Last);
/// let (p, _) = param::parse(b";a=1;a=2", &limits)?;
/// assert!(p.get("a").is_some_and(|v| v.eq_bytes(b"2")));
/// # Ok::<(), parse_net::ParseError>(())
/// ```
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
pub enum DuplicatePolicy {
    /// Refuse a repeated name.
    #[default]
    Refuse,
    /// Keep the first occurrence for lookups.
    First,
    /// Keep the last occurrence for lookups.
    Last,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_limits_defaults_meet_rfc_minimums() {
        let l = Limits::new();
        assert_eq!(l, Limits::default());
        assert!(l.list_members >= 1024);
        assert!(l.inner_list_members >= 256);
        assert!(l.params >= 256);
        assert!(l.dictionary_members >= 1024);
        assert!(l.key_len >= 64);
        assert!(l.string_len >= 1024);
        assert!(l.token_len >= 512);
        assert!(l.byte_seq_len >= 16384);
        assert!(!l.allow_leap_second);
        assert_eq!(l.duplicate_params, DuplicatePolicy::Refuse);
    }

    #[test]
    fn test_limits_setters_set_one_field() {
        let l = Limits::DEFAULT
            .max_list_members(1)
            .max_inner_list_members(2)
            .max_params(3)
            .max_dictionary_members(4)
            .max_key_len(5)
            .max_string_len(6)
            .max_token_len(7)
            .max_byte_seq_len(8)
            .max_empty_elements(9)
            .max_comment_depth(10)
            .max_ranges(11)
            .max_rfc2231_sections(12)
            .max_encoded_words(13)
            .max_hops(14)
            .allow_leap_second(true)
            .duplicate_params(DuplicatePolicy::First);
        assert_eq!(
            (
                l.list_members,
                l.inner_list_members,
                l.params,
                l.dictionary_members
            ),
            (1, 2, 3, 4)
        );
        assert_eq!(
            (l.key_len, l.string_len, l.token_len, l.byte_seq_len),
            (5, 6, 7, 8)
        );
        assert_eq!((l.empty_elements, l.comment_depth, l.ranges), (9, 10, 11));
        assert_eq!((l.rfc2231_sections, l.encoded_words, l.hops), (12, 13, 14));
        assert!(l.allow_leap_second);
        assert_eq!(l.duplicate_params, DuplicatePolicy::First);
    }

    #[test]
    fn test_limits_rfc2231_sections_capped_at_32() {
        assert_eq!(
            Limits::DEFAULT.max_rfc2231_sections(200).rfc2231_sections,
            32
        );
    }
}