Skip to main content

turnloop_http/
multipart.rs

1//! In-memory `multipart/form-data` bodies (RFC 7578 over RFC 2046 framing).
2//!
3//! The boundary is derived from 16 bytes of entropy the host supplies (this crate
4//! reads no randomness source) and is then checked against every part: a
5//! boundary that occurs anywhere in a part's name, filename, content type or
6//! bytes is replaced by the next candidate, so no payload - base64 text with a
7//! boundary-shaped run included - can end a part early.
8//!
9//! ```
10//! use turnloop_http::multipart::{Form, Part};
11//! let form = Form::new()
12//!     .text("version", "1.2.0")
13//!     .part(Part::file("tarball", "pkg.tgz", b"\x1f\x8b...".to_vec()).content_type("application/gzip"));
14//! let encoded = form.encode([7; 16]).unwrap();
15//! assert!(encoded.content_type().starts_with("multipart/form-data; boundary="));
16//! ```
17use crate::{Error, Result, client::Request, http1::Header};
18
19/// One form field: a text value or a named file.
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct Part {
22    name: String,
23    filename: Option<String>,
24    content_type: Option<String>,
25    body: Vec<u8>,
26}
27impl Part {
28    /// A text field. No `Content-Type` is written unless one is set.
29    pub fn text(name: impl Into<String>, value: impl Into<String>) -> Self {
30        Self {
31            name: name.into(),
32            filename: None,
33            content_type: None,
34            body: value.into().into_bytes(),
35        }
36    }
37    /// A file field. Its `Content-Type` is `application/octet-stream` unless set.
38    pub fn file(name: impl Into<String>, filename: impl Into<String>, bytes: Vec<u8>) -> Self {
39        Self {
40            name: name.into(),
41            filename: Some(filename.into()),
42            content_type: None,
43            body: bytes,
44        }
45    }
46    pub fn content_type(mut self, content_type: impl Into<String>) -> Self {
47        self.content_type = Some(content_type.into());
48        self
49    }
50    fn media_type(&self) -> Option<&str> {
51        match (&self.content_type, &self.filename) {
52            (Some(content_type), _) => Some(content_type),
53            (None, Some(_)) => Some("application/octet-stream"),
54            (None, None) => None,
55        }
56    }
57}
58
59/// An ordered list of parts, encoded in one piece by [`Form::encode`].
60#[derive(Debug, Clone, Default, PartialEq, Eq)]
61pub struct Form {
62    parts: Vec<Part>,
63}
64impl Form {
65    pub fn new() -> Self {
66        Self::default()
67    }
68    pub fn text(self, name: impl Into<String>, value: impl Into<String>) -> Self {
69        self.part(Part::text(name, value))
70    }
71    pub fn file(
72        self,
73        name: impl Into<String>,
74        filename: impl Into<String>,
75        bytes: Vec<u8>,
76    ) -> Self {
77        self.part(Part::file(name, filename, bytes))
78    }
79    pub fn part(mut self, part: Part) -> Self {
80        self.parts.push(part);
81        self
82    }
83    pub fn parts(&self) -> &[Part] {
84        &self.parts
85    }
86    /// Serialize the form. `entropy` should come from the host's secure random
87    /// source; any value yields a boundary absent from every part, but only
88    /// unpredictable entropy keeps the boundary unguessable.
89    ///
90    /// A content type containing a control character (CR/LF included) is
91    /// rejected. Quotes, CR and LF in names and filenames are percent-encoded as
92    /// browsers do; other bytes are written as given.
93    pub fn encode(&self, entropy: [u8; 16]) -> Result<Encoded> {
94        for part in &self.parts {
95            if part
96                .media_type()
97                .is_some_and(|t| t.bytes().any(|b| b.is_ascii_control()))
98            {
99                return Err(Error::new(
100                    "UND_ERR_INVALID_ARG",
101                    "invalid multipart content type",
102                ));
103            }
104        }
105        let names: Vec<_> = self
106            .parts
107            .iter()
108            .map(|p| (escape(&p.name), p.filename.as_deref().map(escape)))
109            .collect();
110        let boundary = self.boundary(entropy, &names);
111        // Framing per part is under 128 bytes beyond the boundary, name,
112        // filename and content type; the closing delimiter adds 6.
113        let mut body = Vec::with_capacity(
114            self.parts
115                .iter()
116                .zip(&names)
117                .map(|(part, (name, filename))| {
118                    part.body.len()
119                        + name.len()
120                        + filename.as_ref().map_or(0, String::len)
121                        + part.media_type().map_or(0, str::len)
122                        + boundary.len()
123                        + 128
124                })
125                .sum::<usize>()
126                + boundary.len()
127                + 6,
128        );
129        for (part, (name, filename)) in self.parts.iter().zip(&names) {
130            body.extend_from_slice(b"--");
131            body.extend_from_slice(boundary.as_bytes());
132            body.extend_from_slice(b"\r\nContent-Disposition: form-data; name=\"");
133            body.extend_from_slice(name.as_bytes());
134            body.push(b'"');
135            if let Some(filename) = filename {
136                body.extend_from_slice(b"; filename=\"");
137                body.extend_from_slice(filename.as_bytes());
138                body.push(b'"');
139            }
140            if let Some(media_type) = part.media_type() {
141                body.extend_from_slice(b"\r\nContent-Type: ");
142                body.extend_from_slice(media_type.as_bytes());
143            }
144            body.extend_from_slice(b"\r\n\r\n");
145            body.extend_from_slice(&part.body);
146            body.extend_from_slice(b"\r\n");
147        }
148        body.extend_from_slice(b"--");
149        body.extend_from_slice(boundary.as_bytes());
150        body.extend_from_slice(b"--\r\n");
151        Ok(Encoded { boundary, body })
152    }
153    /// The first candidate that occurs in no part. Candidates are pairwise
154    /// distinct and each one found in a part matches at least one of that
155    /// part's finitely many substrings, so the search ends within
156    /// (total part bytes + 1) candidates.
157    fn boundary(&self, entropy: [u8; 16], names: &[(String, Option<String>)]) -> String {
158        let entropy = u128::from_le_bytes(entropy);
159        let (low, high) = (entropy as u64, (entropy >> 64) as u64);
160        let mut index = 0u64;
161        loop {
162            let boundary = candidate(low, high, index);
163            let needle = boundary.as_bytes();
164            let collides = self
165                .parts
166                .iter()
167                .zip(names)
168                .any(|(part, (name, filename))| {
169                    [
170                        Some(part.body.as_slice()),
171                        Some(name.as_bytes()),
172                        filename.as_deref().map(str::as_bytes),
173                        part.media_type().map(str::as_bytes),
174                    ]
175                    .into_iter()
176                    .flatten()
177                    .any(|bytes| contains(bytes, needle))
178                });
179            if !collides {
180                return boundary;
181            }
182            index += 1;
183        }
184    }
185}
186
187/// An encoded form body and the boundary its `Content-Type` must name.
188#[derive(Debug, Clone, PartialEq, Eq)]
189pub struct Encoded {
190    pub boundary: String,
191    pub body: Vec<u8>,
192}
193impl Encoded {
194    /// The `Content-Type` header value for this body.
195    pub fn content_type(&self) -> String {
196        format!("multipart/form-data; boundary={}", self.boundary)
197    }
198    /// Make this the request body, replacing any `Content-Type` header.
199    pub fn apply(self, request: &mut Request) {
200        let content_type = self.content_type();
201        request
202            .headers
203            .retain(|h| !h.name.eq_ignore_ascii_case("content-type"));
204        request
205            .headers
206            .push(Header::new("content-type", content_type));
207        request.body = self.body;
208    }
209}
210
211/// `"turnloop-"` and 32 hex digits: 41 characters, within RFC 2046's 70, and
212/// no character that needs quoting in the `Content-Type` parameter.
213const PREFIX: &str = "turnloop-";
214const BOUNDARY_LEN: usize = PREFIX.len() + 32;
215
216fn candidate(low: u64, high: u64, index: u64) -> String {
217    // SplitMix64: its finalizer is a bijection and the odd increment makes each
218    // index's input distinct, so every index yields a distinct first half.
219    const GAMMA: u64 = 0x9e37_79b9_7f4a_7c15;
220    let first = mix(low.wrapping_add(index.wrapping_mul(GAMMA)));
221    let second = mix(high ^ first);
222    let mut boundary = String::with_capacity(BOUNDARY_LEN);
223    boundary.push_str(PREFIX);
224    for word in [first, second] {
225        for shift in (0..16).rev() {
226            let digit = ((word >> (shift * 4)) & 15) as u8;
227            boundary.push(char::from(if digit < 10 {
228                b'0' + digit
229            } else {
230                b'a' + digit - 10
231            }));
232        }
233    }
234    boundary
235}
236
237fn mix(mut z: u64) -> u64 {
238    z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
239    z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
240    z ^ (z >> 31)
241}
242
243fn contains(haystack: &[u8], needle: &[u8]) -> bool {
244    haystack
245        .windows(needle.len())
246        .any(|window| window == needle)
247}
248
249/// The WHATWG form-data escaping of a name or filename.
250fn escape(value: &str) -> String {
251    let mut escaped = String::with_capacity(value.len());
252    for c in value.chars() {
253        match c {
254            '"' => escaped.push_str("%22"),
255            '\r' => escaped.push_str("%0D"),
256            '\n' => escaped.push_str("%0A"),
257            c => escaped.push(c),
258        }
259    }
260    escaped
261}