Skip to main content

glacier/
upload.rs

1//! Files uploaded in a `multipart/form-data` request.
2//!
3//! A multipart body's text fields become ordinary params; its files are
4//! read with [`Context::file`](crate::Context::file), by field name as the
5//! form sent it (`comment[note_image]`), as Rails' `params[:comment][:note_image]`.
6
7use bytes::Bytes;
8
9/// A file from a multipart form: its name on the client, its declared
10/// content type and its bytes.
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub struct Upload {
13    pub filename: String,
14    pub content_type: String,
15    pub bytes: Bytes,
16}
17
18impl Upload {
19    pub fn len(&self) -> usize {
20        self.bytes.len()
21    }
22
23    pub fn is_empty(&self) -> bool {
24        self.bytes.is_empty()
25    }
26
27    /// The file's type as its bytes show it, the declared type aside, as
28    /// Paperclip's detector stores it: the type its signature names
29    /// (`image/png`), else its extension's, else `text/plain` for text and
30    /// `application/octet-stream` for anything else; `inode/x-empty` when
31    /// empty.
32    pub fn detected_type(&self) -> String {
33        if self.bytes.is_empty() {
34            return "inode/x-empty".into();
35        }
36        if let Some(sniffed) = sniff(&self.bytes) {
37            return sniffed.into();
38        }
39        extension(&self.filename)
40            .and_then(|ext| crate::mime::for_format(&ext))
41            .unwrap_or(if is_text(&self.bytes) {
42                "text/plain"
43            } else {
44                "application/octet-stream"
45            })
46            .into()
47    }
48
49    /// Whether the file isn't what its declared type says, as Paperclip's
50    /// spoof check: the declared kind (`image` of `image/png`) disagrees
51    /// with the extension's (`shelf.pdf`) or with the bytes (text sent as
52    /// `image/png`). A Rails app's message for it is "has contents that are
53    /// not what they are reported to be".
54    ///
55    /// Unlike `file`, it knows only common types: bytes it can't name, and
56    /// extensions it doesn't know, never count as a mismatch.
57    pub fn is_spoofed(&self) -> bool {
58        let declared = self.content_type.split('/').next().unwrap_or("").trim();
59        if self.filename.is_empty() || declared.is_empty() {
60            return false;
61        }
62        let by_extension = extension(&self.filename)
63            .and_then(|ext| crate::mime::for_format(&ext))
64            .is_some_and(|known| !known.starts_with(&format!("{declared}/")));
65        let by_contents = sniff(&self.bytes)
66            .or_else(|| is_text(&self.bytes).then_some("text/plain"))
67            .is_some_and(|found| !found.contains(declared));
68        by_extension || by_contents
69    }
70}
71
72/// A file name's extension, lower-cased: `Shelf.PNG` → `png`.
73fn extension(filename: &str) -> Option<String> {
74    let (stem, ext) = filename.rsplit_once('.')?;
75    (!stem.is_empty() && !ext.is_empty()).then(|| ext.to_ascii_lowercase())
76}
77
78/// Text: UTF-8 without NULs.
79fn is_text(bytes: &[u8]) -> bool {
80    !bytes.contains(&0) && std::str::from_utf8(bytes).is_ok()
81}
82
83/// The type a file's signature (its first bytes) names, for common types;
84/// text that is SVG, XML or JSON by its start.
85fn sniff(bytes: &[u8]) -> Option<&'static str> {
86    let starts = |magic: &[u8]| bytes.starts_with(magic);
87    let at = |offset: usize, magic: &[u8]| bytes.get(offset..offset + magic.len()) == Some(magic);
88    Some(match () {
89        () if starts(b"\x89PNG\r\n\x1a\n") => "image/png",
90        () if starts(b"\xff\xd8\xff") => "image/jpeg",
91        () if starts(b"GIF87a") || starts(b"GIF89a") => "image/gif",
92        () if starts(b"RIFF") && at(8, b"WEBP") => "image/webp",
93        () if starts(b"II*\0") || starts(b"MM\0*") => "image/tiff",
94        // BMP: "BM" and four reserved zero bytes, so text can't pass.
95        () if starts(b"BM") && at(6, b"\0\0\0\0") => "image/bmp",
96        () if starts(b"\0\0\x01\0") => "image/vnd.microsoft.icon",
97        () if at(4, b"ftyp") => match bytes.get(8..12).unwrap_or_default() {
98            b"heic" | b"heix" | b"hevc" | b"heim" | b"heis" | b"hevm" | b"hevs" | b"mif1"
99            | b"msf1" => "image/heic",
100            b"avif" | b"avis" => "image/avif",
101            b"qt  " => "video/quicktime",
102            _ => "video/mp4",
103        },
104        () if starts(b"%PDF-") => "application/pdf",
105        () if starts(b"PK\x03\x04") => "application/zip",
106        () if starts(b"\x1f\x8b") => "application/gzip",
107        () if starts(b"ID3") || starts(b"\xff\xfb") => "audio/mpeg",
108        () if starts(b"OggS") => "audio/ogg",
109        () if starts(b"\x1a\x45\xdf\xa3") => "video/webm",
110        () if is_text(bytes) => {
111            let head = std::str::from_utf8(&bytes[..bytes.len().min(1024)])
112                .unwrap_or_default()
113                .trim_start();
114            if head.contains("<svg") {
115                "image/svg+xml"
116            } else if head.starts_with("<?xml") {
117                "text/xml"
118            } else if (head.starts_with('{') || head.starts_with('['))
119                && serde_json::from_slice::<serde_json::Value>(bytes).is_ok()
120            {
121                "application/json"
122            } else {
123                return None;
124            }
125        }
126        () => return None,
127    })
128}
129
130/// One part of a multipart body.
131#[derive(Debug, Clone, PartialEq, Eq)]
132pub(crate) enum Part {
133    Field(String, String),
134    File(String, Upload),
135}
136
137/// The boundary from a `multipart/form-data; boundary=…` content type.
138pub(crate) fn boundary(content_type: &str) -> Option<String> {
139    let (kind, params) = content_type.split_once(';')?;
140    if !kind.trim().eq_ignore_ascii_case("multipart/form-data") {
141        return None;
142    }
143    params.split(';').find_map(|param| {
144        let (name, value) = param.split_once('=')?;
145        name.trim()
146            .eq_ignore_ascii_case("boundary")
147            .then(|| value.trim().trim_matches('"').to_owned())
148    })
149}
150
151/// The parts of a buffered multipart body. Malformed parts are skipped;
152/// a file field left empty (no file chosen) is left out, as a browser
153/// sends one.
154pub(crate) fn parse(body: &[u8], boundary: &str) -> Vec<Part> {
155    let delimiter = format!("--{boundary}");
156    let mut parts = Vec::new();
157    let mut rest = match find(body, delimiter.as_bytes()) {
158        Some(start) => &body[start + delimiter.len()..],
159        None => return parts,
160    };
161    let separator = format!("\r\n--{boundary}");
162    loop {
163        // After a delimiter: `--` ends the body; otherwise a line break.
164        if rest.starts_with(b"--") {
165            break;
166        }
167        rest = rest.strip_prefix(b"\r\n").unwrap_or(rest);
168        let Some(end) = find(rest, separator.as_bytes()) else {
169            break;
170        };
171        if let Some(part) = parse_part(&rest[..end]) {
172            parts.push(part);
173        }
174        rest = &rest[end + separator.len()..];
175    }
176    parts
177}
178
179fn parse_part(part: &[u8]) -> Option<Part> {
180    let split = find(part, b"\r\n\r\n")?;
181    let headers = std::str::from_utf8(&part[..split]).ok()?;
182    let content = &part[split + 4..];
183    let mut name = None;
184    let mut filename = None;
185    let mut content_type = None;
186    for line in headers.split("\r\n") {
187        let Some((header, value)) = line.split_once(':') else {
188            continue;
189        };
190        if header.trim().eq_ignore_ascii_case("content-disposition") {
191            for param in value.split(';').skip(1) {
192                let Some((key, value)) = param.split_once('=') else {
193                    continue;
194                };
195                let value = value.trim().trim_matches('"').to_owned();
196                match key.trim() {
197                    "name" => name = Some(value),
198                    "filename" => filename = Some(value),
199                    _ => {}
200                }
201            }
202        } else if header.trim().eq_ignore_ascii_case("content-type") {
203            content_type = Some(value.trim().to_owned());
204        }
205    }
206    let name = name?;
207    match filename {
208        Some(filename) if filename.is_empty() && content.is_empty() => None,
209        Some(filename) => Some(Part::File(
210            name,
211            Upload {
212                filename,
213                content_type: content_type.unwrap_or_else(|| "application/octet-stream".into()),
214                bytes: Bytes::copy_from_slice(content),
215            },
216        )),
217        None => Some(Part::Field(
218            name,
219            String::from_utf8_lossy(content).into_owned(),
220        )),
221    }
222}
223
224fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
225    haystack
226        .windows(needle.len())
227        .position(|window| window == needle)
228}
229
230#[cfg(test)]
231mod tests {
232    use super::*;
233
234    fn body(boundary: &str) -> Vec<u8> {
235        let mut body = Vec::new();
236        body.extend_from_slice(
237            format!(
238                "--{boundary}\r\nContent-Disposition: form-data; name=\"session_id\"\r\n\r\n7\r\n"
239            )
240            .as_bytes(),
241        );
242        body.extend_from_slice(format!("--{boundary}\r\nContent-Disposition: form-data; name=\"comment[note_image]\"; filename=\"shelf.png\"\r\nContent-Type: image/png\r\n\r\n").as_bytes());
243        body.extend_from_slice(b"\x89PNG\r\n--not the end");
244        body.extend_from_slice(format!("\r\n--{boundary}\r\nContent-Disposition: form-data; name=\"empty\"; filename=\"\"\r\nContent-Type: application/octet-stream\r\n\r\n\r\n").as_bytes());
245        body.extend_from_slice(format!("--{boundary}--\r\n").as_bytes());
246        body
247    }
248
249    #[test]
250    fn reads_fields_and_files() {
251        let b = "----glacier123";
252        assert_eq!(
253            boundary(&format!("multipart/form-data; boundary=\"{b}\"")).as_deref(),
254            Some(b)
255        );
256        assert_eq!(boundary("application/json"), None);
257        let parts = parse(&body(b), b);
258        assert_eq!(parts.len(), 2, "the empty file field is left out");
259        assert_eq!(parts[0], Part::Field("session_id".into(), "7".into()));
260        let Part::File(name, upload) = &parts[1] else {
261            panic!("{:?}", parts[1])
262        };
263        assert_eq!(name, "comment[note_image]");
264        assert_eq!(upload.filename, "shelf.png");
265        assert_eq!(upload.content_type, "image/png");
266        assert_eq!(
267            &upload.bytes[..],
268            b"\x89PNG\r\n--not the end",
269            "a CRLF and dashes inside a file are content"
270        );
271    }
272
273    fn upload(filename: &str, content_type: &str, bytes: &[u8]) -> Upload {
274        Upload {
275            filename: filename.into(),
276            content_type: content_type.into(),
277            bytes: Bytes::copy_from_slice(bytes),
278        }
279    }
280
281    const PNG: &[u8] = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR";
282    const PDF: &[u8] = b"%PDF-1.4\n%\xe2\xe3\xcf\xd3\n";
283
284    #[test]
285    fn detects_a_type_from_the_bytes_then_the_name() {
286        assert_eq!(
287            upload("shelf.png", "text/plain", PNG).detected_type(),
288            "image/png"
289        );
290        // A JPEG named .png is a JPEG.
291        assert_eq!(
292            upload("a.png", "image/png", b"\xff\xd8\xff\xe0").detected_type(),
293            "image/jpeg"
294        );
295        assert_eq!(
296            upload("note.pdf", "application/octet-stream", PDF).detected_type(),
297            "application/pdf"
298        );
299        // Bytes without a signature: the extension's type, as Paperclip.
300        assert_eq!(
301            upload("fake.png", "text/plain", b"not an image\n").detected_type(),
302            "image/png"
303        );
304        assert_eq!(upload("notes", "", b"hello").detected_type(), "text/plain");
305        assert_eq!(
306            upload("blob", "", &[0, 159, 146, 150]).detected_type(),
307            "application/octet-stream"
308        );
309        assert_eq!(
310            upload("empty.png", "image/png", b"").detected_type(),
311            "inode/x-empty"
312        );
313    }
314
315    #[test]
316    fn spoofed_when_the_declared_kind_disagrees() {
317        // Honest uploads.
318        assert!(!upload("shelf.png", "image/png", PNG).is_spoofed());
319        assert!(
320            !upload("Shelf.PNG", "image/jpeg", PNG).is_spoofed(),
321            "same kind: image"
322        );
323        assert!(!upload("note.pdf", "application/pdf", PDF).is_spoofed());
324        assert!(!upload("notes.txt", "text/plain", b"hello").is_spoofed());
325        assert!(!upload("data.json", "application/json", b"{\"a\": 1}").is_spoofed());
326        assert!(!upload("logo.svg", "image/svg+xml", b"<svg xmlns=\"x\"/>").is_spoofed());
327        // Text claiming to be an image, by its type and by its name.
328        assert!(upload("fake.png", "text/plain", b"not an image\n").is_spoofed());
329        assert!(upload("fake.png", "image/png", b"not an image\n").is_spoofed());
330        // A PDF named as a photo.
331        assert!(upload("shelf.pdf", "image/png", PNG).is_spoofed());
332        // What it can't tell isn't a mismatch: unknown bytes, unknown extensions.
333        assert!(!upload("photo.heif2", "image/x-new", &[0, 1, 2, 3, 200]).is_spoofed());
334        assert!(!upload("", "image/png", b"text").is_spoofed(), "no name");
335        assert!(
336            !upload("a.png", "", b"text").is_spoofed(),
337            "no declared type"
338        );
339    }
340}