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
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll};

use bytes::{Bytes, BytesMut};
use encoding_rs::{Encoding, UTF_8};
use futures_util::stream::{Stream, TryStreamExt};
use http::header::HeaderMap;
#[cfg(feature = "json")]
use serde::de::DeserializeOwned;

use crate::content_disposition::ContentDisposition;
use crate::multipart::{MultipartState, StreamingStage};
use crate::{Error, helpers};

/// A single field in a multipart stream.
///
/// Its content can be accessed via the [`Stream`] API or the methods defined in
/// this type.
///
/// Stop reading and discard the multipart parser after a stream, parsing, or
/// size-limit error. Further reads after such an error have no recovery
/// guarantee.
///
/// # Lifetime
///
/// The lifetime of the stream `'r` corresponds to the lifetime of the
/// underlying `Stream`. If the underlying stream holds no references directly
/// or transitively, then the lifetime can be `'static`.
///
/// # 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() {
///     let content = field.text().await.unwrap();
///     assert_eq!(content, "abcd");
/// }
/// # }
/// # tokio::runtime::Runtime::new().unwrap().block_on(run());
/// ```
///
/// [`Multipart`]: crate::Multipart
#[derive(Debug)]
pub struct Field<'r> {
    state: Arc<Mutex<MultipartState<'r>>>,
    done: bool,
    headers: HeaderMap,
    content_disposition: ContentDisposition,
    content_type: Option<mime::Mime>,
    content_type_charset: Option<String>,
    idx: usize,
}

impl<'r> Field<'r> {
    pub(crate) fn new(
        state: Arc<Mutex<MultipartState<'r>>>,
        headers: HeaderMap,
        idx: usize,
        content_disposition: ContentDisposition,
    ) -> Self {
        let (content_type, content_type_charset) =
            helpers::parse_content_type(&headers).map_or((None, None), |parsed| {
                (
                    parsed.to_mime(),
                    parsed.get_param("charset").map(str::to_owned),
                )
            });
        Field {
            state,
            headers,
            content_disposition,
            content_type,
            content_type_charset,
            idx,
            done: false,
        }
    }

    /// The field name found in the [`Content-Disposition`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition) header.
    ///
    /// Quoted values decode MIME quoted-pairs before matching field constraints.
    /// If the header is repeated, the last value is used.
    #[must_use]
    pub fn name(&self) -> Option<&str> {
        self.content_disposition.field_name.as_deref()
    }

    /// The file name found in the [`Content-Disposition`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition) header.
    ///
    /// In quoted values, a backslash escapes the following character. Encode
    /// literal backslashes as `\\` in the quoted header parameter.
    ///
    /// If the header is repeated, the last value is used.
    ///
    /// This is untrusted client input. It may contain directory components,
    /// absolute paths, or control characters, including characters produced by
    /// percent decoding. Do not use it directly as a filesystem path. Generate
    /// a storage name or validate it against your application's filename policy.
    #[must_use]
    pub fn file_name(&self) -> Option<&str> {
        self.content_disposition.file_name.as_deref()
    }

    /// Get the content type of the field.
    ///
    /// If the header is repeated, the last value is used, even if it is invalid.
    ///
    /// Returns `None` if the header is invalid or its parameters cannot be
    /// represented faithfully by [`mime::Mime`], such as quoted values with
    /// literal quotes, backslashes, or non-UTF-8 bytes. The original header
    /// remains available through [`Self::headers`], and text decoding still
    /// honors its charset.
    #[must_use]
    pub const fn content_type(&self) -> Option<&mime::Mime> {
        self.content_type.as_ref()
    }

    /// Get a map of headers as [`HeaderMap`].
    ///
    /// Repeated values are preserved in their original order and can be read
    /// with [`HeaderMap::get_all`]. The field metadata accessors use the last
    /// `Content-Disposition` and `Content-Type` values for compatibility.
    #[must_use]
    pub const fn headers(&self) -> &HeaderMap {
        &self.headers
    }

    /// Get the full data of the field as [`Bytes`].
    ///
    /// A single data chunk is returned without copying and may share its
    /// allocation with other buffered fields.
    ///
    /// # 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() {
    ///     let bytes = field.bytes().await.unwrap();
    ///     assert_eq!(bytes.len(), 4);
    /// }
    /// # }
    /// # tokio::runtime::Runtime::new().unwrap().block_on(run());
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if the input stream cannot be read, the multipart data
    /// is malformed, or a configured size limit is exceeded.
    pub async fn bytes(self) -> crate::Result<Bytes> {
        let mut first_chunk: Option<Bytes> = None;
        let mut buf = BytesMut::new();
        let mut chunks_since_yield = 0;

        let mut this = self;
        while let Some(bytes) = this.chunk().await? {
            chunks_since_yield += 1;
            if chunks_since_yield == 32 {
                // A ready source need not provide executor cooperation itself.
                // Bound the work of this aggregation future independently of
                // the per-poll budget of the individual Field stream reads.
                let mut yielded = false;
                std::future::poll_fn(|cx| {
                    if yielded {
                        Poll::Ready(())
                    } else {
                        yielded = true;
                        cx.waker().wake_by_ref();
                        Poll::Pending
                    }
                })
                .await;
                chunks_since_yield = 0;
            }
            if bytes.is_empty() {
                continue;
            }
            if let Some(first) = first_chunk.take() {
                buf.reserve(first.len().saturating_add(bytes.len()));
                buf.extend_from_slice(&first);
            } else if buf.is_empty() {
                first_chunk = Some(bytes);
                continue;
            }
            buf.extend_from_slice(&bytes);
        }

        Ok(first_chunk.unwrap_or_else(|| buf.freeze()))
    }

    /// Stream a chunk of the field data.
    ///
    /// When the field data has been exhausted, this will return [`None`].
    ///
    /// # 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(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());
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if the input stream cannot be read, the multipart data
    /// is malformed, or a configured size limit is exceeded.
    pub async fn chunk(&mut self) -> crate::Result<Option<Bytes>> {
        self.try_next().await
    }

    /// Try to deserialize the field data as JSON.
    ///
    /// # Optional
    ///
    /// This requires the optional `json` feature to be enabled.
    ///
    /// # Examples
    ///
    /// ```
    /// use multra::Multipart;
    /// use bytes::Bytes;
    /// use std::convert::Infallible;
    /// use futures_util::stream::once;
    /// use serde::Deserialize;
    ///
    /// // This `derive` requires the `serde` dependency.
    /// #[derive(Deserialize)]
    /// struct User {
    ///     name: String
    /// }
    ///
    /// # async fn run() {
    /// let data = "--X-BOUNDARY\r\nContent-Disposition: form-data; name=\"my_text_field\"\r\n\r\n{ \"name\": \"Alice\" }\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() {
    ///     let user = field.json::<User>().await.unwrap();
    ///     println!("User Name: {}", user.name);
    /// }
    /// # }
    /// # tokio::runtime::Runtime::new().unwrap().block_on(run());
    /// ```
    ///
    /// # Errors
    ///
    /// This method fails if the field data is not in JSON format
    /// or it cannot be properly deserialized to target type `T`. For more
    /// details please see [`serde_json::from_slice`].
    #[cfg(feature = "json")]
    pub async fn json<T: DeserializeOwned>(self) -> crate::Result<T> {
        serde_json::from_slice(&self.bytes().await?).map_err(Error::DecodeJson)
    }

    /// Get the full field data as text.
    ///
    /// This method decodes the field data with `BOM sniffing` and with
    /// malformed sequences replaced with the `REPLACEMENT CHARACTER`.
    /// Encoding is determined from the `charset` parameter of `Content-Type`
    /// header, and defaults to `utf-8` if not presented.
    ///
    /// # 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() {
    ///     let content = field.text().await.unwrap();
    ///     assert_eq!(content, "abcd");
    /// }
    /// # }
    /// # tokio::runtime::Runtime::new().unwrap().block_on(run());
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if the field cannot be read completely.
    pub async fn text(self) -> crate::Result<String> {
        self.text_with_charset("utf-8").await
    }

    /// Get the full field data as text given a specific encoding.
    ///
    /// This method decodes the field data with `BOM sniffing` and with
    /// malformed sequences replaced with the `REPLACEMENT CHARACTER`.
    /// You can provide a default encoding for decoding the raw message, while
    /// the `charset` parameter of `Content-Type` header is still prioritized.
    /// For more information about the possible encoding name, please go to
    /// [`encoding_rs`] docs.
    ///
    /// # 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() {
    ///     let content = field.text_with_charset("utf-8").await.unwrap();
    ///     assert_eq!(content, "abcd");
    /// }
    /// # }
    /// # tokio::runtime::Runtime::new().unwrap().block_on(run());
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if the field cannot be read completely.
    pub async fn text_with_charset(self, default_encoding: &str) -> crate::Result<String> {
        let encoding_name = self
            .content_type_charset
            .as_deref()
            .unwrap_or(default_encoding);

        let encoding = Encoding::for_label(encoding_name.as_bytes()).unwrap_or(UTF_8);
        let bytes = self.bytes().await?;
        Ok(encoding.decode(&bytes).0.into_owned())
    }

    /// Get the index of this field in order they appeared in the stream.
    ///
    /// # 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() {
    ///     let idx = field.index();
    ///     println!("Field index: {}", idx);
    /// }
    /// # }
    /// # tokio::runtime::Runtime::new().unwrap().block_on(run());
    /// ```
    #[must_use]
    pub const fn index(&self) -> usize {
        self.idx
    }
}

impl Stream for Field<'_> {
    type Item = Result<Bytes, Error>;

    #[allow(clippy::significant_drop_tightening)] // Parsing needs one guard for the full poll.
    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        if self.done {
            return Poll::Ready(None);
        }

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

        let state = &mut *lock;
        let mut read_stream = false;
        let mut needs_wake = false;

        loop {
            match state.buffer.read_field_data(
                &state.field_boundary_bytes,
                state.curr_field_name.as_deref(),
            ) {
                Ok(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(Some(Err(Error::FieldSizeExceeded {
                            limit: state.curr_field_size_limit,
                            field_name: state.curr_field_name.clone(),
                        })));
                    }

                    if done {
                        state.stage = StreamingStage::ReadingBoundary;
                        self.done = true;
                    }

                    return Poll::Ready(Some(Ok(bytes)));
                }
                Ok(None) if !read_stream => {
                    read_stream = true;
                    match state.buffer.poll_stream(cx) {
                        Ok(wake) => needs_wake = wake,
                        Err(err) => return Poll::Ready(Some(Err(err))),
                    }
                }
                Ok(None) => {
                    if needs_wake {
                        cx.waker().wake_by_ref();
                    }
                    return Poll::Pending;
                }
                Err(err) => return Poll::Ready(Some(Err(err))),
            }
        }
    }
}