Skip to main content

form_net/multipart/
parser.rs

1//! The sans-IO multipart parser: a state machine over the delimiter matcher
2//! and the header reader.
3
4use core::fmt;
5
6use crate::error::{EncodingError, FormError, Limit, Location, PolicyRefusal, SyntaxError};
7use crate::limits::{CHARSET_CAPTURE, EmptyFilePolicy, Limits, Policy, TokenPlacement};
8use crate::multipart::boundary::Boundary;
9use crate::multipart::filename::FileName;
10use crate::multipart::header::{Areas, BlockScan, HeadFacts, Text, read_block};
11
12/// Whether a part is a text field or a file.
13///
14/// # Examples
15///
16/// ```
17/// # let body = b"--X\r\nContent-Disposition: form-data; name=a\r\n\r\n1\r\n--X--";
18/// let mp = form_net::parse_multipart(b"multipart/form-data; boundary=X", body)?;
19/// assert_eq!(mp.parts()[0].kind(), form_net::PartKind::Field);
20/// # Ok::<(), form_net::FormError>(())
21/// ```
22#[non_exhaustive]
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24pub enum PartKind {
25    /// A text field: no `filename` parameter.
26    Field,
27    /// A file: a `filename` parameter (even an empty one) or an accepted
28    /// `filename*`.
29    File,
30}
31
32/// The `charset` a part declared.
33///
34/// `Unspecified` means no `charset` parameter: UTF-8 is assumed unless a
35/// `_charset_` field before the part said otherwise. `Other` is any label
36/// that is not UTF-8 or US-ASCII; its text is refused by every text accessor.
37///
38/// # Examples
39///
40/// ```
41/// use form_net::Charset;
42///
43/// # let body = b"--X\r\nContent-Disposition: form-data; name=a\r\nContent-Type: text/plain; charset=UTF-8\r\n\r\n1\r\n--X--";
44/// # let mp = form_net::parse_multipart(b"multipart/form-data; boundary=X", body)?;
45/// assert_eq!(mp.parts()[0].content_type().unwrap().charset(), Charset::Utf8);
46/// # Ok::<(), form_net::FormError>(())
47/// ```
48#[non_exhaustive]
49#[derive(Clone, Copy, Debug, PartialEq, Eq)]
50pub enum Charset {
51    /// `utf-8`.
52    Utf8,
53    /// `us-ascii`.
54    Ascii,
55    /// No `charset` parameter.
56    Unspecified,
57    /// Any other label.
58    Other,
59}
60
61impl Charset {
62    pub(crate) fn from_label(label: &[u8]) -> Charset {
63        if label.eq_ignore_ascii_case(b"utf-8") {
64            Charset::Utf8
65        } else if label.eq_ignore_ascii_case(b"us-ascii") {
66            Charset::Ascii
67        } else {
68            Charset::Other
69        }
70    }
71}
72
73/// One step of the parser: how many input bytes it consumed, and what
74/// happened.
75#[non_exhaustive]
76#[derive(Debug)]
77pub struct Step<'p> {
78    /// Bytes of the input consumed; pass the rest (and later new bytes) to
79    /// the next call.
80    pub consumed: usize,
81    /// What happened.
82    pub event: Event<'p>,
83}
84
85/// What the parser found.
86///
87/// Per part the order is always `PartStart`, any number of `Data` (none for
88/// an empty part), `PartEnd`. A `Data` slice is never empty. After the last
89/// part comes `End`. `NeedInput` can appear anywhere between.
90///
91/// `Debug` prints the length of `Data`, never the bytes.
92#[non_exhaustive]
93pub enum Event<'p> {
94    /// A part's headers were read and checked.
95    PartStart(PartHead<'p>),
96    /// Bytes of the current part's data.
97    Data(&'p [u8]),
98    /// The current part ended.
99    PartEnd(PartSummary),
100    /// The close delimiter was read: the form is complete.
101    End,
102    /// Every byte given was consumed; give more.
103    NeedInput,
104}
105
106impl fmt::Debug for Event<'_> {
107    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108        match self {
109            Self::PartStart(head) => f.debug_tuple("PartStart").field(head).finish(),
110            Self::Data(bytes) => write!(f, "Data({} bytes)", bytes.len()),
111            Self::PartEnd(summary) => f.debug_tuple("PartEnd").field(summary).finish(),
112            Self::End => f.write_str("End"),
113            Self::NeedInput => f.write_str("NeedInput"),
114        }
115    }
116}
117
118/// What one part was.
119#[non_exhaustive]
120#[derive(Clone, Copy, Debug, PartialEq, Eq)]
121pub struct PartSummary {
122    /// The part index, from 0.
123    pub index: u32,
124    /// Field or file.
125    pub kind: PartKind,
126    /// The length of the part's data.
127    pub bytes: u64,
128    /// Whether the part was skipped (by `skip_part` or an inspector).
129    pub skipped: bool,
130}
131
132/// The validated header block of one part, borrowed.
133///
134/// A head is only produced after every header budget and rule passed.
135#[derive(Clone, Copy)]
136pub struct PartHead<'p> {
137    index: u32,
138    block: &'p [u8],
139    name: &'p str,
140    name_raw: &'p [u8],
141    kind: PartKind,
142    filename: Option<FileName<'p>>,
143    content_type: Option<&'p [u8]>,
144    charset: Charset,
145}
146
147impl fmt::Debug for PartHead<'_> {
148    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
149        f.debug_struct("PartHead")
150            .field("index", &self.index)
151            .field("name", &self.name)
152            .field("kind", &self.kind)
153            .field("filename", &self.filename)
154            .finish_non_exhaustive()
155    }
156}
157
158impl<'p> PartHead<'p> {
159    /// A head over bytes kept elsewhere (an owned copy).
160    #[cfg(feature = "alloc")]
161    #[allow(clippy::too_many_arguments)]
162    pub(crate) const fn from_parts(
163        index: u32,
164        block: &'p [u8],
165        name: &'p str,
166        name_raw: &'p [u8],
167        kind: PartKind,
168        filename: Option<FileName<'p>>,
169        content_type: Option<&'p [u8]>,
170        charset: Charset,
171    ) -> Self {
172        Self {
173            index,
174            block,
175            name,
176            name_raw,
177            kind,
178            filename,
179            content_type,
180            charset,
181        }
182    }
183
184    /// The header block, the final CRLF CRLF included.
185    #[cfg(feature = "alloc")]
186    pub(crate) const fn block(&self) -> &'p [u8] {
187        self.block
188    }
189
190    /// The part index, from 0, in body order.
191    #[must_use]
192    pub const fn index(&self) -> u32 {
193        self.index
194    }
195
196    /// The field name, with `%0A`, `%0D`, `%22` decoded to LF, CR, `"` (no
197    /// other escape is decoded). Always valid UTF-8 and never empty.
198    #[must_use]
199    pub const fn name(&self) -> &'p str {
200        self.name
201    }
202
203    /// The field name as sent.
204    #[must_use]
205    pub const fn name_raw(&self) -> &'p [u8] {
206        self.name_raw
207    }
208
209    /// Field or file.
210    #[must_use]
211    pub const fn kind(&self) -> PartKind {
212        self.kind
213    }
214
215    /// Whether this is a file part.
216    #[must_use]
217    pub const fn is_file(&self) -> bool {
218        matches!(self.kind, PartKind::File)
219    }
220
221    /// The client's file name, for file parts.
222    #[must_use]
223    pub const fn filename(&self) -> Option<FileName<'p>> {
224        self.filename
225    }
226
227    /// The declared `Content-Type`: a hint, never trusted.
228    #[must_use]
229    pub fn content_type(&self) -> Option<ContentType<'p>> {
230        self.content_type.and_then(ContentType::parse)
231    }
232
233    /// The part's own `charset` parameter (`Unspecified` when absent).
234    #[must_use]
235    pub const fn charset(&self) -> Charset {
236        self.charset
237    }
238
239    /// Every header line, in order, as raw `(name, value)` bytes.
240    #[must_use]
241    pub fn headers(&self) -> Headers<'p> {
242        Headers { rest: self.block }
243    }
244
245    /// The size of the header block, the final CRLF CRLF included.
246    #[must_use]
247    pub const fn header_bytes(&self) -> u32 {
248        self.block.len() as u32
249    }
250}
251
252/// A part's declared `Content-Type`, already checked. **A hint**: the client
253/// chose it.
254///
255/// # Examples
256///
257/// ```
258/// # let body = b"--X\r\nContent-Disposition: form-data; name=f; filename=a.png\r\nContent-Type: Image/PNG; q=\"x y\"\r\n\r\n\r\n--X--";
259/// # let mp = form_net::parse_multipart(b"multipart/form-data; boundary=X", body)?;
260/// let ct = mp.file("f").unwrap().content_type().unwrap();
261/// assert!(ct.is("image", "png"));
262/// assert_eq!((ct.type_(), ct.subtype()), ("Image", "PNG"));
263/// assert_eq!(ct.parameter("Q"), Some(&b"x y"[..]));
264/// # Ok::<(), form_net::FormError>(())
265/// ```
266#[derive(Clone, Copy)]
267pub struct ContentType<'p> {
268    raw: &'p [u8],
269    media: parse_net::MediaType<'p>,
270}
271
272impl fmt::Debug for ContentType<'_> {
273    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
274        f.debug_struct("ContentType")
275            .field("type", &self.type_())
276            .field("subtype", &self.subtype())
277            .finish_non_exhaustive()
278    }
279}
280
281impl<'p> ContentType<'p> {
282    pub(crate) fn parse(raw: &'p [u8]) -> Option<ContentType<'p>> {
283        parse_net::media::parse(raw, &crate::kind::HEADER_LIMITS)
284            .ok()
285            .map(|media| ContentType { raw, media })
286    }
287
288    /// The value as sent.
289    #[must_use]
290    pub const fn raw(&self) -> &'p [u8] {
291        self.raw
292    }
293
294    /// The type, as sent.
295    #[must_use]
296    pub fn type_(&self) -> &'p str {
297        core::str::from_utf8(self.media.type_()).unwrap_or("")
298    }
299
300    /// The subtype, as sent.
301    #[must_use]
302    pub fn subtype(&self) -> &'p str {
303        core::str::from_utf8(self.media.subtype()).unwrap_or("")
304    }
305
306    /// Whether the type and subtype are these, ASCII case-insensitively.
307    #[must_use]
308    pub fn is(&self, type_: &str, subtype: &str) -> bool {
309        self.media.is(type_, subtype)
310    }
311
312    /// A parameter's value by name (ASCII case-insensitive), without
313    /// surrounding quotes; backslashes are literal, as browsers send them.
314    #[must_use]
315    pub fn parameter(&self, name: &str) -> Option<&'p [u8]> {
316        self.media
317            .params()
318            .get(name)
319            .map(|w| crate::kind::word_raw(&w))
320    }
321
322    /// The `charset` parameter.
323    #[must_use]
324    pub fn charset(&self) -> Charset {
325        self.parameter("charset")
326            .map_or(Charset::Unspecified, Charset::from_label)
327    }
328}
329
330/// Every header line of a part, in order, as raw `(name, value)` bytes with
331/// the value trimmed.
332///
333/// `Debug` prints the header names only: values carry file names.
334#[derive(Clone)]
335pub struct Headers<'p> {
336    rest: &'p [u8],
337}
338
339impl fmt::Debug for Headers<'_> {
340    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
341        let mut list = f.debug_list();
342        for (name, _) in self.clone() {
343            list.entry(&core::str::from_utf8(name).unwrap_or("?"));
344        }
345        list.finish()
346    }
347}
348
349impl<'p> Iterator for Headers<'p> {
350    type Item = (&'p [u8], &'p [u8]);
351
352    fn next(&mut self) -> Option<Self::Item> {
353        let lf = self.rest.iter().position(|&b| b == b'\n')?;
354        let line = self.rest.get(..lf.saturating_sub(1)).unwrap_or(&[]);
355        self.rest = self.rest.get(lf.wrapping_add(1)..).unwrap_or(&[]);
356        if line.is_empty() {
357            self.rest = &[];
358            return None;
359        }
360        let colon = line.iter().position(|&b| b == b':').unwrap_or(line.len());
361        let name = line.get(..colon).unwrap_or(&[]);
362        let value = line.get(colon.wrapping_add(1)..).unwrap_or(&[]);
363        Some((name, parse_net::text::trim_ows(value)))
364    }
365}
366
367#[derive(Clone, Copy, Debug, PartialEq, Eq)]
368enum State {
369    Preamble,
370    /// After a delimiter: expecting `--`, padding, or CRLF.
371    AfterDelimiter(After),
372    Headers,
373    Body,
374    /// The delimiter that ends the current part was found; `PartEnd` is due.
375    EndOfPart,
376    Epilogue,
377    Poisoned,
378}
379
380#[derive(Clone, Copy, Debug, PartialEq, Eq)]
381enum After {
382    Start,
383    Dash,
384    Padding(u8),
385    Cr,
386}
387
388/// The token field's progress.
389#[derive(Clone, Copy, Debug, PartialEq, Eq)]
390enum Token {
391    NotSeen,
392    Capturing,
393    Captured,
394}
395
396const SKIPPING: u8 = 1;
397const IS_TOKEN: u8 = 2;
398const IS_CHARSET: u8 = 4;
399const DEFERRED: u8 = 8;
400
401/// Where a head's block is.
402#[derive(Clone, Copy, Debug)]
403pub(crate) enum Source {
404    /// In the input, from this index.
405    Input(usize),
406    /// In the parser buffer, from 0.
407    Buffer,
408}
409
410/// What a call to `advance` produced, as positions only.
411#[derive(Clone, Copy, Debug)]
412pub(crate) enum Outcome {
413    PartStart(HeadFacts, Source),
414    /// `input[start..end]`.
415    DataInput(usize, usize),
416    /// The first bytes of the delimiter.
417    DataDelimiter(usize),
418    PartEnd(PartSummary),
419    End,
420    NeedInput,
421}
422
423/// The sans-IO `multipart/form-data` parser.
424///
425/// Feed it bytes as they arrive, in chunks of any size split at any byte;
426/// it returns one [`Event`] per call and how many bytes it consumed. The
427/// events are identical for every split of the same body. It never
428/// allocates after construction and never rescans a byte: the delimiter
429/// search is a streaming Knuth-Morris-Pratt automaton with an eight-byte skip
430/// to the next CR.
431///
432/// The buffer holds the header block, the decoded field name, the decoded
433/// `filename*` (under `AcceptAlone`), the token, and the `_charset_` value:
434/// [`Limits::multipart_buffer_len`] bytes. It is wiped on `reset` and on
435/// drop.
436///
437/// # Examples
438///
439/// ```
440/// use form_net::{Event, FormKind, Limits, MultipartParser, Policy};
441///
442/// let content_type = b"multipart/form-data; boundary=X";
443/// let body = b"--X\r\nContent-Disposition: form-data; name=\"title\"\r\n\r\nHoliday\r\n--X--\r\n";
444/// let FormKind::Multipart(boundary) = FormKind::detect(content_type)? else { unreachable!() };
445/// let mut parser = MultipartParser::new(boundary, &Limits::DEFAULT, &Policy::DEFAULT)?;
446///
447/// let mut events = Vec::new();
448/// let mut chunks = body.chunks(7).peekable();     // any split gives the same events
449/// while let Some(chunk) = chunks.next() {
450///     let last = chunks.peek().is_none();
451///     let mut rest = chunk;
452///     loop {
453///         let step = parser.parse(rest, last)?;
454///         rest = &rest[step.consumed..];
455///         match step.event {
456///             Event::PartStart(head) => events.push(format!("start {}", head.name())),
457///             Event::Data(bytes) => events.push(format!("data {}", bytes.len())),
458///             Event::PartEnd(summary) => events.push(format!("end {}", summary.bytes)),
459///             Event::End => break,
460///             Event::NeedInput => break,
461///             _ => {}
462///         }
463///     }
464/// }
465/// assert!(parser.is_done());
466/// assert_eq!(events.first().map(String::as_str), Some("start title"));
467/// assert_eq!(events.last().map(String::as_str), Some("end 7"));
468/// # Ok::<(), form_net::FormError>(())
469/// ```
470pub struct MultipartParser<B: AsMut<[u8]> + AsRef<[u8]>> {
471    boundary: Boundary,
472    limits: Limits,
473    policy: Policy,
474    buffer: B,
475    state: State,
476    /// Delimiter bytes matched and not yet known to be data.
477    k: u8,
478    flags: u8,
479    token: Token,
480    token_len: u16,
481    charset_len: u8,
482    charset_done: bool,
483    scan: BlockScan,
484    /// Header bytes copied into the buffer.
485    copied: u32,
486    /// The longest header block read so far: every byte the parser writes
487    /// into the header, name, and file-name areas lies within this many
488    /// bytes of each area's start (decoding never lengthens), so the wipe
489    /// covers exactly what was written (D-103).
490    dirty: u32,
491    parts: u32,
492    files: u32,
493    fields: u32,
494    kind: PartKind,
495    part_bytes: u64,
496    text_total: u64,
497    data_start: u64,
498    preamble: u64,
499    epilogue: u64,
500    /// Where the current header block starts in the body.
501    head_start: u64,
502    /// Where the epilogue starts in the body.
503    epilogue_start: u64,
504    bytes_seen: u64,
505}
506
507impl<B: AsMut<[u8]> + AsRef<[u8]>> fmt::Debug for MultipartParser<B> {
508    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
509        f.debug_struct("MultipartParser")
510            .field("boundary", &self.boundary)
511            .field("state", &self.state)
512            .field("bytes_seen", &self.bytes_seen)
513            .field("parts_seen", &self.parts)
514            .finish_non_exhaustive()
515    }
516}
517
518#[cfg(feature = "alloc")]
519impl MultipartParser<alloc::vec::Vec<u8>> {
520    /// A parser with its own buffer of
521    /// [`Limits::multipart_buffer_len`] bytes, allocated once.
522    ///
523    /// # Errors
524    ///
525    /// `InvalidLimits` from validating the limits with the policy.
526    ///
527    /// # Examples
528    ///
529    /// ```
530    /// use form_net::{Boundary, Limits, MultipartParser, Policy};
531    ///
532    /// let parser = MultipartParser::new(Boundary::new(b"X")?, &Limits::DEFAULT, &Policy::DEFAULT)?;
533    /// assert_eq!(parser.bytes_seen(), 0);
534    /// # Ok::<(), form_net::FormError>(())
535    /// ```
536    pub fn new(boundary: Boundary, limits: &Limits, policy: &Policy) -> Result<Self, FormError> {
537        limits.validate_with(policy)?;
538        let buffer = alloc::vec![0u8; limits.multipart_buffer_len(policy)];
539        Self::with_buffer(boundary, limits, policy, buffer)
540    }
541}
542
543impl<B: AsMut<[u8]> + AsRef<[u8]>> MultipartParser<B> {
544    /// A parser over a buffer the caller provides; it never allocates.
545    ///
546    /// # Errors
547    ///
548    /// `InvalidLimits`; `BufferTooSmall` when `buffer` is shorter than
549    /// [`Limits::multipart_buffer_len`].
550    ///
551    /// # Examples
552    ///
553    /// ```
554    /// use form_net::{Boundary, Limits, MultipartParser, Policy};
555    ///
556    /// const LIMITS: Limits = Limits::DEFAULT.with_max_part_header_bytes(1024);
557    /// const LEN: usize = LIMITS.multipart_buffer_len(&Policy::DEFAULT);
558    /// let mut buffer = [0u8; LEN];
559    /// let parser = MultipartParser::with_buffer(Boundary::new(b"X")?, &LIMITS, &Policy::DEFAULT, &mut buffer[..])?;
560    /// # Ok::<(), form_net::FormError>(())
561    /// ```
562    pub fn with_buffer(
563        boundary: Boundary,
564        limits: &Limits,
565        policy: &Policy,
566        buffer: B,
567    ) -> Result<Self, FormError> {
568        limits.validate_with(policy)?;
569        let needed = limits.multipart_buffer_len(policy);
570        if buffer.as_ref().len() < needed {
571            return Err(FormError::BufferTooSmall { needed });
572        }
573        Ok(Self {
574            boundary,
575            limits: *limits,
576            policy: *policy,
577            buffer,
578            state: State::Preamble,
579            // The body may start with `--boundary`: start as if CRLF had
580            // been seen.
581            k: 2,
582            flags: 0,
583            token: Token::NotSeen,
584            token_len: 0,
585            charset_len: 0,
586            charset_done: false,
587            scan: BlockScan::default(),
588            copied: 0,
589            dirty: 0,
590            parts: 0,
591            files: 0,
592            fields: 0,
593            kind: PartKind::Field,
594            part_bytes: 0,
595            text_total: 0,
596            data_start: 0,
597            preamble: 0,
598            epilogue: 0,
599            head_start: 0,
600            epilogue_start: 0,
601            bytes_seen: 0,
602        })
603    }
604
605    /// Consumes a prefix of `input` and returns one event. `eof = true` says
606    /// `input` ends the body.
607    ///
608    /// # Errors
609    ///
610    /// Every multipart error (see the crate's `docs/API.md`); `Poisoned`
611    /// after any error until [`reset`](Self::reset).
612    pub fn parse<'p>(&'p mut self, input: &'p [u8], eof: bool) -> Result<Step<'p>, FormError> {
613        let (consumed, outcome) = self.advance(input, eof)?;
614        Ok(Step {
615            consumed,
616            event: self.view(outcome, input),
617        })
618    }
619
620    /// Discards the rest of the current part: its bytes are consumed and
621    /// counted against the budgets but produce no `Data` events, and its
622    /// summary has `skipped = true`. Outside a part it does nothing.
623    pub fn skip_part(&mut self) {
624        if matches!(self.state, State::Body) {
625            self.flags |= SKIPPING;
626        }
627    }
628
629    /// Returns the parser to its initial state for a new body, wipes its
630    /// buffer, and clears the poisoned state. It never allocates.
631    pub fn reset(&mut self, boundary: Boundary) {
632        self.wipe_used();
633        let limits = self.limits;
634        let policy = self.policy;
635        self.boundary = boundary;
636        self.state = State::Preamble;
637        self.k = 2;
638        self.flags = 0;
639        self.token = Token::NotSeen;
640        self.token_len = 0;
641        self.charset_len = 0;
642        self.charset_done = false;
643        self.scan = BlockScan::default();
644        self.copied = 0;
645        self.parts = 0;
646        self.files = 0;
647        self.fields = 0;
648        self.kind = PartKind::Field;
649        self.part_bytes = 0;
650        self.text_total = 0;
651        self.data_start = 0;
652        self.preamble = 0;
653        self.epilogue = 0;
654        self.head_start = 0;
655        self.epilogue_start = 0;
656        self.bytes_seen = 0;
657        self.limits = limits;
658        self.policy = policy;
659    }
660
661    /// Body bytes consumed so far.
662    #[must_use]
663    pub const fn bytes_seen(&self) -> u64 {
664        self.bytes_seen
665    }
666
667    /// Parts started so far.
668    #[must_use]
669    pub const fn parts_seen(&self) -> u32 {
670        self.parts
671    }
672
673    /// File parts counted so far.
674    #[must_use]
675    pub const fn files_seen(&self) -> u32 {
676        self.files
677    }
678
679    /// Whether the close delimiter was read.
680    #[must_use]
681    pub fn is_done(&self) -> bool {
682        self.state == State::Epilogue
683    }
684
685    /// The limits the parser was built with.
686    #[must_use]
687    pub const fn limits(&self) -> &Limits {
688        &self.limits
689    }
690
691    /// The policy the parser was built with.
692    #[must_use]
693    pub const fn policy(&self) -> &Policy {
694        &self.policy
695    }
696
697    /// The token field's value, once its part has ended.
698    #[must_use]
699    pub fn captured_token(&self) -> Option<&str> {
700        if self.token != Token::Captured {
701            return None;
702        }
703        let start = self.token_area();
704        let bytes = self
705            .buffer
706            .as_ref()
707            .get(start..start.saturating_add(usize::from(self.token_len)))?;
708        core::str::from_utf8(bytes).ok()
709    }
710
711    /// The value of the last complete `_charset_` field.
712    #[must_use]
713    pub fn declared_charset(&self) -> Option<&[u8]> {
714        if !self.charset_done {
715            return None;
716        }
717        let start = self.charset_area();
718        self.buffer
719            .as_ref()
720            .get(start..start.saturating_add(usize::from(self.charset_len)))
721    }
722
723    /// The decoded name of the last head, `len` bytes in the name area.
724    #[cfg(feature = "alloc")]
725    pub(crate) fn area_name(&self, len: u32) -> &str {
726        let start = self.name_area();
727        let bytes = self
728            .buffer
729            .as_ref()
730            .get(start..start.saturating_add(len as usize))
731            .unwrap_or(&[]);
732        core::str::from_utf8(bytes).unwrap_or("")
733    }
734
735    /// The decoded `filename*` of the last head, `len` bytes.
736    #[cfg(feature = "alloc")]
737    pub(crate) fn area_filename(&self, len: u32) -> &[u8] {
738        let start = self.filename_area();
739        self.buffer
740            .as_ref()
741            .get(start..start.saturating_add(len as usize))
742            .unwrap_or(&[])
743    }
744
745    /// Where the current part's data starts in the body.
746    #[cfg(feature = "alloc")]
747    pub(crate) const fn data_start(&self) -> u64 {
748        self.data_start
749    }
750
751    // Buffer layout: header block, name, filename (AcceptAlone), token, charset.
752
753    fn name_area(&self) -> usize {
754        self.limits.max_part_header_bytes as usize
755    }
756
757    fn filename_area(&self) -> usize {
758        self.name_area().saturating_add(self.limits.name() as usize)
759    }
760
761    fn token_area(&self) -> usize {
762        let filename = if matches!(
763            self.policy.extended_filename,
764            crate::ExtendedFilenamePolicy::AcceptAlone
765        ) {
766            self.limits.filename() as usize
767        } else {
768            0
769        };
770        self.filename_area().saturating_add(filename)
771    }
772
773    fn charset_area(&self) -> usize {
774        let token = if self.policy.token_field.is_some() {
775            usize::from(self.limits.token())
776        } else {
777            0
778        };
779        self.token_area().saturating_add(token)
780    }
781
782    /// The location of the current part's header block.
783    fn head_at(&self) -> Location {
784        Location::in_part(self.parts.checked_sub(1), self.head_start)
785    }
786
787    /// The location of the first data byte past a budget of `limit` of
788    /// which `used` is spent, in the current part.
789    fn excess(&self, used: u64, limit: u64) -> Location {
790        let into_part = self.part_bytes.saturating_add(limit.saturating_sub(used));
791        Location::in_part(
792            self.parts.checked_sub(1),
793            self.data_start.saturating_add(into_part),
794        )
795    }
796
797    fn at(&self, pos: usize) -> Location {
798        let part = if matches!(self.state, State::Preamble | State::Epilogue) {
799            None
800        } else {
801            self.parts.checked_sub(1)
802        };
803        Location::in_part(part, self.bytes_seen.saturating_add(pos as u64))
804    }
805
806    /// Runs the state machine and returns positions only, so callers that
807    /// own the input for longer (the buffered parser) can slice it
808    /// themselves.
809    pub(crate) fn advance(
810        &mut self,
811        input: &[u8],
812        eof: bool,
813    ) -> Result<(usize, Outcome), FormError> {
814        if self.state == State::Poisoned {
815            return Err(FormError::Poisoned);
816        }
817        match self.run(input, eof) {
818            Ok((consumed, outcome)) => {
819                self.bytes_seen = self.bytes_seen.saturating_add(consumed as u64);
820                Ok((consumed, outcome))
821            }
822            Err(e) => {
823                self.state = State::Poisoned;
824                Err(e)
825            }
826        }
827    }
828
829    fn run(&mut self, input: &[u8], eof: bool) -> Result<(usize, Outcome), FormError> {
830        if self.bytes_seen.saturating_add(input.len() as u64) > self.limits.body() {
831            return Err(FormError::limit(
832                Limit::Body,
833                Location::at(self.limits.body()),
834            ));
835        }
836        let mut pos = 0usize;
837        loop {
838            let hay = input.get(pos..).unwrap_or(&[]);
839            match self.state {
840                State::Poisoned => return Err(FormError::Poisoned),
841                State::Preamble => {
842                    if let Some(after) = self.preamble_step(hay)? {
843                        pos = pos.wrapping_add(after);
844                        self.state = State::AfterDelimiter(After::Start);
845                        continue;
846                    }
847                    if eof {
848                        return Err(FormError::syntax(
849                            SyntaxError::NoInitialDelimiter,
850                            self.at(input.len()),
851                        ));
852                    }
853                    return Ok((input.len(), Outcome::NeedInput));
854                }
855                State::AfterDelimiter(sub) => {
856                    let Some(&c) = hay.first() else {
857                        return self.need_input(input.len(), eof);
858                    };
859                    pos = pos.wrapping_add(1);
860                    let at = self.at(pos);
861                    self.state = match (sub, c) {
862                        (After::Start, b'-') => State::AfterDelimiter(After::Dash),
863                        (After::Dash, b'-') => {
864                            self.state = State::Epilogue;
865                            self.epilogue_start = self.bytes_seen.saturating_add(pos as u64);
866                            return Ok((pos, Outcome::End));
867                        }
868                        (After::Start, b' ' | b'\t') => {
869                            if self.limits.max_padding_bytes == 0 {
870                                return Err(FormError::limit(Limit::Padding, at));
871                            }
872                            State::AfterDelimiter(After::Padding(1))
873                        }
874                        (After::Padding(n), b' ' | b'\t') => {
875                            if n >= self.limits.max_padding_bytes {
876                                return Err(FormError::limit(Limit::Padding, at));
877                            }
878                            State::AfterDelimiter(After::Padding(n.saturating_add(1)))
879                        }
880                        (After::Start | After::Padding(_), b'\r') => {
881                            State::AfterDelimiter(After::Cr)
882                        }
883                        (After::Cr, b'\n') => {
884                            self.parts = self.parts.saturating_add(1);
885                            if self.parts > self.limits.max_parts {
886                                return Err(FormError::limit(Limit::Parts, self.at(pos)));
887                            }
888                            self.scan = BlockScan::default();
889                            self.copied = 0;
890                            self.head_start = self.bytes_seen.saturating_add(pos as u64);
891                            State::Headers
892                        }
893                        (After::Start | After::Padding(_), b'\n') => {
894                            return Err(FormError::syntax(SyntaxError::BareLineFeed, at));
895                        }
896                        _ => return Err(FormError::syntax(SyntaxError::BoundaryInContent, at)),
897                    };
898                }
899                State::Headers => {
900                    let at = self.head_at();
901                    match self.scan.feed(hay, &self.limits, at)? {
902                        Some(end) => {
903                            let source = if self.copied == 0 {
904                                Source::Input(pos)
905                            } else {
906                                self.copy_header(hay.get(..end).unwrap_or(&[]), at)?;
907                                Source::Buffer
908                            };
909                            let block_start_in_input = pos;
910                            pos = pos.wrapping_add(end);
911                            let facts =
912                                self.read_head(input, source, block_start_in_input, end, at)?;
913                            let (is_token, is_charset) = {
914                                let block = self.block(&facts, source, input);
915                                let name = self.name_bytes(&facts, block);
916                                let token = self
917                                    .policy
918                                    .token_field
919                                    .is_some_and(|t| name == t.name().as_bytes());
920                                (token, name == b"_charset_")
921                            };
922                            self.start_part(&facts, is_token, is_charset, at)?;
923                            self.data_start = self.bytes_seen.saturating_add(pos as u64);
924                            return Ok((pos, Outcome::PartStart(facts, source)));
925                        }
926                        None => {
927                            self.copy_header(hay, at)?;
928                            return self.need_input(input.len(), eof);
929                        }
930                    }
931                }
932                State::Body => {
933                    if hay.is_empty() {
934                        return self.need_input(input.len(), eof);
935                    }
936                    match self.body_step(hay, pos, input.len(), eof)? {
937                        BodyStep::Emit(consumed, outcome) => return Ok((consumed, outcome)),
938                        BodyStep::Continue(next) => pos = next,
939                    }
940                }
941                State::EndOfPart => {
942                    let summary = self.end_part(self.at(pos))?;
943                    self.state = State::AfterDelimiter(After::Start);
944                    return Ok((pos, Outcome::PartEnd(summary)));
945                }
946                State::Epilogue => {
947                    self.epilogue = self.epilogue.saturating_add(hay.len() as u64);
948                    if self.epilogue > self.limits.epilogue() {
949                        let at = self.epilogue_start.saturating_add(self.limits.epilogue());
950                        return Err(FormError::limit(Limit::Epilogue, Location::at(at)));
951                    }
952                    return Ok((input.len(), Outcome::End));
953                }
954            }
955        }
956    }
957
958    fn need_input(&self, len: usize, eof: bool) -> Result<(usize, Outcome), FormError> {
959        if eof {
960            Err(FormError::syntax(SyntaxError::Truncated, self.at(len)))
961        } else {
962            Ok((len, Outcome::NeedInput))
963        }
964    }
965
966    /// Scans the preamble. Returns the index in `hay` just after the first
967    /// delimiter, or `None` when all of `hay` was consumed.
968    fn preamble_step(&mut self, hay: &[u8]) -> Result<Option<usize>, FormError> {
969        let len = self.boundary.len() as u64;
970        // A delimiter must end within max_preamble_bytes + its own length.
971        let budget = self.limits.preamble().saturating_add(len);
972        let room = usize::try_from(budget.saturating_sub(self.preamble)).unwrap_or(usize::MAX);
973        let window = hay.get(..room.min(hay.len())).unwrap_or(hay);
974        let (k, found) = self.boundary.run(usize::from(self.k), window);
975        self.k = k as u8;
976        match found {
977            Some(after) => {
978                // Real bytes up to the end of the delimiter; a delimiter that
979                // includes the two virtual bytes (CRLF) starts the body.
980                let end = self.preamble.saturating_add(after as u64);
981                let preamble = end.saturating_sub(len);
982                if preamble > self.limits.preamble() {
983                    return Err(FormError::limit(
984                        Limit::Preamble,
985                        Location::at(self.limits.preamble()),
986                    ));
987                }
988                self.k = 0;
989                Ok(Some(after))
990            }
991            None => {
992                self.preamble = self.preamble.saturating_add(window.len() as u64);
993                if window.len() < hay.len() || self.preamble >= budget {
994                    return Err(FormError::limit(
995                        Limit::Preamble,
996                        Location::at(self.limits.preamble()),
997                    ));
998                }
999                Ok(None)
1000            }
1001        }
1002    }
1003
1004    fn copy_header(&mut self, bytes: &[u8], at: Location) -> Result<(), FormError> {
1005        let start = self.copied as usize;
1006        let end = start.saturating_add(bytes.len());
1007        if end > self.limits.max_part_header_bytes as usize {
1008            return Err(FormError::limit(Limit::PartHeaderBytes, at));
1009        }
1010        match self.buffer.as_mut().get_mut(start..end) {
1011            Some(dst) => dst.copy_from_slice(bytes),
1012            None => return Err(FormError::limit(Limit::PartHeaderBytes, at)),
1013        }
1014        self.copied = end as u32;
1015        self.dirty = self.dirty.max(self.copied);
1016        Ok(())
1017    }
1018
1019    fn read_head(
1020        &mut self,
1021        input: &[u8],
1022        source: Source,
1023        start: usize,
1024        end: usize,
1025        at: Location,
1026    ) -> Result<HeadFacts, FormError> {
1027        let name_area = self.name_area();
1028        let filename_area = self.filename_area();
1029        let filename_end = self.token_area();
1030        let limits = self.limits;
1031        let policy = self.policy;
1032        let copied = self.copied as usize;
1033        let block_len = match source {
1034            Source::Input(_) => end,
1035            Source::Buffer => copied,
1036        };
1037        self.dirty = self.dirty.max(u32::try_from(block_len).unwrap_or(u32::MAX));
1038        let buf = self.buffer.as_mut();
1039        let (head, rest) = buf.split_at_mut(name_area.min(buf.len()));
1040        let (name, rest) =
1041            rest.split_at_mut(filename_area.saturating_sub(name_area).min(rest.len()));
1042        let filename = rest
1043            .get_mut(..filename_end.saturating_sub(filename_area))
1044            .unwrap_or(&mut []);
1045        let block = match source {
1046            Source::Input(_) => input.get(start..start.saturating_add(end)).unwrap_or(&[]),
1047            Source::Buffer => head.get(..copied).unwrap_or(&[]),
1048        };
1049        read_block(block, &limits, &policy, Areas { name, filename }, at)
1050    }
1051
1052    /// The budgets and rules that apply when a part starts.
1053    fn start_part(
1054        &mut self,
1055        facts: &HeadFacts,
1056        is_token: bool,
1057        is_charset: bool,
1058        at: Location,
1059    ) -> Result<(), FormError> {
1060        self.state = State::Body;
1061        self.k = 0;
1062        self.flags = 0;
1063        self.kind = facts.kind;
1064        self.part_bytes = 0;
1065        match facts.kind {
1066            PartKind::Field => {
1067                self.fields = self.fields.saturating_add(1);
1068                if self.fields > self.limits.max_fields {
1069                    return Err(FormError::limit(Limit::Fields, at));
1070                }
1071                if is_token {
1072                    if self.token != Token::NotSeen {
1073                        return Err(FormError::policy(PolicyRefusal::DuplicateToken, at));
1074                    }
1075                    self.token = Token::Capturing;
1076                    self.token_len = 0;
1077                    self.flags |= IS_TOKEN;
1078                }
1079                if is_charset {
1080                    self.flags |= IS_CHARSET;
1081                    self.charset_len = 0;
1082                    self.charset_done = false;
1083                }
1084            }
1085            PartKind::File => {
1086                let empty = matches!(facts.filename, Some((Text::Block(span), _)) if span.len == 0)
1087                    || matches!(facts.filename, Some((Text::Area(0), _)));
1088                if empty && self.policy.empty_files == EmptyFilePolicy::Skip {
1089                    self.flags |= DEFERRED;
1090                } else {
1091                    self.count_file(at)?;
1092                }
1093            }
1094        }
1095        Ok(())
1096    }
1097
1098    /// The block of a head, wherever it is.
1099    fn block<'a>(&'a self, facts: &HeadFacts, source: Source, input: &'a [u8]) -> &'a [u8] {
1100        let len = facts.block_len as usize;
1101        match source {
1102            Source::Input(start) => input.get(start..start.saturating_add(len)).unwrap_or(&[]),
1103            Source::Buffer => self.buffer.as_ref().get(..len).unwrap_or(&[]),
1104        }
1105    }
1106
1107    /// The decoded name of a head.
1108    fn name_bytes<'a>(&'a self, facts: &HeadFacts, block: &'a [u8]) -> &'a [u8] {
1109        match facts.name {
1110            Text::Block(span) => span.get(block),
1111            Text::Area(len) => {
1112                let start = self.name_area();
1113                self.buffer
1114                    .as_ref()
1115                    .get(start..start.saturating_add(len as usize))
1116                    .unwrap_or(&[])
1117            }
1118        }
1119    }
1120
1121    /// The borrowed view of a head.
1122    fn head_view<'p>(&'p self, facts: &HeadFacts, source: Source, input: &'p [u8]) -> PartHead<'p> {
1123        let block = self.block(facts, source, input);
1124        let name = core::str::from_utf8(self.name_bytes(facts, block)).unwrap_or("");
1125        let filename = facts.filename.map(|(text, origin)| {
1126            let raw = match text {
1127                Text::Block(span) => span.get(block),
1128                Text::Area(len) => {
1129                    let start = self.filename_area();
1130                    self.buffer
1131                        .as_ref()
1132                        .get(start..start.saturating_add(len as usize))
1133                        .unwrap_or(&[])
1134                }
1135            };
1136            FileName::new(raw, origin)
1137        });
1138        PartHead {
1139            index: self.parts.saturating_sub(1),
1140            block,
1141            name,
1142            name_raw: facts.name_raw.get(block),
1143            kind: facts.kind,
1144            filename,
1145            content_type: facts.content_type.map(|span| span.get(block)),
1146            charset: facts.charset,
1147        }
1148    }
1149
1150    /// Turns positions into borrowed events.
1151    fn view<'p>(&'p self, outcome: Outcome, input: &'p [u8]) -> Event<'p> {
1152        match outcome {
1153            Outcome::PartStart(facts, source) => {
1154                Event::PartStart(self.head_view(&facts, source, input))
1155            }
1156            Outcome::DataInput(start, end) => Event::Data(input.get(start..end).unwrap_or(&[])),
1157            Outcome::DataDelimiter(n) => {
1158                Event::Data(self.boundary.delimiter().get(..n).unwrap_or(&[]))
1159            }
1160            Outcome::PartEnd(summary) => Event::PartEnd(summary),
1161            Outcome::End => Event::End,
1162            Outcome::NeedInput => Event::NeedInput,
1163        }
1164    }
1165
1166    fn count_file(&mut self, at: Location) -> Result<(), FormError> {
1167        self.files = self.files.saturating_add(1);
1168        if self.files > self.limits.max_files {
1169            return Err(FormError::limit(Limit::Files, at));
1170        }
1171        if let Some(t) = self.policy.token_field {
1172            if t.placement() == TokenPlacement::BeforeFirstFile && self.token != Token::Captured {
1173                return Err(FormError::policy(PolicyRefusal::TokenFieldLate, at));
1174            }
1175        }
1176        Ok(())
1177    }
1178
1179    /// Checks budgets for `n` more data bytes of the current part, and
1180    /// captures the token or `_charset_` value.
1181    fn take_data(&mut self, bytes: &[u8]) -> Result<(), FormError> {
1182        let n = bytes.len() as u64;
1183        if n == 0 {
1184            return Ok(());
1185        }
1186        if self.flags & DEFERRED != 0 {
1187            self.flags &= !DEFERRED;
1188            let at = Location::in_part(self.parts.checked_sub(1), self.data_start);
1189            self.count_file(at)?;
1190        }
1191        let total = self.part_bytes.saturating_add(n);
1192        match self.kind {
1193            PartKind::File => {
1194                let limit = self.limits.file();
1195                if total > limit {
1196                    let at = self.excess(self.part_bytes, limit);
1197                    return Err(FormError::limit(Limit::FileSize, at));
1198                }
1199            }
1200            PartKind::Field => {
1201                let limit = u64::from(self.limits.value());
1202                if total > limit {
1203                    let at = self.excess(self.part_bytes, limit);
1204                    return Err(FormError::limit(Limit::ValueLength, at));
1205                }
1206                let text = self.text_total.saturating_add(n);
1207                let limit = self.limits.text();
1208                if text > limit {
1209                    let at = self.excess(self.text_total, limit);
1210                    return Err(FormError::limit(Limit::TextTotal, at));
1211                }
1212                self.text_total = text;
1213            }
1214        }
1215        if self.flags & IS_TOKEN != 0 {
1216            let start = self
1217                .token_area()
1218                .saturating_add(usize::from(self.token_len));
1219            let end = start.saturating_add(bytes.len());
1220            let limit = u64::from(self.limits.token());
1221            let at = self.excess(u64::from(self.token_len), limit);
1222            if end
1223                > self
1224                    .token_area()
1225                    .saturating_add(usize::from(self.limits.token()))
1226            {
1227                return Err(FormError::limit(Limit::TokenLength, at));
1228            }
1229            match self.buffer.as_mut().get_mut(start..end) {
1230                Some(dst) => dst.copy_from_slice(bytes),
1231                None => return Err(FormError::limit(Limit::TokenLength, at)),
1232            }
1233            self.token_len = self.token_len.saturating_add(bytes.len() as u16);
1234        }
1235        if self.flags & IS_CHARSET != 0 {
1236            let start = self
1237                .charset_area()
1238                .saturating_add(usize::from(self.charset_len));
1239            let end = start.saturating_add(bytes.len());
1240            let at = self.excess(u64::from(self.charset_len), CHARSET_CAPTURE as u64);
1241            if end > self.charset_area().saturating_add(CHARSET_CAPTURE) {
1242                return Err(FormError::encoding(EncodingError::UnsupportedCharset, at));
1243            }
1244            match self.buffer.as_mut().get_mut(start..end) {
1245                Some(dst) => dst.copy_from_slice(bytes),
1246                None => return Err(FormError::encoding(EncodingError::UnsupportedCharset, at)),
1247            }
1248            self.charset_len = self.charset_len.saturating_add(bytes.len() as u8);
1249        }
1250        self.part_bytes = total;
1251        Ok(())
1252    }
1253
1254    fn end_part(&mut self, at: Location) -> Result<PartSummary, FormError> {
1255        if self.flags & IS_TOKEN != 0 {
1256            let start = self.token_area();
1257            let bytes = self
1258                .buffer
1259                .as_ref()
1260                .get(start..start.saturating_add(usize::from(self.token_len)))
1261                .unwrap_or(&[]);
1262            if core::str::from_utf8(bytes).is_err() {
1263                return Err(FormError::encoding(EncodingError::InvalidUtf8, at));
1264            }
1265            self.token = Token::Captured;
1266        }
1267        if self.flags & IS_CHARSET != 0 {
1268            self.charset_done = true;
1269        }
1270        let summary = PartSummary {
1271            index: self.parts.saturating_sub(1),
1272            kind: self.kind,
1273            bytes: self.part_bytes,
1274            skipped: self.flags & SKIPPING != 0,
1275        };
1276        self.flags = 0;
1277        self.k = 0;
1278        Ok(summary)
1279    }
1280
1281    /// One step in a part's data. `pos` is where `hay` starts in the input.
1282    fn body_step(
1283        &mut self,
1284        hay: &[u8],
1285        pos: usize,
1286        input_len: usize,
1287        eof: bool,
1288    ) -> Result<BodyStep, FormError> {
1289        let len = self.boundary.len();
1290        let k0 = usize::from(self.k);
1291        if k0 > 0 {
1292            // Bytes from earlier chunks that matched the start of the
1293            // delimiter: resolve them before anything else.
1294            let mut k = k0;
1295            for (i, &c) in hay.iter().enumerate() {
1296                k = self.boundary.step(k, c);
1297                let n = i.wrapping_add(1);
1298                if k == len {
1299                    // The delimiter started inside the held bytes.
1300                    let data = k0.saturating_add(n).saturating_sub(len);
1301                    self.k = 0;
1302                    self.state = State::EndOfPart;
1303                    return self.emit_delimiter_bytes(data, pos.wrapping_add(n));
1304                }
1305                if k <= n {
1306                    // Every held byte is data; scan the input again from 0.
1307                    self.k = 0;
1308                    return self.emit_delimiter_bytes(k0, pos);
1309                }
1310            }
1311            // All of `hay` extended the partial match.
1312            let n = hay.len();
1313            if eof {
1314                return Err(FormError::syntax(
1315                    SyntaxError::Truncated,
1316                    self.at(input_len),
1317                ));
1318            }
1319            let data = k0.saturating_add(n).saturating_sub(k);
1320            self.k = k as u8;
1321            return self.emit_delimiter_bytes(data, input_len);
1322        }
1323        let (k, found) = self.boundary.run(0, hay);
1324        match found {
1325            Some(after) => {
1326                let data = after.saturating_sub(len);
1327                self.k = 0;
1328                self.state = State::EndOfPart;
1329                let bytes = hay.get(..data).unwrap_or(&[]);
1330                self.emit_input_bytes(bytes, pos, pos.wrapping_add(data), pos.wrapping_add(after))
1331            }
1332            None => {
1333                if eof {
1334                    return Err(FormError::syntax(
1335                        SyntaxError::Truncated,
1336                        self.at(input_len),
1337                    ));
1338                }
1339                self.k = k as u8;
1340                let data_end = hay.len().saturating_sub(k);
1341                let bytes = hay.get(..data_end).unwrap_or(&[]);
1342                self.emit_input_bytes(bytes, pos, pos.wrapping_add(data_end), input_len)
1343            }
1344        }
1345    }
1346
1347    /// Emits `delimiter[..n]` as data (or skips it), consuming up to
1348    /// `consumed`.
1349    fn emit_delimiter_bytes(&mut self, n: usize, consumed: usize) -> Result<BodyStep, FormError> {
1350        let boundary = self.boundary;
1351        let bytes = boundary.delimiter().get(..n).unwrap_or(&[]);
1352        self.take_data(bytes)?;
1353        if n == 0 || self.flags & SKIPPING != 0 {
1354            return Ok(BodyStep::Continue(consumed));
1355        }
1356        Ok(BodyStep::Emit(consumed, Outcome::DataDelimiter(n)))
1357    }
1358
1359    /// Emits `input[start..end]` as data (or skips it), consuming up to
1360    /// `consumed`.
1361    fn emit_input_bytes(
1362        &mut self,
1363        bytes: &[u8],
1364        start: usize,
1365        end: usize,
1366        consumed: usize,
1367    ) -> Result<BodyStep, FormError> {
1368        self.take_data(bytes)?;
1369        if start == end || self.flags & SKIPPING != 0 {
1370            return Ok(BodyStep::Continue(consumed));
1371        }
1372        Ok(BodyStep::Emit(consumed, Outcome::DataInput(start, end)))
1373    }
1374}
1375
1376/// What a body step did.
1377enum BodyStep {
1378    Emit(usize, Outcome),
1379    Continue(usize),
1380}
1381
1382impl<B: AsMut<[u8]> + AsRef<[u8]>> MultipartParser<B> {
1383    /// Wipes every byte the parser wrote into its buffer, and nothing more:
1384    /// a buffer of the default size is 9.6 KiB, and a login form writes a
1385    /// few hundred bytes of it (D-103).
1386    fn wipe_used(&mut self) {
1387        let used = self.dirty as usize;
1388        let regions = [
1389            (0, used.min(self.name_area())),
1390            (
1391                self.name_area(),
1392                used.min(self.filename_area().saturating_sub(self.name_area())),
1393            ),
1394            (
1395                self.filename_area(),
1396                used.min(self.token_area().saturating_sub(self.filename_area())),
1397            ),
1398            (self.token_area(), usize::from(self.token_len)),
1399            // The whole capture area: a second, shorter `_charset_` value
1400            // resets the length over the tail of the first (found by review).
1401            (self.charset_area(), CHARSET_CAPTURE),
1402        ];
1403        let buf = self.buffer.as_mut();
1404        for (start, len) in regions {
1405            if let Some(region) = buf.get_mut(start..start.saturating_add(len)) {
1406                crate::wipe::wipe(region);
1407            }
1408        }
1409        self.dirty = 0;
1410    }
1411}
1412
1413impl<B: AsMut<[u8]> + AsRef<[u8]>> Drop for MultipartParser<B> {
1414    fn drop(&mut self) {
1415        self.wipe_used();
1416    }
1417}
1418
1419#[cfg(test)]
1420mod tests {
1421    use super::*;
1422
1423    /// D-103: the wipe covers every byte the parser wrote. With a caller
1424    /// buffer the result is visible: after a body that writes every area
1425    /// (header blocks, an escaped name, a decoded `filename*`, the token,
1426    /// `_charset_`), dropping or resetting leaves the buffer all zeros.
1427    #[test]
1428    fn test_wipe_covers_every_area_written() {
1429        let policy = Policy::DEFAULT
1430            .with_extended_filename(crate::ExtendedFilenamePolicy::AcceptAlone)
1431            .with_token_field(crate::TokenField::new("csrf"));
1432        let limits = Limits::DEFAULT.with_max_part_header_bytes(512);
1433        let long = "x".repeat(300);
1434        let body = alloc::format!(
1435            "--X\r\nContent-Disposition: form-data; name=csrf\r\n\r\nsecret-token-value\r\n\
1436             --X\r\nContent-Disposition: form-data; name=_charset_\r\n\r\nUTF-8\r\n\
1437             --X\r\nContent-Disposition: form-data; name=\"pass%22word\"\r\nX-Pad: {long}\r\n\r\nhunter2\r\n\
1438             --X\r\nContent-Disposition: form-data; name=f; filename*=UTF-8''caf%C3%A9.txt\r\n\r\nfile\r\n--X--"
1439        );
1440        // Two `_charset_` values, the second shorter: the first one's tail
1441        // must not survive (found by review).
1442        let body = body.replace(
1443            "name=_charset_\r\n\r\nUTF-8\r\n",
1444            "name=_charset_\r\n\r\nunicode-1-1-utf-8\r\n--X\r\nContent-Disposition: form-data; name=_charset_\r\n\r\nutf8\r\n",
1445        );
1446        assert!(body.contains("unicode-1-1-utf-8"));
1447        for split in [usize::MAX, 7, 1] {
1448            let mut buf = alloc::vec![0u8; limits.multipart_buffer_len(&policy)];
1449            {
1450                let mut p = MultipartParser::with_buffer(
1451                    Boundary::new(b"X").unwrap(),
1452                    &limits,
1453                    &policy,
1454                    &mut buf[..],
1455                )
1456                .unwrap();
1457                let bytes = body.as_bytes();
1458                let chunks: alloc::vec::Vec<&[u8]> = bytes.chunks(split.min(bytes.len())).collect();
1459                let mut ended = false;
1460                for (i, c) in chunks.iter().enumerate() {
1461                    let last = i + 1 == chunks.len();
1462                    let mut rest = *c;
1463                    loop {
1464                        let step = p.parse(rest, last).unwrap();
1465                        rest = &rest[step.consumed..];
1466                        match step.event {
1467                            Event::NeedInput => break,
1468                            Event::End => {
1469                                ended = true;
1470                                break;
1471                            }
1472                            _ => {}
1473                        }
1474                    }
1475                }
1476                assert!(ended);
1477                assert_eq!(p.captured_token(), Some("secret-token-value"));
1478            }
1479            assert!(
1480                buf.iter().all(|&b| b == 0),
1481                "split {split}: bytes left at {:?}",
1482                buf.iter().position(|&b| b != 0)
1483            );
1484        }
1485    }
1486
1487    #[test]
1488    fn test_parser_size_is_bounded() {
1489        // NFR-18 as measured: the boundary and its matcher table are 149 of
1490        // these bytes; the buffer is separate.
1491        assert!(core::mem::size_of::<MultipartParser<&mut [u8]>>() <= 384);
1492        assert!(core::mem::size_of::<Boundary>() <= 150);
1493    }
1494
1495    #[cfg(feature = "alloc")]
1496    #[test]
1497    fn test_debug_never_shows_data_or_file_names() {
1498        let body = b"--X\r\nContent-Disposition: form-data; name=f; filename=\"secret.pdf\"\r\n\r\nhunter2\r\n--X--";
1499        let mut p = MultipartParser::new(
1500            Boundary::new(b"X").unwrap(),
1501            &Limits::DEFAULT,
1502            &Policy::DEFAULT,
1503        )
1504        .unwrap();
1505        let mut rest: &[u8] = body;
1506        let mut seen = alloc::string::String::new();
1507        loop {
1508            let step = p.parse(rest, true).unwrap();
1509            rest = &rest[step.consumed..];
1510            if let Event::PartStart(head) = &step.event {
1511                seen.push_str(&alloc::format!("{:?}", head.headers()));
1512            }
1513            seen.push_str(&alloc::format!("{step:?}"));
1514            if matches!(step.event, Event::End) {
1515                break;
1516            }
1517        }
1518        assert!(seen.contains("Data(7 bytes)"), "{seen}");
1519        assert!(
1520            !seen.contains("hunter2") && !seen.contains("secret"),
1521            "{seen}"
1522        );
1523    }
1524
1525    #[test]
1526    fn test_charset_labels() {
1527        assert_eq!(Charset::from_label(b"UTF-8"), Charset::Utf8);
1528        assert_eq!(Charset::from_label(b"us-ascii"), Charset::Ascii);
1529        assert_eq!(Charset::from_label(b"utf8"), Charset::Other);
1530    }
1531}