multra 1.3.0

An async parser for `multipart/form-data` content-type in Rust.
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
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll};

use bytes::Bytes;
use futures_util::future;
use futures_util::stream::{Stream, TryStreamExt};
#[cfg(feature = "tokio-io")]
use {tokio::io::AsyncRead, tokio_util::io::ReaderStream};

use crate::buffer::StreamBuffer;
use crate::constraints::Constraints;
use crate::content_disposition::ContentDisposition;
use crate::error::Error;
use crate::field::Field;
use crate::{Result, constants, helpers};

/// Represents the implementation of `multipart/form-data` formatted data.
///
/// This will parse the source stream into [`Field`] instances via
/// [`next_field()`](Self::next_field).
///
/// # Errors and cancellation
///
/// Stop parsing and discard this instance after a stream, parsing, or
/// constraint error. Recovery after these errors is not guaranteed. If
/// [`Error::LockFailure`] is returned because a previous field is still alive,
/// drop that field before retrying.
///
/// Cancelling a pending [`Self::next_field`] or [`Field::chunk`] operation keeps
/// the parsing progress in this instance, so that operation can be retried.
///
/// # Field Exclusivity
///
/// A `Field` represents a raw, self-decoding stream into multipart data. As
/// such, only _one_ `Field` from a given `Multipart` instance may be live at
/// once. That is, a `Field` emitted by `next_field()` must be dropped before
/// calling `next_field()` again. Failure to do so will result in an error.
///
/// ```rust
/// use std::convert::Infallible;
///
/// use bytes::Bytes;
/// use futures_util::stream::once;
/// use multra::Multipart;
///
/// # async fn run() {
/// let data = "--X-BOUNDARY\r\nContent-Disposition: form-data; \
///     name=\"my_text_field\"\r\n\r\nabcd\r\n--X-BOUNDARY--\r\n";
///
/// let stream = once(async move { Result::<Bytes, Infallible>::Ok(Bytes::from(data)) });
/// let mut multipart = Multipart::new(stream, "X-BOUNDARY");
///
/// let field1 = multipart.next_field().await;
/// let field2 = multipart.next_field().await;
///
/// assert!(field2.is_err());
/// # }
/// # tokio::runtime::Runtime::new().unwrap().block_on(run());
/// ```
///
/// # Examples
///
/// ```
/// use std::convert::Infallible;
///
/// use bytes::Bytes;
/// use futures_util::stream::once;
/// use multra::Multipart;
///
/// # async fn run() {
/// let data = "--X-BOUNDARY\r\nContent-Disposition: form-data; \
///     name=\"my_text_field\"\r\n\r\nabcd\r\n--X-BOUNDARY--\r\n";
///
/// let stream = once(async move { Result::<Bytes, Infallible>::Ok(Bytes::from(data)) });
/// let mut multipart = Multipart::new(stream, "X-BOUNDARY");
///
/// while let Some(field) = multipart.next_field().await.unwrap() {
///     println!("Field: {:?}", field.text().await)
/// }
/// # }
/// # tokio::runtime::Runtime::new().unwrap().block_on(run());
/// ```
#[derive(Debug)]
pub struct Multipart<'r> {
    state: Arc<Mutex<MultipartState<'r>>>,
}

#[derive(Debug)]
pub struct MultipartState<'r> {
    pub(crate) buffer: StreamBuffer<'r>,
    pub(crate) boundary_bytes: Vec<u8>,
    pub(crate) field_boundary_bytes: Vec<u8>,
    pub(crate) stage: StreamingStage,
    pub(crate) next_field_idx: usize,
    pub(crate) curr_field_name: Option<String>,
    pub(crate) curr_field_size_limit: u64,
    pub(crate) curr_field_size_counter: u64,
    pub(crate) constraints: Constraints,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StreamingStage {
    FindingFirstBoundary,
    ReadingBoundary,
    DeterminingBoundaryType,
    ReadingTransportPadding,
    ReadingClosingTransportPadding,
    ReadingFieldHeaders,
    ReadingFieldData,
    ReadingEpilogue,
    Eof,
}

impl<'r> Multipart<'r> {
    /// Construct a new `Multipart` instance with the given [`Bytes`] stream and
    /// the boundary.
    ///
    /// This constructor keeps the default unbounded size limits for backward
    /// compatibility. For untrusted input, prefer [`Multipart::with_constraints`].
    pub fn new<S, O, E, B>(stream: S, boundary: B) -> Self
    where
        S: Stream<Item = Result<O, E>> + Send + 'r,
        O: Into<Bytes> + 'static,
        E: Into<Box<dyn std::error::Error + Send + Sync>> + 'r,
        B: Into<String>,
    {
        Multipart::with_constraints(stream, boundary, Constraints::default())
    }

    /// Construct a new `Multipart` instance after validating the boundary.
    ///
    /// This constructor keeps the default unbounded size limits for backward
    /// compatibility. For untrusted input, prefer
    /// [`Multipart::try_with_constraints`].
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidBoundary`] if the boundary is empty, longer
    /// than 70 bytes, or contains characters that are not valid in a multipart
    /// boundary.
    pub fn try_new<S, O, E, B>(stream: S, boundary: B) -> Result<Self>
    where
        S: Stream<Item = Result<O, E>> + Send + 'r,
        O: Into<Bytes> + 'static,
        E: Into<Box<dyn std::error::Error + Send + Sync>> + 'r,
        B: Into<String>,
    {
        Self::try_with_constraints(stream, boundary, Constraints::default())
    }

    /// Construct a new `Multipart` instance with the given [`Bytes`] stream and
    /// the boundary.
    ///
    /// This is the recommended constructor for untrusted multipart bodies.
    pub fn with_constraints<S, O, E, B>(stream: S, boundary: B, constraints: Constraints) -> Self
    where
        S: Stream<Item = Result<O, E>> + Send + 'r,
        O: Into<Bytes> + 'static,
        E: Into<Box<dyn std::error::Error + Send + Sync>> + 'r,
        B: Into<String>,
    {
        let boundary = boundary.into();
        let boundary_bytes = format!("{}{}", constants::BOUNDARY_EXT, boundary).into_bytes();
        let field_boundary_bytes =
            format!("{}{}{}", constants::CRLF, constants::BOUNDARY_EXT, boundary).into_bytes();
        let stream = stream
            .map_ok(Into::into)
            .map_err(|err| Error::StreamReadFailed(err.into()));

        Multipart {
            state: Arc::new(Mutex::new(MultipartState {
                buffer: StreamBuffer::new(
                    stream,
                    constraints.size_limit.whole_stream,
                    constraints.size_limit.boundary_padding,
                ),
                boundary_bytes,
                field_boundary_bytes,
                stage: StreamingStage::FindingFirstBoundary,
                next_field_idx: 0,
                curr_field_name: None,
                curr_field_size_limit: constraints.size_limit.per_field,
                curr_field_size_counter: 0,
                constraints,
            })),
        }
    }

    /// Construct a constrained `Multipart` instance after validating the
    /// boundary.
    ///
    /// This is the recommended constructor when the boundary does not come
    /// from [`crate::parse_boundary`].
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidBoundary`] if the boundary is empty, longer
    /// than 70 bytes, or contains characters that are not valid in a multipart
    /// boundary.
    pub fn try_with_constraints<S, O, E, B>(
        stream: S,
        boundary: B,
        constraints: Constraints,
    ) -> Result<Self>
    where
        S: Stream<Item = Result<O, E>> + Send + 'r,
        O: Into<Bytes> + 'static,
        E: Into<Box<dyn std::error::Error + Send + Sync>> + 'r,
        B: Into<String>,
    {
        let boundary = boundary.into();
        crate::validate_boundary(&boundary)?;
        Ok(Self::with_constraints(stream, boundary, constraints))
    }

    /// Construct a new `Multipart` instance with the given [`AsyncRead`] reader
    /// and the boundary.
    ///
    /// # Optional
    ///
    /// This requires the optional `tokio-io` feature to be enabled.
    ///
    /// This constructor keeps the default unbounded size limits for backward
    /// compatibility. For untrusted input, prefer
    /// [`Multipart::with_reader_and_constraints`].
    ///
    /// # Examples
    ///
    /// ```
    /// use multra::Multipart;
    ///
    /// # async fn run() {
    /// let data =
    ///     "--X-BOUNDARY\r\nContent-Disposition: form-data; name=\"my_text_field\"\r\n\r\nabcd\r\n--X-BOUNDARY--\r\n";
    /// let reader = data.as_bytes();
    /// let mut multipart = Multipart::with_reader(reader, "X-BOUNDARY");
    ///
    /// while let Some(mut field) = multipart.next_field().await.unwrap() {
    ///     while let Some(chunk) = field.chunk().await.unwrap() {
    ///         println!("Chunk: {:?}", chunk);
    ///     }
    /// }
    /// # }
    /// # tokio::runtime::Runtime::new().unwrap().block_on(run());
    /// ```
    #[cfg(feature = "tokio-io")]
    pub fn with_reader<R, B>(reader: R, boundary: B) -> Self
    where
        R: AsyncRead + Unpin + Send + 'r,
        B: Into<String>,
    {
        let stream = ReaderStream::new(reader);
        Multipart::new(stream, boundary)
    }

    /// Construct a new `Multipart` instance from an [`AsyncRead`] reader after
    /// validating the boundary.
    ///
    /// # Optional
    ///
    /// This requires the optional `tokio-io` feature to be enabled.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidBoundary`] if the boundary is invalid.
    #[cfg(feature = "tokio-io")]
    pub fn try_with_reader<R, B>(reader: R, boundary: B) -> Result<Self>
    where
        R: AsyncRead + Unpin + Send + 'r,
        B: Into<String>,
    {
        let stream = ReaderStream::new(reader);
        Self::try_new(stream, boundary)
    }

    /// Construct a new `Multipart` instance with the given [`AsyncRead`] reader
    /// and the boundary.
    ///
    /// # Optional
    ///
    /// This requires the optional `tokio-io` feature to be enabled.
    ///
    /// This is the recommended constructor for untrusted multipart bodies.
    ///
    /// # Examples
    ///
    /// ```
    /// use multra::{Constraints, Multipart, SizeLimit};
    ///
    /// # async fn run() {
    /// let data =
    ///     "--X-BOUNDARY\r\nContent-Disposition: form-data; name=\"my_text_field\"\r\n\r\nabcd\r\n--X-BOUNDARY--\r\n";
    /// let reader = data.as_bytes();
    /// let constraints = Constraints::new().size_limit(
    ///     SizeLimit::new().whole_stream(15 * 1024 * 1024).per_field(10 * 1024 * 1024),
    /// );
    /// let mut multipart =
    ///     Multipart::with_reader_and_constraints(reader, "X-BOUNDARY", constraints);
    ///
    /// while let Some(mut field) = multipart.next_field().await.unwrap() {
    ///     while let Some(chunk) = field.chunk().await.unwrap() {
    ///         println!("Chunk: {:?}", chunk);
    ///     }
    /// }
    /// # }
    /// # tokio::runtime::Runtime::new().unwrap().block_on(run());
    /// ```
    #[cfg(feature = "tokio-io")]
    pub fn with_reader_and_constraints<R, B>(
        reader: R,
        boundary: B,
        constraints: Constraints,
    ) -> Self
    where
        R: AsyncRead + Unpin + Send + 'r,
        B: Into<String>,
    {
        let stream = ReaderStream::new(reader);
        Multipart::with_constraints(stream, boundary, constraints)
    }

    /// Construct a constrained `Multipart` instance from an [`AsyncRead`]
    /// reader after validating the boundary.
    ///
    /// # Optional
    ///
    /// This requires the optional `tokio-io` feature to be enabled.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidBoundary`] if the boundary is invalid.
    #[cfg(feature = "tokio-io")]
    pub fn try_with_reader_and_constraints<R, B>(
        reader: R,
        boundary: B,
        constraints: Constraints,
    ) -> Result<Self>
    where
        R: AsyncRead + Unpin + Send + 'r,
        B: Into<String>,
    {
        let stream = ReaderStream::new(reader);
        Self::try_with_constraints(stream, boundary, constraints)
    }

    /// Yields the next [`Field`] if available.
    ///
    /// Any previous `Field` returned by this method must be dropped before
    /// calling this method or [`Multipart::next_field_with_idx()`] again. See
    /// [field-exclusivity](#field-exclusivity) for details.
    ///
    /// # Errors
    ///
    /// Returns an error if a previous field is still alive, the input stream
    /// cannot be read, the multipart data is malformed, or a configured
    /// constraint is violated.
    pub async fn next_field(&mut self) -> Result<Option<Field<'r>>> {
        future::poll_fn(|cx| self.poll_next_field(cx)).await
    }

    /// Yields the next [`Field`] if available.
    ///
    /// Any previous `Field` returned by this method must be dropped before
    /// calling this method or [`Multipart::next_field_with_idx()`] again. See
    /// [field-exclusivity](#field-exclusivity) for details.
    ///
    /// # Errors
    ///
    /// Returns an error if a previous field is still alive, the input stream
    /// cannot be read, the multipart data is malformed, or a configured
    /// constraint is violated.
    pub fn poll_next_field(&mut self, cx: &mut Context<'_>) -> Poll<Result<Option<Field<'r>>>> {
        let result = self.poll_next_field_from_buffer();
        if result.is_ready() {
            return result;
        }

        let Ok(mut lock) = self.state.try_lock() else {
            return Poll::Ready(Err(Error::LockFailure));
        };
        let buffered_len = lock.buffer.buf.len();
        let needs_wake = lock.buffer.poll_stream(cx)?;
        let has_new_input = lock.buffer.eof || lock.buffer.buf.len() != buffered_len;
        drop(lock);

        // Read at most one nonempty chunk per poll. New data schedules another
        // poll if it is still insufficient; an upstream Pending registers its
        // own waker. EOF must be parsed immediately because it does not wake us.
        let result = if has_new_input {
            self.poll_next_field_from_buffer()
        } else {
            Poll::Pending
        };
        if result.is_pending() && needs_wake {
            cx.waker().wake_by_ref();
        }
        result
    }

    #[allow(clippy::too_many_lines)] // The stages form one explicit parser state machine.
    fn poll_next_field_from_buffer(&self) -> Poll<Result<Option<Field<'r>>>> {
        // The public polling entry point requires `&mut Multipart`, and
        // `Field` is not `Clone`.
        // Here, we are guaranteeing that the returned `Field` will be the
        // _only_ field with access to the multipart parsing state. This ensure
        // that lock failure can never occur. This is effectively a dynamic
        // version of passing an `&mut` of `self` to the `Field`.
        if Arc::strong_count(&self.state) != 1 {
            return Poll::Ready(Err(Error::LockFailure));
        }

        let Ok(mut lock) = self.state.try_lock() else {
            return Poll::Ready(Err(Error::LockFailure));
        };

        let state = &mut *lock;
        if state.stage == StreamingStage::Eof {
            return Poll::Ready(Ok(None));
        }

        if state.stage == StreamingStage::FindingFirstBoundary {
            let preamble_limit = state.constraints.size_limit.preamble;
            if let Some(preamble_len) = state.buffer.find_first_boundary(&state.boundary_bytes) {
                if preamble_len as u64 > preamble_limit {
                    return Poll::Ready(Err(Error::PreambleSizeExceeded {
                        limit: preamble_limit,
                    }));
                }
                state.buffer.advance(preamble_len);
                state.stage = StreamingStage::ReadingBoundary;
            } else {
                // The independent preamble limit prevents unbounded buffer
                // growth when the whole-stream limit is left unbounded. A
                // trailing partial boundary is not preamble until more input
                // proves that it is not the opening delimiter.
                let partial_boundary_len = state
                    .buffer
                    .partial_pattern_suffix_len(&state.boundary_bytes);
                let preamble_len = state.buffer.buf.len().saturating_sub(partial_boundary_len);
                if preamble_len as u64 > preamble_limit {
                    return Poll::Ready(Err(Error::PreambleSizeExceeded {
                        limit: preamble_limit,
                    }));
                }
                if state.buffer.eof {
                    return Poll::Ready(Err(Error::IncompleteStream));
                }
            }
        }

        // The previous field did not finish reading its data.
        if state.stage == StreamingStage::ReadingFieldData {
            match state.buffer.read_field_data(
                &state.field_boundary_bytes,
                state.curr_field_name.as_deref(),
            )? {
                Some((done, bytes)) => {
                    // Saturating add prevents an attacker from overflowing
                    // the counter back to zero to bypass the size check.
                    state.curr_field_size_counter = state
                        .curr_field_size_counter
                        .saturating_add(bytes.len() as u64);

                    if state.curr_field_size_counter > state.curr_field_size_limit {
                        return Poll::Ready(Err(Error::FieldSizeExceeded {
                            limit: state.curr_field_size_limit,
                            field_name: state.curr_field_name.clone(),
                        }));
                    }

                    if done {
                        state.stage = StreamingStage::ReadingBoundary;
                    } else {
                        return Poll::Pending;
                    }
                }
                None => {
                    return Poll::Pending;
                }
            }
        }

        if state.stage == StreamingStage::ReadingBoundary {
            let Some(boundary_bytes) = state.buffer.read_exact(state.boundary_bytes.len()) else {
                return if state.buffer.eof {
                    Poll::Ready(Err(Error::IncompleteStream))
                } else {
                    Poll::Pending
                };
            };

            if &boundary_bytes[..] == state.boundary_bytes.as_slice() {
                state.stage = StreamingStage::DeterminingBoundaryType;
            } else {
                return Poll::Ready(Err(Error::IncompleteStream));
            }
        }

        if state.stage == StreamingStage::DeterminingBoundaryType {
            let ext_len = constants::BOUNDARY_EXT.len();
            let Some(next_bytes) = state.buffer.peek_exact(ext_len) else {
                return if state.buffer.eof {
                    Poll::Ready(Err(Error::IncompleteStream))
                } else {
                    Poll::Pending
                };
            };

            if next_bytes == constants::BOUNDARY_EXT.as_bytes() {
                state.buffer.advance(ext_len);
                state.stage = StreamingStage::ReadingClosingTransportPadding;
            } else {
                state.stage = StreamingStage::ReadingTransportPadding;
            }
        }

        if matches!(
            state.stage,
            StreamingStage::ReadingTransportPadding
                | StreamingStage::ReadingClosingTransportPadding
        ) {
            let closing = state.stage == StreamingStage::ReadingClosingTransportPadding;
            if !state.buffer.advance_past_transport_padding()? {
                if closing && state.buffer.eof {
                    state.stage = StreamingStage::Eof;
                    return Poll::Ready(Ok(None));
                }
                return if state.buffer.eof {
                    Poll::Ready(Err(Error::IncompleteStream))
                } else {
                    Poll::Pending
                };
            }

            let crlf_len = constants::CRLF.len();
            let Some(crlf_bytes) = state.buffer.read_exact(crlf_len) else {
                return if state.buffer.eof {
                    Poll::Ready(Err(Error::IncompleteStream))
                } else {
                    Poll::Pending
                };
            };

            if &crlf_bytes[..] == constants::CRLF.as_bytes() {
                if closing {
                    state.stage = if state.constraints.size_limit.whole_stream == u64::MAX {
                        StreamingStage::Eof
                    } else {
                        StreamingStage::ReadingEpilogue
                    };
                    if state.stage == StreamingStage::Eof {
                        return Poll::Ready(Ok(None));
                    }
                } else {
                    state.stage = StreamingStage::ReadingFieldHeaders;
                }
            } else {
                return Poll::Ready(Err(Error::IncompleteStream));
            }
        }

        if state.stage == StreamingStage::ReadingFieldHeaders {
            let field_count_limit = state.constraints.max_fields.unwrap_or(usize::MAX);
            if state.next_field_idx >= field_count_limit {
                return Poll::Ready(Err(Error::FieldCountExceeded {
                    limit: field_count_limit,
                }));
            }
            let headers_limit = state.constraints.size_limit.headers;
            let Some(header_bytes) = state.buffer.read_headers() else {
                if state.buffer.buf.len() as u64 > headers_limit {
                    return Poll::Ready(Err(Error::HeadersSizeExceeded {
                        limit: headers_limit,
                    }));
                }

                return if state.buffer.eof {
                    Poll::Ready(Err(Error::IncompleteStream))
                } else {
                    Poll::Pending
                };
            };

            if header_bytes.len() as u64 > headers_limit {
                return Poll::Ready(Err(Error::HeadersSizeExceeded {
                    limit: headers_limit,
                }));
            }

            let mut headers = [httparse::EMPTY_HEADER; constants::MAX_HEADERS];

            let headers = match httparse::parse_headers(&header_bytes, &mut headers)
                .map_err(Error::ReadHeaderFailed)?
            {
                httparse::Status::Complete((consumed, raw_headers)) => {
                    // The buffer and header parser must agree on where the
                    // header block ends. Otherwise a bare-LF empty line can
                    // make bytes from the field body disappear as headers.
                    if consumed != header_bytes.len() {
                        return Poll::Ready(Err(Error::ReadHeaderFailed(httparse::Error::NewLine)));
                    }
                    match helpers::convert_raw_headers_to_header_map(raw_headers) {
                        Ok(headers) => headers,
                        Err(err) => {
                            return Poll::Ready(Err(err));
                        }
                    }
                }
                httparse::Status::Partial => {
                    return Poll::Ready(Err(Error::IncompleteHeaders));
                }
            };

            state.stage = StreamingStage::ReadingFieldData;

            let field_idx = state.next_field_idx;
            // The count check before parsing headers also guarantees that the
            // zero-based field index never wraps, even with no explicit limit.
            state.next_field_idx += 1;

            let content_disposition = ContentDisposition::parse(&headers);
            let field_size_limit = state
                .constraints
                .size_limit
                .extract_size_limit_for(content_disposition.field_name.as_deref());

            state
                .curr_field_name
                .clone_from(&content_disposition.field_name);
            state.curr_field_size_limit = field_size_limit;
            state.curr_field_size_counter = 0;

            let field_name = content_disposition.field_name.as_deref();
            if !state.constraints.is_it_allowed(field_name) {
                return Poll::Ready(Err(Error::UnknownField {
                    field_name: field_name.map(str::to_owned),
                }));
            }

            drop(lock); // The lock will be dropped anyway, but let's be explicit.
            let field = Field::new(self.state.clone(), headers, field_idx, content_disposition);
            return Poll::Ready(Ok(Some(field)));
        }

        if state.stage == StreamingStage::ReadingEpilogue {
            // These bytes were counted when pulled from the source. Discard
            // them before requesting another chunk so epilogue memory stays
            // bounded by one upstream chunk rather than its total length.
            state.buffer.buf.clear();
            if state.buffer.eof {
                state.stage = StreamingStage::Eof;
                return Poll::Ready(Ok(None));
            }
        }

        Poll::Pending
    }

    /// Yields the next [`Field`] with its positioning index as
    /// <code>([usize], [Field])</code>.
    ///
    /// Any previous `Field` returned by this method must be dropped before
    /// calling this method or [`Multipart::next_field()`] again. See
    /// [field-exclusivity](#field-exclusivity) for details.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::convert::Infallible;
    ///
    /// use bytes::Bytes;
    /// use futures_util::stream::once;
    /// use multra::Multipart;
    ///
    /// # async fn run() {
    /// let data = "--X-BOUNDARY\r\nContent-Disposition: form-data; \
    ///     name=\"my_text_field\"\r\n\r\nabcd\r\n--X-BOUNDARY--\r\n";
    ///
    /// let stream = once(async move { Result::<Bytes, Infallible>::Ok(Bytes::from(data)) });
    /// let mut multipart = Multipart::new(stream, "X-BOUNDARY");
    ///
    /// while let Some((idx, field)) = multipart.next_field_with_idx().await.unwrap() {
    ///     println!("Index: {:?}, Content: {:?}", idx, field.text().await)
    /// }
    /// # }
    /// # tokio::runtime::Runtime::new().unwrap().block_on(run());
    /// ```
    ///
    /// # Errors
    ///
    /// Returns the same errors as [`Self::next_field`].
    pub async fn next_field_with_idx(&mut self) -> Result<Option<(usize, Field<'r>)>> {
        self.next_field()
            .await
            .map(|f| f.map(|field| (field.index(), field)))
    }
}

#[cfg(test)]
mod tests {
    use bytes::Bytes;
    use futures_util::stream;

    use super::Multipart;
    use crate::{Constraints, Error};

    #[tokio::test]
    async fn field_indices_cannot_overflow() {
        for constraints in [
            Constraints::new(),
            Constraints::new().max_fields(usize::MAX),
        ] {
            let source = stream::iter([Ok::<_, std::convert::Infallible>(Bytes::from_static(
                b"--B\r\nContent-Disposition: form-data; name=\"a\"\r\n\r\nx\r\n--B--\r\n",
            ))]);
            let mut multipart = Multipart::with_constraints(source, "B", constraints);
            multipart.state.lock().unwrap().next_field_idx = usize::MAX;
            assert!(matches!(
                multipart.next_field().await,
                Err(Error::FieldCountExceeded { limit: usize::MAX })
            ));
        }
    }
}