Skip to main content

serenade_form/
multipart.rs

1//! `multipart/form-data` body parser.
2
3use std::collections::HashMap;
4use std::hash::BuildHasher;
5
6use crate::file::{FileStorage, UploadedFile};
7use crate::kind::{DEFAULT_MAX_MULTIPART_BODY, FileOptions};
8use crate::{FormError, parse_urlencoded_multi};
9
10type PartHeaders = Vec<(String, String)>;
11
12/// Parsed multipart form: text fields and file uploads.
13#[derive(Debug, Default)]
14pub struct MultipartData {
15    /// Text field values (submission order preserved per key).
16    pub fields: HashMap<String, Vec<String>>,
17    /// File uploads (last part wins per field name).
18    pub files: HashMap<String, UploadedFile>,
19}
20
21/// Extracts the `boundary` parameter from a `Content-Type` header value.
22#[must_use]
23pub fn multipart_boundary(content_type: &str) -> Option<&str> {
24    let lower = content_type.to_ascii_lowercase();
25    if !lower.starts_with("multipart/form-data") {
26        return None;
27    }
28    for part in content_type.split(';').skip(1) {
29        let part = part.trim();
30        let Some((key, value)) = part.split_once('=') else {
31            continue;
32        };
33        if key.trim().eq_ignore_ascii_case("boundary") {
34            return Some(value.trim().trim_matches('"'));
35        }
36    }
37    None
38}
39
40/// Returns `true` when `content_type` is `multipart/form-data`.
41#[must_use]
42pub fn is_multipart(content_type: Option<&str>) -> bool {
43    content_type.is_some_and(|value| {
44        value
45            .split(';')
46            .next()
47            .is_some_and(|mime| mime.trim().eq_ignore_ascii_case("multipart/form-data"))
48    })
49}
50
51/// Parses a `multipart/form-data` body.
52///
53/// `file_options` maps field names to [`FileOptions`] used for size, MIME, and storage.
54/// Unknown file parts use [`FileOptions::default`].
55///
56/// # Errors
57///
58/// Returns [`FormError::Multipart`] when the body exceeds `max_body`, the boundary is
59/// missing/invalid, or a part cannot be decoded. Returns [`FormError::Upload`] when a
60/// declared file field violates size or MIME constraints.
61pub fn parse_multipart<S: BuildHasher>(
62    body: &[u8],
63    boundary: &str,
64    file_options: &HashMap<String, FileOptions, S>,
65    max_body: u64,
66) -> Result<MultipartData, FormError> {
67    if body.len() as u64 > max_body {
68        return Err(FormError::Multipart(format!(
69            "body exceeds max size of {max_body} bytes"
70        )));
71    }
72    if boundary.is_empty() {
73        return Err(FormError::Multipart(String::from("empty boundary")));
74    }
75    let delimiter = format!("--{boundary}").into_bytes();
76    let parts = split_multipart_parts(body, &delimiter)?;
77    let mut data = MultipartData::default();
78    for part in parts {
79        if part.is_empty() {
80            continue;
81        }
82        let (headers, content) = split_part_headers(part)?;
83        let disposition = header_value(&headers, "content-disposition").ok_or_else(|| {
84            FormError::Multipart(String::from("part missing Content-Disposition"))
85        })?;
86        let name = disposition_param(disposition, "name")
87            .ok_or_else(|| FormError::Multipart(String::from("part missing name parameter")))?;
88        let filename = disposition_param(disposition, "filename");
89        if let Some(filename) = filename {
90            // Empty file inputs post `filename=""` with an empty body; treat as absent.
91            if filename.is_empty() && content.is_empty() {
92                continue;
93            }
94            let content_type = header_value(&headers, "content-type").map(str::to_owned);
95            let options = file_options
96                .get(name)
97                .cloned()
98                .unwrap_or_else(FileOptions::default);
99            let upload = build_upload(filename, content_type, content, &options)?;
100            data.files.insert(name.to_owned(), upload);
101        } else {
102            let text = std::str::from_utf8(content)
103                .map_err(|_| FormError::Multipart(String::from("text part is not UTF-8")))?;
104            data.fields
105                .entry(name.to_owned())
106                .or_default()
107                .push(text.to_owned());
108        }
109    }
110    Ok(data)
111}
112
113/// Parses urlencoded or multipart from a request body using `Content-Type`.
114///
115/// # Errors
116///
117/// Propagates [`parse_urlencoded_multi`] or [`parse_multipart`] failures. Missing
118/// multipart boundary yields [`FormError::Multipart`].
119pub fn parse_form_body<S: BuildHasher>(
120    content_type: Option<&str>,
121    body: &[u8],
122    file_options: &HashMap<String, FileOptions, S>,
123) -> Result<MultipartData, FormError> {
124    if is_multipart(content_type) {
125        let boundary = content_type
126            .and_then(multipart_boundary)
127            .ok_or_else(|| FormError::Multipart(String::from("missing multipart boundary")))?;
128        parse_multipart(body, boundary, file_options, DEFAULT_MAX_MULTIPART_BODY)
129    } else {
130        let fields = parse_urlencoded_multi(body)?;
131        Ok(MultipartData {
132            fields,
133            files: HashMap::new(),
134        })
135    }
136}
137
138fn build_upload(
139    filename: &str,
140    content_type: Option<String>,
141    content: &[u8],
142    options: &FileOptions,
143) -> Result<UploadedFile, FormError> {
144    if content.len() as u64 > options.max_size {
145        return Err(FormError::Upload(format!(
146            "file exceeds max size of {} bytes",
147            options.max_size
148        )));
149    }
150    if !options.mime_types.is_empty() {
151        let mime = content_type.as_deref().unwrap_or("");
152        let allowed = options
153            .mime_types
154            .iter()
155            .any(|allowed| mime_matches(mime, allowed));
156        if !allowed {
157            return Err(FormError::Upload(format!(
158                "content type {mime:?} is not allowed"
159            )));
160        }
161    }
162    let filename = if filename.is_empty() {
163        None
164    } else {
165        Some(filename.to_owned())
166    };
167    match options.storage {
168        FileStorage::Memory => Ok(UploadedFile::from_bytes(
169            filename,
170            content_type,
171            content.to_vec(),
172        )),
173        FileStorage::TempFile => UploadedFile::from_tempfile(filename, content_type, content),
174    }
175}
176
177fn mime_matches(actual: &str, allowed: &str) -> bool {
178    let actual = actual.trim().to_ascii_lowercase();
179    let allowed = allowed.trim().to_ascii_lowercase();
180    if allowed.ends_with("/*") {
181        let prefix = &allowed[..allowed.len() - 1];
182        return actual.starts_with(prefix);
183    }
184    actual == allowed
185}
186
187fn split_multipart_parts<'a>(body: &'a [u8], delimiter: &[u8]) -> Result<Vec<&'a [u8]>, FormError> {
188    let mut parts = Vec::new();
189    let mut rest = body;
190    if rest.starts_with(delimiter) {
191        rest = &rest[delimiter.len()..];
192        rest = strip_leading_crlf(rest);
193    } else if let Some(pos) = find_bytes(rest, delimiter) {
194        rest = &rest[pos + delimiter.len()..];
195        rest = strip_leading_crlf(rest);
196    } else {
197        return Err(FormError::Multipart(String::from("boundary not found")));
198    }
199    loop {
200        if rest.starts_with(b"--") {
201            break;
202        }
203        let Some(pos) = find_bytes(rest, delimiter) else {
204            return Err(FormError::Multipart(String::from(
205                "unterminated multipart body",
206            )));
207        };
208        let mut part = &rest[..pos];
209        part = strip_trailing_crlf(part);
210        parts.push(part);
211        rest = &rest[pos + delimiter.len()..];
212        rest = strip_leading_crlf(rest);
213    }
214    Ok(parts)
215}
216
217fn split_part_headers(part: &[u8]) -> Result<(PartHeaders, &[u8]), FormError> {
218    let sep = find_header_body_sep(part).ok_or_else(|| {
219        FormError::Multipart(String::from("multipart part missing header terminator"))
220    })?;
221    let header_bytes = &part[..sep.start];
222    let content = &part[sep.end..];
223    let header_text = std::str::from_utf8(header_bytes)
224        .map_err(|_| FormError::Multipart(String::from("multipart headers are not UTF-8")))?;
225    let mut headers = Vec::new();
226    for line in header_text.split('\n') {
227        let line = line.trim_end_matches('\r');
228        if line.is_empty() {
229            continue;
230        }
231        let (name, value) = line
232            .split_once(':')
233            .ok_or_else(|| FormError::Multipart(String::from("malformed multipart header line")))?;
234        headers.push((name.trim().to_ascii_lowercase(), value.trim().to_owned()));
235    }
236    Ok((headers, content))
237}
238
239struct Span {
240    start: usize,
241    end: usize,
242}
243
244fn find_header_body_sep(part: &[u8]) -> Option<Span> {
245    if let Some(pos) = find_bytes(part, b"\r\n\r\n") {
246        return Some(Span {
247            start: pos,
248            end: pos + 4,
249        });
250    }
251    find_bytes(part, b"\n\n").map(|pos| Span {
252        start: pos,
253        end: pos + 2,
254    })
255}
256
257fn header_value<'a>(headers: &'a [(String, String)], name: &str) -> Option<&'a str> {
258    headers
259        .iter()
260        .find(|(key, _)| key == name)
261        .map(|(_, value)| value.as_str())
262}
263
264fn disposition_param<'a>(disposition: &'a str, key: &str) -> Option<&'a str> {
265    for part in disposition.split(';').skip(1) {
266        let part = part.trim();
267        let Some((name, value)) = part.split_once('=') else {
268            continue;
269        };
270        if name.trim().eq_ignore_ascii_case(key) {
271            return Some(value.trim().trim_matches('"'));
272        }
273    }
274    None
275}
276
277fn find_bytes(haystack: &[u8], needle: &[u8]) -> Option<usize> {
278    haystack
279        .windows(needle.len())
280        .position(|window| window == needle)
281}
282
283fn strip_leading_crlf(bytes: &[u8]) -> &[u8] {
284    if bytes.starts_with(b"\r\n") {
285        &bytes[2..]
286    } else if bytes.starts_with(b"\n") {
287        &bytes[1..]
288    } else {
289        bytes
290    }
291}
292
293fn strip_trailing_crlf(bytes: &[u8]) -> &[u8] {
294    if bytes.ends_with(b"\r\n") {
295        &bytes[..bytes.len() - 2]
296    } else if bytes.ends_with(b"\n") {
297        &bytes[..bytes.len() - 1]
298    } else {
299        bytes
300    }
301}