form-net 0.3.0

Sans-IO form parsing for Rust: application/x-www-form-urlencoded and streaming multipart/form-data, with budgets checked before allocation, safe upload spilling, and typed extraction. No third-party 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
//! The allocation-free urlencoded scanner.

use core::fmt;

use crate::error::{FormError, Limit, Location};
use crate::limits::{Limits, PercentPolicy};
use crate::urlencoded::decode::decode_component;

const HAS_EQUALS: u8 = 1;
const NAME_DECODE: u8 = 2;
const VALUE_DECODE: u8 = 4;

/// Iterates the pairs of a urlencoded body without allocating or copying.
///
/// Budgets are checked per sequence before the sequence is handed out: body
/// size (every byte, empty sequences included), field count, raw name and
/// value lengths, and the running total of raw value lengths. After the
/// first error the iterator returns `None`.
///
/// # Examples
///
/// ```
/// use form_net::Limits;
///
/// let pairs: Vec<_> = form_net::raw_pairs(b"a=1&&b", &Limits::DEFAULT)
///     .map(|p| p.map(|p| (p.name_raw(), p.value_raw(), p.has_equals())))
///     .collect::<Result<_, _>>()?;
/// assert_eq!(pairs, [(&b"a"[..], &b"1"[..], true), (&b"b"[..], &b""[..], false)]);
/// # Ok::<(), form_net::FormError>(())
/// ```
#[must_use]
pub fn raw_pairs<'a>(input: &'a [u8], limits: &Limits) -> RawPairs<'a> {
    RawPairs {
        input,
        pos: 0,
        fields: 0,
        text: 0,
        limits: *limits,
        done: false,
        checked_body: false,
    }
}

/// The iterator returned by [`raw_pairs`].
#[derive(Clone)]
pub struct RawPairs<'a> {
    input: &'a [u8],
    pos: usize,
    fields: u32,
    text: u64,
    limits: Limits,
    done: bool,
    checked_body: bool,
}

impl fmt::Debug for RawPairs<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RawPairs")
            .field("position", &self.pos)
            .field("fields", &self.fields)
            .finish_non_exhaustive()
    }
}

impl<'a> RawPairs<'a> {
    fn fail(&mut self, err: FormError) -> Option<Result<RawPair<'a>, FormError>> {
        self.done = true;
        Some(Err(err))
    }
}

impl<'a> Iterator for RawPairs<'a> {
    type Item = Result<RawPair<'a>, FormError>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.done {
            return None;
        }
        if !self.checked_body {
            self.checked_body = true;
            if self.input.len() > self.limits.body_usize() {
                return self.fail(FormError::limit(
                    Limit::Body,
                    Location::at(self.limits.body()),
                ));
            }
        }
        loop {
            if self.pos >= self.input.len() {
                self.done = true;
                return None;
            }
            let start = self.pos;
            let mut flags = 0u8;
            let mut eq = None;
            let mut i = start;
            let end = loop {
                i = crate::scan::find_any(self.input, i, *b"&=%+");
                match self.input.get(i) {
                    None | Some(b'&') => break i,
                    Some(b'=') if eq.is_none() => {
                        eq = Some(i);
                        flags |= HAS_EQUALS;
                    }
                    Some(b'%' | b'+') => {
                        flags |= if eq.is_some() {
                            VALUE_DECODE
                        } else {
                            NAME_DECODE
                        };
                    }
                    Some(_) => {}
                }
                i = i.wrapping_add(1);
            };
            self.pos = end.saturating_add(1).min(self.input.len());
            if end == start {
                continue;
            }
            let seq = self.input.get(start..end).unwrap_or(&[]);
            let (name, value) = match eq {
                Some(e) => {
                    let at = e.wrapping_sub(start);
                    (
                        seq.get(..at).unwrap_or(&[]),
                        seq.get(at.wrapping_add(1)..).unwrap_or(&[]),
                    )
                }
                None => (seq, &[][..]),
            };
            let offset = start as u64;
            let at = Location::at(offset);
            self.fields = self.fields.saturating_add(1);
            if self.fields > self.limits.max_fields {
                return self.fail(FormError::limit(Limit::Fields, at));
            }
            if name.len() as u64 > u64::from(self.limits.name()) {
                return self.fail(FormError::limit(Limit::NameLength, at));
            }
            let value_at = Location::at(offset.saturating_add(name.len() as u64).saturating_add(1));
            if value.len() as u64 > u64::from(self.limits.value()) {
                return self.fail(FormError::limit(Limit::ValueLength, value_at));
            }
            self.text = self.text.saturating_add(value.len() as u64);
            if self.text > self.limits.text() {
                return self.fail(FormError::limit(Limit::TextTotal, value_at));
            }
            return Some(Ok(RawPair {
                name,
                value,
                flags,
                offset,
            }));
        }
    }
}

impl core::iter::FusedIterator for RawPairs<'_> {}

/// One `name=value` sequence, undecoded.
///
/// `Debug` prints the offset and the lengths only: values can be secrets.
#[derive(Clone, Copy)]
pub struct RawPair<'a> {
    name: &'a [u8],
    value: &'a [u8],
    flags: u8,
    offset: u64,
}

impl fmt::Debug for RawPair<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RawPair")
            .field("offset", &self.offset)
            .field("name_len", &self.name.len())
            .field("value_len", &self.value.len())
            .finish()
    }
}

impl<'a> RawPair<'a> {
    /// The name as sent, before decoding.
    ///
    /// # Examples
    ///
    /// ```
    /// let p = form_net::raw_pairs(b"a+b=1", &form_net::Limits::DEFAULT).next().unwrap()?;
    /// assert_eq!(p.name_raw(), b"a+b");
    /// # Ok::<(), form_net::FormError>(())
    /// ```
    #[must_use]
    pub const fn name_raw(&self) -> &'a [u8] {
        self.name
    }

    /// The value as sent, before decoding.
    ///
    /// # Examples
    ///
    /// ```
    /// let p = form_net::raw_pairs(b"a=%41", &form_net::Limits::DEFAULT).next().unwrap()?;
    /// assert_eq!(p.value_raw(), b"%41");
    /// # Ok::<(), form_net::FormError>(())
    /// ```
    #[must_use]
    pub const fn value_raw(&self) -> &'a [u8] {
        self.value
    }

    /// Whether the sequence contained `=`: `a` and `a=` both have an empty
    /// value, but only `a=` has an equals sign.
    ///
    /// # Examples
    ///
    /// ```
    /// use form_net::Limits;
    ///
    /// let mut it = form_net::raw_pairs(b"a&b=", &Limits::DEFAULT);
    /// assert!(!it.next().unwrap()?.has_equals());
    /// assert!(it.next().unwrap()?.has_equals());
    /// # Ok::<(), form_net::FormError>(())
    /// ```
    #[must_use]
    pub const fn has_equals(&self) -> bool {
        self.flags & HAS_EQUALS != 0
    }

    /// Whether the name contains `%` or `+`.
    ///
    /// # Examples
    ///
    /// ```
    /// let p = form_net::raw_pairs(b"a+b=1", &form_net::Limits::DEFAULT).next().unwrap()?;
    /// assert!(p.name_needs_decoding() && !p.value_needs_decoding());
    /// # Ok::<(), form_net::FormError>(())
    /// ```
    #[must_use]
    pub const fn name_needs_decoding(&self) -> bool {
        self.flags & NAME_DECODE != 0
    }

    /// Whether the value contains `%` or `+`.
    ///
    /// # Examples
    ///
    /// ```
    /// let p = form_net::raw_pairs(b"a=1%20", &form_net::Limits::DEFAULT).next().unwrap()?;
    /// assert!(p.value_needs_decoding());
    /// # Ok::<(), form_net::FormError>(())
    /// ```
    #[must_use]
    pub const fn value_needs_decoding(&self) -> bool {
        self.flags & VALUE_DECODE != 0
    }

    /// The name with no copy, when it needs no decoding and is valid UTF-8.
    ///
    /// # Examples
    ///
    /// ```
    /// let p = form_net::raw_pairs(b"email=x", &form_net::Limits::DEFAULT).next().unwrap()?;
    /// assert_eq!(p.name_str(), Some("email"));
    /// # Ok::<(), form_net::FormError>(())
    /// ```
    #[must_use]
    pub fn name_str(&self) -> Option<&'a str> {
        if self.name_needs_decoding() {
            None
        } else {
            core::str::from_utf8(self.name).ok()
        }
    }

    /// The value with no copy, when it needs no decoding and is valid UTF-8.
    ///
    /// # Examples
    ///
    /// ```
    /// let p = form_net::raw_pairs(b"q=a+b", &form_net::Limits::DEFAULT).next().unwrap()?;
    /// assert_eq!(p.value_str(), None);
    /// # Ok::<(), form_net::FormError>(())
    /// ```
    #[must_use]
    pub fn value_str(&self) -> Option<&'a str> {
        if self.value_needs_decoding() {
            None
        } else {
            core::str::from_utf8(self.value).ok()
        }
    }

    /// Decodes the name into `out` (see [`decode_into`](crate::decode_into)).
    ///
    /// # Errors
    ///
    /// `Encoding { InvalidPercent | InvalidUtf8 }` located in the body;
    /// `BufferTooSmall` when `out` is shorter than the raw name.
    ///
    /// # Examples
    ///
    /// ```
    /// use form_net::PercentPolicy;
    ///
    /// let p = form_net::raw_pairs(b"a%20b=1", &form_net::Limits::DEFAULT).next().unwrap()?;
    /// let mut out = [0u8; 16];
    /// assert_eq!(p.decode_name(&mut out, PercentPolicy::Refuse)?, "a b");
    /// # Ok::<(), form_net::FormError>(())
    /// ```
    pub fn decode_name<'b>(
        &self,
        out: &'b mut [u8],
        policy: PercentPolicy,
    ) -> Result<&'b str, FormError> {
        decode_component(self.name, out, policy).map_err(|e| e.shifted(self.offset))
    }

    /// Decodes the value into `out` (see [`decode_into`](crate::decode_into)).
    ///
    /// # Errors
    ///
    /// As [`decode_name`](Self::decode_name).
    ///
    /// # Examples
    ///
    /// ```
    /// use form_net::PercentPolicy;
    ///
    /// let p = form_net::raw_pairs(b"q=rust+forms", &form_net::Limits::DEFAULT).next().unwrap()?;
    /// let mut out = [0u8; 16];
    /// assert_eq!(p.decode_value(&mut out, PercentPolicy::Refuse)?, "rust forms");
    /// # Ok::<(), form_net::FormError>(())
    /// ```
    pub fn decode_value<'b>(
        &self,
        out: &'b mut [u8],
        policy: PercentPolicy,
    ) -> Result<&'b str, FormError> {
        let at = self
            .offset
            .saturating_add(self.name.len() as u64)
            .saturating_add(1);
        decode_component(self.value, out, policy).map_err(|e| e.shifted(at))
    }

    /// The byte offset of the sequence in the body.
    ///
    /// # Examples
    ///
    /// ```
    /// let mut it = form_net::raw_pairs(b"a=1&bb=2", &form_net::Limits::DEFAULT);
    /// let _ = it.next();
    /// assert_eq!(it.next().unwrap()?.offset(), 4);
    /// # Ok::<(), form_net::FormError>(())
    /// ```
    #[must_use]
    pub const fn offset(&self) -> u64 {
        self.offset
    }
}

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

    type Pairs<'a> = Vec<(&'a [u8], &'a [u8])>;

    fn pairs(input: &[u8]) -> Result<Pairs<'_>, FormError> {
        raw_pairs(input, &Limits::DEFAULT)
            .map(|p| p.map(|p| (p.name_raw(), p.value_raw())))
            .collect()
    }

    #[test]
    fn test_raw_pairs_whatwg_splitting() {
        assert_eq!(pairs(b"").unwrap(), []);
        assert_eq!(pairs(b"&&&").unwrap(), []);
        assert_eq!(pairs(b"=").unwrap(), [(&b""[..], &b""[..])]);
        assert_eq!(pairs(b"a==b").unwrap(), [(&b"a"[..], &b"=b"[..])]);
        assert_eq!(pairs(b"=a").unwrap(), [(&b""[..], &b"a"[..])]);
        assert_eq!(pairs(b"a;b=c").unwrap(), [(&b"a;b"[..], &b"c"[..])]);
        assert_eq!(
            pairs(b"a=1&b=2&").unwrap(),
            [(&b"a"[..], &b"1"[..]), (&b"b"[..], &b"2"[..])]
        );
    }

    #[test]
    fn test_raw_pairs_flags_per_side() {
        let p = raw_pairs(b"a%=b", &Limits::DEFAULT)
            .next()
            .unwrap()
            .unwrap();
        assert!(p.name_needs_decoding() && !p.value_needs_decoding());
        let p = raw_pairs(b"a=b+%", &Limits::DEFAULT)
            .next()
            .unwrap()
            .unwrap();
        assert!(!p.name_needs_decoding() && p.value_needs_decoding());
        let p = raw_pairs(b"a=b=+", &Limits::DEFAULT)
            .next()
            .unwrap()
            .unwrap();
        assert!(p.value_needs_decoding() && p.has_equals());
    }

    #[test]
    fn test_raw_pairs_field_limit_n_and_n_plus_one() {
        let l = Limits::DEFAULT.with_max_fields(2);
        assert_eq!(raw_pairs(b"a&b", &l).count(), 2);
        let r: Result<Vec<_>, _> = raw_pairs(b"a&b&c", &l).collect();
        assert!(matches!(
            r,
            Err(FormError::Limit {
                limit: Limit::Fields,
                at
            }) if at.offset == 4
        ));
    }

    #[test]
    fn test_raw_pairs_length_limits_at_the_edge() {
        let l = Limits::DEFAULT
            .with_max_name_bytes(3)
            .with_max_value_bytes(3);
        assert!(raw_pairs(b"abc=def", &l).all(|p| p.is_ok()));
        let e = raw_pairs(b"abcd=1", &l).next().unwrap().unwrap_err();
        assert!(matches!(
            e,
            FormError::Limit {
                limit: Limit::NameLength,
                ..
            }
        ));
        let e = raw_pairs(b"a=defg", &l).next().unwrap().unwrap_err();
        assert!(matches!(e, FormError::Limit { limit: Limit::ValueLength, at } if at.offset == 2));
        let l = Limits::DEFAULT.with_max_text_bytes(4);
        let r: Result<Vec<_>, _> = raw_pairs(b"a=12&b=345", &l).collect();
        assert!(matches!(
            r,
            Err(FormError::Limit {
                limit: Limit::TextTotal,
                ..
            })
        ));
    }

    #[test]
    fn test_raw_pairs_body_limit_counts_empty_sequences() {
        let l = Limits::DEFAULT.with_max_body_bytes(4);
        assert_eq!(raw_pairs(b"&&&&", &l).count(), 0);
        let e = raw_pairs(b"&&&&&", &l).next().unwrap().unwrap_err();
        assert!(matches!(
            e,
            FormError::Limit {
                limit: Limit::Body,
                ..
            }
        ));
    }

    #[test]
    fn test_raw_pairs_stops_after_error() {
        let l = Limits::DEFAULT.with_max_fields(0);
        let mut it = raw_pairs(b"a&b", &l);
        assert!(it.next().unwrap().is_err());
        assert!(it.next().is_none());
    }

    #[test]
    fn test_raw_pair_debug_hides_values() {
        let p = raw_pairs(b"password=hunter2", &Limits::DEFAULT)
            .next()
            .unwrap()
            .unwrap();
        let s = alloc::format!("{p:?}");
        assert!(!s.contains("hunter2") && !s.contains("password"));
    }
}