cpa-server 0.4.1

Part of cliproxy: HTTP routes, client auth, credential selection and the management API
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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
//! Credential uploads as gin's `c.MultipartForm()` reads them: Go's
//! `mime.ParseMediaType`, `mime/multipart.Reader` and the `textproto` header rules,
//! applied to a body that is already fully in memory.
//!
//! ponytail: no quoted-printable part decoding and no header count or size limits.

use axum::body::Bytes;
use axum::extract::rejection::BytesRejection;
use cpa_common::gostr::quote;
use cpa_core::gostr::GoStr;

use crate::body_limit::Read;
use std::borrow::Cow;
use std::collections::{BTreeMap, HashMap};

/// A file field of the form.
pub(super) struct FilePart {
    /// `filepath.Base` of the part's `filename` parameter; never empty.
    pub filename: String,
    pub data: Vec<u8>,
}

pub(super) type Files = BTreeMap<String, Vec<FilePart>>;

const NOT_MULTIPART: &str = "request Content-Type isn't multipart/form-data";
const MISSING_BOUNDARY: &str = "no multipart boundary param in Content-Type";
const TOO_LARGE: &str = "multipart: message too large";
const MAX_PARTS: usize = 1000;
/// Go `peekBufferSize`, the multipart reader's `bufio` size.
const PEEK_BUFFER: usize = 4096;

/// gin `Context.ContentType`: the header up to the first space or `;`, unchanged.
pub(super) fn is_form(content_type: &str) -> bool {
    content_type.split([' ', ';']).next() == Some("multipart/form-data")
}

/// File parts grouped by sorted field name (gin's handler sorts `form.File` keys),
/// in body order within a field. Errors carry Go's text.
pub(super) fn form_files(content_type: &str, body: &[u8]) -> Result<Vec<FilePart>, String> {
    Ok(form(content_type, body)?.0.into_values().flatten().collect())
}

/// `Request.ParseMultipartForm`: file parts and value parts by field name, each in body
/// order.
pub(super) fn form(content_type: &str, body: &[u8]) -> Result<(Files, HashMap<String, Vec<String>>), String> {
    let mut hit_limit = false;
    read_form(content_type, body, &mut hit_limit, false)
}

/// A multipart body that could not be used: the read failed before the limit, or Go's
/// `ParseMultipartForm` error with its status (`413` for the limit error).
pub(crate) enum Failed {
    Read(BytesRejection),
    Form(u16, String),
}

/// The body for `ParseMultipartForm`. When `server.max-request-body-bytes` stopped the
/// read, Go has parsed the bytes before the limit: the form is those bytes when it ends
/// within them, else the limit error inside file data and, inside a part's headers,
/// usually the parse error of the truncated line.
pub(crate) fn body(read: Read, content_type: &str) -> Result<Bytes, Failed> {
    match read.body {
        Err(rejection) if crate::body_limit::is_too_large(&rejection) => {
            let mut hit_limit = false;
            match read_form(content_type, &read.prefix, &mut hit_limit, true) {
                Ok(_) => Ok(read.prefix),
                Err(e) => Err(Failed::Form(if hit_limit { 413 } else { 400 }, e)),
            }
        }
        body => body.map_err(Failed::Read),
    }
}

/// `limited`: the body ends in `http.MaxBytesError` rather than EOF; `hit_limit` is set
/// when the reader runs into it.
fn read_form(
    content_type: &str,
    body: &[u8],
    hit_limit: &mut bool,
    limited: bool,
) -> Result<(Files, HashMap<String, Vec<String>>), String> {
    let (media, params) = parse_media_type(content_type).map_err(|_| NOT_MULTIPART.to_owned())?;
    if media != "multipart/form-data" {
        return Err(NOT_MULTIPART.into());
    }
    let boundary = params.get("boundary").ok_or(MISSING_BOUNDARY)?;
    let mut reader = Reader {
        buf: body,
        pos: 0,
        nl: b"\r\n",
        dash_boundary: format!("--{boundary}").into_bytes(),
        parts_read: 0,
        limited,
        hit_limit,
        window: 0,
        over: false,
    };
    let mut files: Files = BTreeMap::new();
    let mut values: HashMap<String, Vec<String>> = HashMap::new();
    let mut parts = 0;
    while let Some(headers) = reader.next_part()? {
        parts += 1;
        if parts > MAX_PARTS {
            return Err(TOO_LARGE.into());
        }
        let (disposition, params) = headers
            .get("content-disposition")
            .and_then(|v| parse_media_type(v).ok())
            .unwrap_or_default();
        let name = if disposition == "form-data" {
            params.get("name").cloned().unwrap_or_default()
        } else {
            String::new()
        };
        if name.is_empty() {
            // Go skips the part; a truncated body surfaces at the next boundary scan.
            if reader.body().is_err() {
                reader.pos = reader.buf.len();
            }
            continue;
        }
        let data = reader.body()?;
        let filename = params.get("filename").map(String::as_str).unwrap_or_default();
        if !filename.is_empty() {
            files.entry(name).or_default().push(FilePart {
                filename: go_base(filename).to_owned(),
                data,
            });
        } else {
            values
                .entry(name)
                .or_default()
                .push(String::from_utf8_lossy(&data).into_owned());
        }
    }
    Ok((files, values))
}

/// Go `filepath.Base` on Unix.
pub(super) fn go_base(path: &str) -> &str {
    if path.is_empty() {
        return ".";
    }
    let trimmed = path.trim_end_matches('/');
    if trimmed.is_empty() {
        return "/";
    }
    trimmed.rsplit('/').next().unwrap_or(trimmed)
}

struct Reader<'a, 'h> {
    buf: &'a [u8],
    pos: usize,
    nl: &'static [u8],
    dash_boundary: Vec<u8>,
    parts_read: usize,
    limited: bool,
    hit_limit: &'h mut bool,
    /// Limited parse: the end of what Go's 4096-byte `bufio.Reader` has pulled from
    /// the `MaxBytesReader`, and whether that reader has returned the limit error.
    /// Modelled with an underlying reader that fills every read it is given.
    window: usize,
    over: bool,
}

/// `bufio.Reader.ReadSlice('\n')` in the limited parse.
enum Slice<'a> {
    Line(&'a [u8]),
    /// `bufio.ErrBufferFull`: 4096 bytes without a newline.
    Full(&'a [u8]),
    /// The read error, with what was buffered before it.
    Over(&'a [u8]),
}

enum Scan {
    Data,
    End,
    UnexpectedEof,
}

impl<'a> Reader<'a, '_> {
    /// `bufio.Reader.ReadSlice('\n')`: the line with its newline, and whether the
    /// body ended before one.
    fn read_slice(&mut self) -> (&'a [u8], bool) {
        let rest = &self.buf[self.pos..];
        match rest.iter().position(|&b| b == b'\n') {
            Some(i) => {
                self.pos += i + 1;
                (&rest[..=i], false)
            }
            None => {
                self.pos = self.buf.len();
                (rest, true)
            }
        }
    }

    fn is_final_boundary(&self, line: &[u8]) -> bool {
        let mut dash_dash = self.dash_boundary.clone();
        dash_dash.extend_from_slice(b"--");
        line.strip_prefix(dash_dash.as_slice())
            .map(skip_lwsp)
            .is_some_and(|rest| rest.is_empty() || rest == self.nl)
    }

    fn is_boundary_delimiter_line(&mut self, line: &[u8]) -> bool {
        let Some(rest) = line.strip_prefix(self.dash_boundary.as_slice()).map(skip_lwsp) else {
            return false;
        };
        // Go switches to bare-LF mode when the first delimiter line ends in "\n".
        if self.parts_read == 0 && rest == b"\n" {
            self.nl = b"\n";
        }
        rest == self.nl
    }

    /// Go `Reader.nextPart`; `None` is a clean end of the form.
    fn next_part(&mut self) -> Result<Option<HashMap<String, String>>, String> {
        if self.dash_boundary == b"--" {
            return Err("multipart: boundary is empty".into());
        }
        let mut expect_new_part = false;
        loop {
            let line = if self.limited {
                match self.slice_go() {
                    Slice::Line(line) => line,
                    Slice::Full(_) => return Err("multipart: NextPart: bufio: buffer full".into()),
                    Slice::Over(_) => return Err(format!("multipart: NextPart: {}", self.end("EOF"))),
                }
            } else {
                let (line, eof) = self.read_slice();
                if eof && self.is_final_boundary(line) {
                    return Ok(None);
                }
                if eof {
                    return Err("multipart: NextPart: EOF".into());
                }
                line
            };
            if self.is_boundary_delimiter_line(line) {
                self.parts_read += 1;
                return self.headers();
            }
            if self.is_final_boundary(line) {
                return Ok(None);
            }
            if expect_new_part {
                return Err(format!("multipart: expecting a new Part; got line {}", quote(line)));
            }
            if self.parts_read == 0 {
                continue;
            }
            if line == self.nl {
                expect_new_part = true;
                continue;
            }
            return Err(format!("multipart: unexpected line in Next(): {}", quote(line)));
        }
    }

    /// bufio `fill` over the `MaxBytesReader`: a read of the free buffer space gets
    /// all of it, or the bytes left before the limit and the limit error.
    fn fill(&mut self) {
        let want = PEEK_BUFFER - (self.window - self.pos);
        let left = self.buf.len() - self.window;
        if want <= left {
            self.window += want;
        } else {
            self.window = self.buf.len();
            self.over = true;
        }
    }

    /// `bufio.Reader.ReadSlice('\n')` (the order of its checks matters: a newline,
    /// then the read error, then a full buffer).
    fn slice_go(&mut self) -> Slice<'a> {
        loop {
            let buffered = &self.buf[self.pos..self.window];
            if let Some(i) = buffered.iter().position(|&b| b == b'\n') {
                self.pos += i + 1;
                return Slice::Line(&buffered[..=i]);
            }
            if self.over {
                self.pos = self.window;
                return Slice::Over(buffered);
            }
            if buffered.len() >= PEEK_BUFFER {
                self.pos += PEEK_BUFFER;
                return Slice::Full(buffered);
            }
            self.fill();
        }
    }

    /// `bufio.Reader.ReadLine`: a line without its newline and whether it continues
    /// (a full buffer; a "\r" at its end is put back), or `None` for the read error.
    /// Bytes before the error come back as a line, the error with the next call.
    fn read_line_go(&mut self) -> Option<(&'a [u8], bool)> {
        match self.slice_go() {
            Slice::Full(line) => match line.strip_suffix(b"\r") {
                Some(line) => {
                    self.pos -= 1;
                    Some((line, true))
                }
                None => Some((line, true)),
            },
            Slice::Over([]) => None,
            Slice::Over(line) => Some((line, false)),
            Slice::Line(line) => {
                let line = &line[..line.len() - 1];
                Some((line.strip_suffix(b"\r").unwrap_or(line), false))
            }
        }
    }

    /// `textproto.Reader.readLineSlice`: the fragments of one line joined; the read
    /// error drops them. `Err` is `message too large` past `lim`.
    fn read_line_slice_go(&mut self, lim: usize) -> Result<Option<Cow<'a, [u8]>>, String> {
        let mut line: Option<Vec<u8>> = None;
        loop {
            let Some((part, more)) = self.read_line_go() else {
                return Ok(None);
            };
            if line.as_ref().map_or(0, Vec::len) + part.len() > lim {
                return Err(TOO_LARGE.into());
            }
            match (&mut line, more) {
                (None, false) => return Ok(Some(Cow::Borrowed(part))),
                (None, true) => line = Some(part.to_vec()),
                (Some(line), _) => line.extend_from_slice(part),
            }
            if !more {
                return Ok(line.map(Cow::Owned));
            }
        }
    }

    /// `textproto.Reader.skipSpace` (`ReadByte` fills an empty buffer).
    fn skip_space_go(&mut self) -> usize {
        let mut n = 0;
        loop {
            if self.pos == self.window {
                if self.over {
                    return n;
                }
                self.fill();
                continue;
            }
            if !matches!(self.buf[self.pos], b' ' | b'\t') {
                return n;
            }
            self.pos += 1;
            n += 1;
        }
    }

    /// One header line: the limited parse reads it as Go does, a whole body as one
    /// line up to its newline. `None` is the end of the body.
    fn header_line(&mut self, lim: usize) -> Result<Option<Cow<'a, [u8]>>, String> {
        if self.limited {
            return self.read_line_slice_go(lim);
        }
        Ok(self.read_line().map(Cow::Borrowed))
    }

    /// The read error at the end of the body: `eof`, or the limit error.
    fn end(&mut self, eof: &str) -> String {
        if !self.limited {
            return eof.to_owned();
        }
        *self.hit_limit = true;
        crate::body_limit::MESSAGE.to_owned()
    }

    /// `textproto.Reader.readLineSlice`: one line without its "\n" or "\r\n";
    /// `None` at the end of the body.
    fn read_line(&mut self) -> Option<&'a [u8]> {
        if self.pos >= self.buf.len() {
            return None;
        }
        let (line, _) = self.read_slice();
        Some(match line.strip_suffix(b"\n") {
            Some(line) => line.strip_suffix(b"\r").unwrap_or(line),
            None => line,
        })
    }

    /// Go `readMIMEHeader`, keyed by lowercased name; the first value wins for
    /// `Header.Get`. EOF inside the headers ends the form cleanly, as in Go; the limit
    /// error fails it.
    fn headers(&mut self) -> Result<Option<HashMap<String, String>>, String> {
        let mut headers = HashMap::new();
        // `Peek(1)`.
        if self.limited && self.pos == self.window && !self.over {
            self.fill();
        }
        let limited = self.limited;
        let visible = if limited { self.window } else { self.buf.len() };
        if matches!(self.buf[..visible].get(self.pos), Some(b' ' | b'\t')) {
            let Some(line) = self.header_line(80)? else {
                return self.ended();
            };
            if line.len() > 80 {
                return Err(TOO_LARGE.into());
            }
            return Err(format!("malformed MIME header initial line: {}", quote(&line)));
        }
        loop {
            let Some(first) = self.header_line(usize::MAX)? else {
                return self.ended();
            };
            let first = &*first;
            if first.is_empty() {
                return Ok(Some(headers));
            }
            if !first.contains(&b':') {
                return Err(format!("malformed MIME header: missing colon: {}", quote(first)));
            }
            // textproto trims spaces and tabs; a whole body keeps the wider trim.
            // ponytail: the limited parse only, where a cut line can end in "\r".
            let trim = if self.limited { go_trim } else { trim_ascii_space };
            let mut kv = trim(first).to_vec();
            loop {
                let spaces = if limited {
                    self.skip_space_go()
                } else {
                    let spaces = self.buf[self.pos..]
                        .iter()
                        .take_while(|&&b| b == b' ' || b == b'\t')
                        .count();
                    self.pos += spaces;
                    spaces
                };
                if spaces == 0 {
                    break;
                }
                kv.push(b' ');
                // Go stops at a continuation line it cannot read; the next line's read
                // reports the error.
                match self.header_line(usize::MAX)? {
                    Some(line) => kv.extend_from_slice(trim(&line)),
                    None => break,
                }
            }
            let malformed = || format!("malformed MIME header line: {}", quote(&kv));
            let colon = kv.iter().position(|&b| b == b':').unwrap_or(kv.len());
            let (key, value) = (&kv[..colon], &kv[(colon + 1).min(kv.len())..]);
            if !key.iter().all(|&b| is_header_field_byte(b) || b == b' ') {
                return Err(malformed());
            }
            if value.iter().any(|&b| (b < 0x20 && b != b'\t') || b == 0x7f) {
                return Err(malformed());
            }
            // Keys with a space are kept but never canonicalized, so `Get` misses them.
            if !key.contains(&b' ') {
                let value = value.iter().skip_while(|&&b| b == b' ' || b == b'\t');
                headers
                    .entry(String::from_utf8_lossy(key).to_ascii_lowercase())
                    .or_insert_with(|| String::from_utf8_lossy(&value.copied().collect::<Vec<_>>()).into_owned());
            }
        }
    }

    /// The headers ended with the body: a clean end of the form at EOF.
    fn ended(&mut self) -> Result<Option<HashMap<String, String>>, String> {
        match self.limited {
            false => Ok(None),
            true => Err(self.end("EOF")),
        }
    }

    /// The current part's body, up to its closing boundary (Go `partReader`).
    fn body(&mut self) -> Result<Vec<u8>, String> {
        if self.limited {
            return self.body_go();
        }
        let mut nl_dash = self.nl.to_vec();
        nl_dash.extend_from_slice(&self.dash_boundary);
        let mut data = Vec::new();
        let mut total = 0;
        loop {
            let rest = &self.buf[self.pos..];
            let (n, scan) = scan_until_boundary(rest, &self.dash_boundary, &nl_dash, total);
            data.extend_from_slice(&rest[..n]);
            self.pos += n;
            total += n;
            match scan {
                Scan::Data => {}
                Scan::End => return Ok(data),
                Scan::UnexpectedEof => return Err(self.end("unexpected EOF")),
            }
        }
    }
}

impl Reader<'_, '_> {
    /// `partReader.Read` until the part ends, over the bufio window: it scans what is
    /// buffered and fills only when the scan needs more (`Peek(len+1)`).
    fn body_go(&mut self) -> Result<Vec<u8>, String> {
        let mut nl_dash = self.nl.to_vec();
        nl_dash.extend_from_slice(&self.dash_boundary);
        let mut data = Vec::new();
        let (mut total, mut read_err) = (0, false);
        loop {
            let buffered = &self.buf[self.pos..self.window];
            let (n, end) = scan_go(buffered, &self.dash_boundary, &nl_dash, total, read_err);
            data.extend_from_slice(&buffered[..n]);
            self.pos += n;
            total += n;
            match end {
                Some(true) => return Ok(data),
                Some(false) => return Err(self.end("unexpected EOF")),
                None if n > 0 => {}
                None => {
                    let want = buffered.len() + 1;
                    while self.window - self.pos < want.min(PEEK_BUFFER) && !self.over {
                        self.fill();
                    }
                    read_err = self.window - self.pos < want;
                }
            }
        }
    }
}

/// Go `scanUntilBoundary`: the bytes that are part data, and `Some(true)` at the
/// boundary or `Some(false)` for the read error.
fn scan_go(buf: &[u8], dash: &[u8], nl_dash: &[u8], total: usize, read_err: bool) -> (usize, Option<bool>) {
    let err = read_err.then_some(false);
    if total == 0 {
        if buf.starts_with(dash) {
            return match match_after_go(buf, dash.len(), read_err) {
                -1 => (dash.len(), None),
                0 => (0, None),
                _ => (0, Some(true)),
            };
        }
        if dash.starts_with(buf) {
            return (0, err);
        }
    }
    if let Some(i) = buf.windows(nl_dash.len()).position(|w| w == nl_dash) {
        return match match_after_go(&buf[i..], nl_dash.len(), read_err) {
            -1 => (i + nl_dash.len(), None),
            0 => (i, None),
            _ => (i, Some(true)),
        };
    }
    if nl_dash.starts_with(buf) {
        return (0, err);
    }
    if let Some(i) = buf.iter().rposition(|&b| b == nl_dash[0])
        && nl_dash.starts_with(&buf[i..])
    {
        return (i, None);
    }
    (buf.len(), err)
}

/// Go `matchAfterPrefix`: +1 the boundary ends here, -1 it does not, 0 more input is
/// needed to tell.
fn match_after_go(buf: &[u8], prefix: usize, read_err: bool) -> i8 {
    match (buf.get(prefix), buf.get(prefix + 1)) {
        (None, _) => i8::from(read_err),
        (Some(b' ' | b'\t' | b'\r' | b'\n'), _) => 1,
        (Some(b'-'), None) => -i8::from(read_err),
        (Some(b'-'), Some(b'-')) => 1,
        _ => -1,
    }
}

/// Go `scanUntilBoundary` with the whole body buffered (the read error is set).
fn scan_until_boundary(buf: &[u8], dash: &[u8], nl_dash: &[u8], total: usize) -> (usize, Scan) {
    if total == 0 {
        if buf.starts_with(dash) {
            return match match_after_prefix(buf, dash) {
                true => (0, Scan::End),
                false => (dash.len(), Scan::Data),
            };
        }
        if dash.starts_with(buf) {
            return (0, Scan::UnexpectedEof);
        }
    }
    if let Some(i) = buf.windows(nl_dash.len()).position(|w| w == nl_dash) {
        return match match_after_prefix(&buf[i..], nl_dash) {
            true => (i, Scan::End),
            false => (i + nl_dash.len(), Scan::Data),
        };
    }
    if nl_dash.starts_with(buf) {
        return (0, Scan::UnexpectedEof);
    }
    if let Some(i) = buf.iter().rposition(|&b| b == nl_dash[0])
        && nl_dash.starts_with(&buf[i..])
    {
        return (i, Scan::Data);
    }
    (buf.len(), Scan::UnexpectedEof)
}

/// Go `matchAfterPrefix` at end of input: true when the boundary ends here.
fn match_after_prefix(buf: &[u8], prefix: &[u8]) -> bool {
    match buf.get(prefix.len()) {
        None => true,
        Some(b' ' | b'\t' | b'\r' | b'\n') => true,
        Some(b'-') => buf.get(prefix.len() + 1) == Some(&b'-'),
        Some(_) => false,
    }
}

fn skip_lwsp(b: &[u8]) -> &[u8] {
    let n = b.iter().take_while(|&&c| c == b' ' || c == b'\t').count();
    &b[n..]
}

/// textproto `trim`: spaces and tabs at both ends.
fn go_trim(b: &[u8]) -> &[u8] {
    let is_space = |c: &u8| matches!(c, b' ' | b'\t');
    let start = b.iter().position(|c| !is_space(c)).unwrap_or(b.len());
    let end = b.iter().rposition(|c| !is_space(c)).map_or(start, |i| i + 1);
    &b[start..end]
}

fn trim_ascii_space(b: &[u8]) -> &[u8] {
    let is_space = |c: &u8| matches!(c, b' ' | b'\t' | b'\n' | b'\r');
    let start = b.iter().position(|c| !is_space(c)).unwrap_or(b.len());
    let end = b.iter().rposition(|c| !is_space(c)).map_or(start, |i| i + 1);
    &b[start..end]
}

fn is_header_field_byte(b: u8) -> bool {
    b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b)
}

fn is_tspecial(c: u8) -> bool {
    b"()<>@,;:\\\"/[]?=".contains(&c)
}

fn is_token_char(c: u8) -> bool {
    c > 0x20 && c < 0x7f && !is_tspecial(c)
}

fn consume_token(v: &str) -> (&str, &str) {
    let i = v.bytes().position(|c| !is_token_char(c)).unwrap_or(v.len());
    v.split_at(i)
}

fn consume_value(v: &str) -> Option<(String, &str)> {
    if !v.starts_with('"') {
        let (token, rest) = consume_token(v);
        return Some((token.to_owned(), rest));
    }
    let bytes = v.as_bytes();
    let mut out = Vec::new();
    let mut i = 1;
    while i < bytes.len() {
        match bytes[i] {
            b'"' => return Some((String::from_utf8_lossy(&out).into_owned(), &v[i + 1..])),
            // Unnecessary escapes stay literal backslashes (MSIE paths).
            b'\\' if i + 1 < bytes.len() && is_tspecial(bytes[i + 1]) => {
                out.push(bytes[i + 1]);
                i += 1;
            }
            b'\r' | b'\n' => return None,
            b => out.push(b),
        }
        i += 1;
    }
    None
}

/// Go `consumeMediaParam`: `None` when `v` does not start with a valid parameter.
fn consume_media_param(v: &str) -> Option<(String, String, &str)> {
    let rest = v.trim_start().strip_prefix(';')?.trim_start();
    let (param, rest) = consume_token(rest);
    if param.is_empty() {
        return None;
    }
    let rest = rest.trim_start().strip_prefix('=')?.trim_start();
    let (value, after) = consume_value(rest)?;
    if value.is_empty() && after.len() == rest.len() {
        return None;
    }
    Some((param.go_lower(), value, after))
}

/// Go `mime.ParseMediaType`, including RFC 2231 continuations and charsets.
pub(super) fn parse_media_type(v: &str) -> Result<(String, HashMap<String, String>), ()> {
    let base = v.split(';').next().unwrap_or_default();
    let media = base.go_lower().trim().to_owned();
    let (kind, rest) = consume_token(&media);
    if kind.is_empty() {
        return Err(());
    }
    if !rest.is_empty() {
        let (sub, rest) = consume_token(rest.strip_prefix('/').ok_or(())?);
        if sub.is_empty() || !rest.is_empty() {
            return Err(());
        }
    }
    let mut params = HashMap::new();
    let mut continuation: HashMap<String, HashMap<String, String>> = HashMap::new();
    let mut v = &v[base.len()..];
    loop {
        v = v.trim_start();
        if v.is_empty() {
            break;
        }
        let Some((key, value, rest)) = consume_media_param(v) else {
            if v.trim() == ";" {
                break;
            }
            return Err(());
        };
        let map = match key.split_once('*') {
            Some((base_name, _)) => continuation.entry(base_name.to_owned()).or_default(),
            None => &mut params,
        };
        if map.get(&key).is_some_and(|existing| *existing != value) {
            return Err(());
        }
        map.insert(key, value);
        v = rest;
    }
    for (key, pieces) in continuation {
        if let Some(v) = pieces.get(&format!("{key}*")) {
            if let Some(decoded) = decode_2231(v) {
                params.insert(key, decoded);
            }
            continue;
        }
        let mut buf = String::new();
        let mut valid = false;
        for n in 0.. {
            if let Some(v) = pieces.get(&format!("{key}*{n}")) {
                valid = true;
                buf.push_str(v);
                continue;
            }
            let Some(v) = pieces.get(&format!("{key}*{n}*")) else {
                break;
            };
            valid = true;
            if n == 0 {
                buf.push_str(&decode_2231(v).unwrap_or_default());
            } else {
                buf.push_str(&percent_unescape(v).unwrap_or_default());
            }
        }
        if valid {
            params.insert(key, buf);
        }
    }
    Ok((media, params))
}

fn decode_2231(v: &str) -> Option<String> {
    let (charset, rest) = v.split_once('\'')?;
    let (_, value) = rest.split_once('\'')?;
    match charset.go_lower().as_str() {
        "us-ascii" | "utf-8" => percent_unescape(value),
        _ => None,
    }
}

/// Go `percentHexUnescape`.
fn percent_unescape(s: &str) -> Option<String> {
    let b = s.as_bytes();
    let mut out = Vec::with_capacity(b.len());
    let mut i = 0;
    while i < b.len() {
        if b[i] == b'%' {
            let hex = std::str::from_utf8(b.get(i + 1..i + 3)?).ok()?;
            out.push(
                u8::from_str_radix(hex, 16)
                    .ok()
                    .filter(|_| hex.bytes().all(|c| c.is_ascii_hexdigit()))?,
            );
            i += 3;
        } else {
            out.push(b[i]);
            i += 1;
        }
    }
    Some(String::from_utf8_lossy(&out).into_owned())
}

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

    const CT: &str = "multipart/form-data; boundary=b";

    #[test]
    fn reads_file_fields_sorted_by_field_and_skips_values() {
        let body = b"--b\r\nContent-Disposition: form-data; name=\"z\"; filename=\"dir/a.json\"\r\n\r\n{}\r\n--b\r\nContent-Disposition: form-data; name=\"f\"\r\n\r\nv\r\n--b\r\nContent-Disposition: form-data; name=\"c\"; filename=\"b.json\"\r\n\r\n[1]\r\n--b--\r\n";
        let files = form_files(CT, body).unwrap();
        let got: Vec<_> = files.iter().map(|f| (f.filename.as_str(), f.data.as_slice())).collect();
        // Field "c" sorts before field "z".
        assert_eq!(got, [("b.json", &b"[1]"[..]), ("a.json", &b"{}"[..])]);
    }

    #[test]
    fn media_type_params_follow_go() {
        let (t, p) = parse_media_type("Form-Data; Name=\"a\\\"b\"; filename*=UTF-8''x%2Ey; k*0=p; k*1*=%41").unwrap();
        assert_eq!(t, "form-data");
        assert_eq!(p["name"], "a\"b");
        assert_eq!(p["filename"], "x.y");
        assert_eq!(p["k"], "pA");
        assert!(parse_media_type("a/b; x=1; x=2").is_err());
        assert!(parse_media_type("a/b; x=1; x=1").is_ok());
        assert!(parse_media_type("a/b/c").is_err());
        assert!(parse_media_type("a/b; x=\"open").is_err());
    }

    /// Deterministic fuzz over boundary-shaped fragments: never panics, and any
    /// file returned has a non-empty base name.
    #[test]
    fn hostile_bodies_never_panic() {
        const PIECES: &[&[u8]] = &[
            b"--b",
            b"--",
            b"\r\n",
            b"\n",
            b"\r",
            b" ",
            b"\t",
            b"-",
            b"b",
            b"{}",
            b"Content-Disposition: form-data; name=\"f\"; filename=\"x.json\"",
            b"Content-Disposition: form-data; name=f",
            b"X:",
            b":",
            b"\x7f",
            b"\xff",
        ];
        let mut seed: u64 = 0x9e37_79b9_7f4a_7c15;
        let mut next = || {
            seed ^= seed << 13;
            seed ^= seed >> 7;
            seed ^= seed << 17;
            seed
        };
        for _ in 0..20_000 {
            let mut body = Vec::new();
            for _ in 0..(next() % 24) {
                body.extend_from_slice(PIECES[(next() % PIECES.len() as u64) as usize]);
            }
            if let Ok(files) = form_files(CT, &body) {
                assert!(
                    files
                        .iter()
                        .all(|f| !f.filename.is_empty() && !f.filename.contains('/'))
                );
            }
        }
    }
}