http-multipart 0.1.2

multipart for http crate type
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
use core::{
    pin::Pin,
    task::{ready, Context, Poll},
};

use std::{borrow::Cow, io, vec};

use bytes::{Bytes, BytesMut};
use futures_core::stream::Stream;
use http::header::HeaderValue;

use super::MultipartError;

type BoxedStream = Pin<Box<dyn Stream<Item = io::Result<Bytes>> + Send>>;

/// A builder for a `multipart/form-data` request body.
///
/// Add fields via [`Part`], then obtain the `Content-Type` header value with
/// [`Form::content_type`] and the body stream with [`Form::into_stream`].
///
/// # Examples
/// ```rust
/// use http::Request;
/// use http_multipart::{Form, Part};
///
/// // construct a form from parts
/// let parts = vec![
///     Part::text("username", "alice"),
///     Part::binary("data", &b"hello"[..]).file_name("hello.bin"),
/// ];
/// let form = Form::new(parts);
///
/// // build a request with the form
/// let req = Request::builder()
///     .method("POST") // multipart is usually used with POST method
///     .header("Content-Type", form.content_type()) // content type header must be set to form's content type
///     .body(form) // form implements Stream, so it can be used directly as the body
///     .unwrap();
/// ```
pub struct Form {
    boundary: Box<[u8]>,
    parts: vec::IntoIter<Part>,
    state: StreamState,
    buf: BytesMut,
}

/// A single field for [`Form`]
pub struct Part {
    name: String,
    filename: Option<String>,
    content_type: Cow<'static, str>,
    body: BoxedStream,
}

impl Form {
    /// Create a new form with an automatically generated boundary.
    pub fn new(parts: Vec<Part>) -> Self {
        Self::with_boundary(generate_boundary(), parts).unwrap()
    }

    /// Create a form with a caller-supplied boundary.
    ///
    /// Returns [`MultipartError::Boundary`] if `boundary` is empty or contains
    /// `\r` / `\n` (which would break the wire format).
    pub fn with_boundary(boundary: impl AsRef<[u8]>, parts: Vec<Part>) -> Result<Self, MultipartError> {
        let b = boundary.as_ref();
        if b.is_empty() || b.iter().any(|&c| c == b'\r' || c == b'\n') {
            return Err(MultipartError::Boundary);
        }
        let mut prefixed = Vec::with_capacity(2 + b.len());
        prefixed.extend_from_slice(b"--");
        prefixed.extend_from_slice(b);
        Ok(Self {
            boundary: prefixed.into_boxed_slice(),
            parts: parts.into_iter(),
            state: StreamState::NextPart,
            buf: BytesMut::new(),
        })
    }

    /// The raw boundary bytes used by this form.
    pub fn boundary(&self) -> &[u8] {
        &self.boundary[2..]
    }

    /// The `Content-Type` header value that must be set on the outgoing request.
    ///
    /// Example: `multipart/form-data; boundary=0000000000001a2b`
    pub fn content_type(&self) -> HeaderValue {
        let boundary = self.boundary();
        let mut v = BytesMut::with_capacity(30 + boundary.len());
        v.extend_from_slice(b"multipart/form-data; boundary=");
        v.extend_from_slice(boundary);
        // Boundary is validated to be ASCII on construction, so this never panics.
        HeaderValue::from_maybe_shared(v.freeze()).expect("boundary is valid ASCII")
    }
}

impl Part {
    /// plain-text field. field `Content-Type` is `text/plain; charset=utf-8`.
    #[inline]
    pub fn text(name: impl Into<String>, value: impl Into<String>) -> Self {
        Self::binary(name, value.into()).content_type("text/plain; charset=utf-8")
    }

    /// fixed binary field. field `Content-Type` is `application/octet-stream`.
    #[inline]
    pub fn binary(name: impl Into<String>, body: impl Into<Bytes>) -> Self {
        Self::stream(name, Once(Some(body.into())))
    }

    /// streaming binary field. field `Content-Type` is `application/octet-stream`.
    ///
    /// [`Stream`] trait is utilized for generic async streaming interface
    pub fn stream<S>(name: impl Into<String>, stream: S) -> Self
    where
        S: Stream<Item = io::Result<Bytes>> + Send + 'static,
    {
        Self {
            name: name.into(),
            filename: None,
            content_type: Cow::Borrowed("application/octet-stream"),
            body: Box::pin(stream),
        }
    }

    /// Attach a filename (sets the `filename` parameter in `Content-Disposition`).
    pub fn file_name(mut self, filename: impl Into<String>) -> Self {
        self.filename = Some(filename.into());
        self
    }

    /// Override the `Content-Type` for this part.
    pub fn content_type(mut self, ct: impl Into<Cow<'static, str>>) -> Self {
        self.content_type = ct.into();
        self
    }

    fn format_headers_into(&self, buf: &mut BytesMut) {
        let (low, up) = self.body.size_hint();
        let exact = Some(low) == up;

        // Fixed bytes:
        //   "Content-Disposition: form-data; name=\""  38
        //   closing quote + CRLF                        3
        //   "Content-Type: " + CRLF                    16
        //   final blank CRLF                             2
        //                                         total 59
        let mut len = 59 + self.name.len() + self.content_type.len();
        if let Some(fname) = &self.filename {
            len += 13 + fname.len(); // "; filename=\"" (12) + closing quote (1)
        }
        if exact {
            len += 38; // "Content-Length: " (16) + up to 20 digits + CRLF (2)
        }
        buf.reserve(len);

        buf.extend_from_slice(b"Content-Disposition: form-data; name=\"");
        buf.extend_from_slice(self.name.as_bytes());
        buf.extend_from_slice(b"\"");

        if let Some(fname) = &self.filename {
            buf.extend_from_slice(b"; filename=\"");
            buf.extend_from_slice(fname.as_bytes());
            buf.extend_from_slice(b"\"");
        }

        buf.extend_from_slice(b"\r\n");

        buf.extend_from_slice(b"Content-Type: ");
        buf.extend_from_slice(self.content_type.as_bytes());
        buf.extend_from_slice(b"\r\n");

        if exact {
            buf.extend_from_slice(b"Content-Length: ");
            buf.extend_from_slice(format!("{low}").as_bytes());
            buf.extend_from_slice(b"\r\n");
        }

        buf.extend_from_slice(b"\r\n");
    }
}

struct Once(Option<Bytes>);

impl Stream for Once {
    type Item = io::Result<Bytes>;

    #[inline]
    fn poll_next(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        Poll::Ready(self.get_mut().0.take().map(Ok))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let size = self.0.as_ref().map(|b| b.len()).unwrap_or(0);
        (size, Some(size))
    }
}

enum StreamState {
    NextPart,
    Body(BoxedStream),
    Done,
}

impl Stream for Form {
    type Item = io::Result<Bytes>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let this = self.get_mut();
        match &mut this.state {
            StreamState::Done => Poll::Ready(None),
            StreamState::NextPart => {
                this.buf.reserve(this.boundary.len() + 4);
                this.buf.extend_from_slice(&this.boundary);

                this.state = match this.parts.next() {
                    None => {
                        this.buf.extend_from_slice(b"--\r\n");
                        StreamState::Done
                    }
                    Some(part) => {
                        this.buf.extend_from_slice(b"\r\n");
                        part.format_headers_into(&mut this.buf);
                        StreamState::Body(part.body)
                    }
                };

                Poll::Ready(Some(Ok(this.buf.split().freeze())))
            }
            StreamState::Body(body) => {
                let chunk = ready!(body.as_mut().poll_next(cx)).unwrap_or_else(|| {
                    this.state = StreamState::NextPart;
                    // the end of delimiter chunk is only 2 bytes.
                    // downstream should try to buffer it to reduce fragmentation
                    Ok(Bytes::from_static(b"\r\n"))
                });

                Poll::Ready(Some(chunk))
            }
        }
    }
}

// Generate a boundary that is unique within the current process.
//
// The boundary is not cryptographically random.  For environments where the
// boundary must not appear in the body (security-sensitive uploads), supply
// your own random boundary via [`Form::with_boundary`].
fn generate_boundary() -> Box<[u8]> {
    use std::sync::atomic::{AtomicU64, Ordering};
    static COUNTER: AtomicU64 = AtomicU64::new(0);
    let n = COUNTER.fetch_add(1, Ordering::Relaxed);
    // XOR with a stack address for modest per-process entropy.
    let salt = &n as *const u64 as u64;
    let val = n ^ salt.wrapping_mul(0x9e3779b97f4a7c15);
    format!("{val:016x}").into_bytes().into_boxed_slice()
}

#[cfg(test)]
mod test {
    use std::{convert::Infallible, pin::pin};

    use bytes::Bytes;
    use futures_util::{FutureExt, StreamExt};
    use http::{header::CONTENT_TYPE, Method, Request};

    use super::*;
    use crate::multipart;

    /// Drain a `Form` synchronously. Works because `Once` bodies are always `Poll::Ready`.
    fn collect(mut form: Form) -> Vec<u8> {
        let mut out = Vec::new();
        loop {
            match form.next().now_or_never() {
                Some(Some(Ok(bytes))) => out.extend_from_slice(&bytes),
                Some(None) => break,
                Some(Some(Err(e))) => panic!("stream error: {e}"),
                None => panic!("stream returned Poll::Pending unexpectedly"),
            }
        }
        out
    }

    #[test]
    fn empty_form() {
        let form = Form::with_boundary("abc", vec![]).unwrap();
        let body = collect(form);
        assert_eq!(body, b"--abc--\r\n");
    }

    #[test]
    fn single_text_field() {
        // Part::text uses Once whose size_hint is exact, so Content-Length is emitted.
        let form = Form::with_boundary("abc", vec![Part::text("field", "value")]).unwrap();
        let body = collect(form);
        assert_eq!(
            body,
            b"--abc\r\n\
              Content-Disposition: form-data; name=\"field\"\r\n\
              Content-Type: text/plain; charset=utf-8\r\n\
              Content-Length: 5\r\n\
              \r\n\
              value\r\n\
              --abc--\r\n"
        );
    }

    #[test]
    fn file_part() {
        let part = Part::binary("upload", Bytes::from_static(b"data"))
            .file_name("hello.bin")
            .content_type("application/octet-stream");
        let form = Form::with_boundary("abc", vec![part]).unwrap();
        let body = collect(form);
        assert_eq!(
            body,
            b"--abc\r\n\
              Content-Disposition: form-data; name=\"upload\"; filename=\"hello.bin\"\r\n\
              Content-Type: application/octet-stream\r\n\
              Content-Length: 4\r\n\
              \r\n\
              data\r\n\
              --abc--\r\n"
        );
    }

    #[test]
    fn roundtrip() {
        // Encode with Form, then parse with Multipart and verify fields.
        let parts = vec![
            Part::text("name", "alice"),
            Part::binary("file", Bytes::from_static(b"hello world"))
                .file_name("hi.txt")
                .content_type("text/plain"),
        ];
        let form = Form::with_boundary("testbound", parts).unwrap();

        let content_type = form.content_type();
        let body: Bytes = collect(form).into();

        let mut req = Request::new(());
        *req.method_mut() = Method::POST;
        req.headers_mut().insert(CONTENT_TYPE, content_type);

        let stream = futures_util::stream::once(async { Ok::<_, Infallible>(body) });
        let mut mp = pin!(multipart(&req, stream).unwrap());

        // Field 1: "name" = "alice"
        {
            let mut f1 = mp.try_next().now_or_never().unwrap().unwrap().unwrap();
            assert_eq!(f1.name(), Some("name"));
            assert_eq!(
                f1.try_next().now_or_never().unwrap().unwrap().unwrap().as_ref(),
                b"alice"
            );
            assert!(f1.try_next().now_or_never().unwrap().unwrap().is_none());
        }

        // Field 2: "file"
        {
            let mut f2 = mp.try_next().now_or_never().unwrap().unwrap().unwrap();
            assert_eq!(f2.name(), Some("file"));
            assert_eq!(f2.file_name(), Some("hi.txt"));
            assert_eq!(f2.headers().get(CONTENT_TYPE).unwrap().as_bytes(), b"text/plain");
            assert_eq!(
                f2.try_next().now_or_never().unwrap().unwrap().unwrap().as_ref(),
                b"hello world"
            );
            assert!(f2.try_next().now_or_never().unwrap().unwrap().is_none());
        }

        // No more fields.
        assert!(mp.try_next().now_or_never().unwrap().unwrap().is_none());
    }

    #[test]
    fn multi_part_delimiters() {
        let form = Form::with_boundary(
            "sep",
            vec![Part::text("a", "1"), Part::text("b", "2"), Part::text("c", "3")],
        )
        .unwrap();
        let body = collect(form);
        // Each single-char value → Content-Length: 1.
        let expected = b"--sep\r\n\
            Content-Disposition: form-data; name=\"a\"\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: 1\r\n\r\n1\r\n\
            --sep\r\n\
            Content-Disposition: form-data; name=\"b\"\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: 1\r\n\r\n2\r\n\
            --sep\r\n\
            Content-Disposition: form-data; name=\"c\"\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: 1\r\n\r\n3\r\n\
            --sep--\r\n";
        assert_eq!(body, expected);
    }

    #[test]
    fn with_boundary_rejects_empty() {
        assert!(matches!(Form::with_boundary("", vec![]), Err(MultipartError::Boundary)));
    }

    #[test]
    fn with_boundary_rejects_newline() {
        assert!(matches!(
            Form::with_boundary("ab\ncd", vec![]),
            Err(MultipartError::Boundary)
        ));
        assert!(matches!(
            Form::with_boundary("ab\rcd", vec![]),
            Err(MultipartError::Boundary)
        ));
    }

    #[test]
    fn content_type_header() {
        let form = Form::with_boundary("myboundary", vec![]).unwrap();
        assert_eq!(
            form.content_type().as_bytes(),
            b"multipart/form-data; boundary=myboundary"
        );
    }
}