chiark / gitweb /
server: wip
[hippotat.git] / src / multipart.rs
1 // Copyright 2021 Ian Jackson and contributors to Hippotat
2 // SPDX-License-Identifier: GPL-3.0-or-later
3 // There is NO WARRANTY.
4
5 use crate::prelude::*;
6
7 #[derive(Debug)]
8 pub struct Component<'b> {
9   pub name: PartName,
10   pub payload_start: &'b [u8],
11 }
12
13 #[derive(Debug)]
14 #[derive(Eq,PartialEq,Ord,PartialOrd,Hash)]
15 #[allow(non_camel_case_types)]
16 pub enum PartName { m, d, Other }
17
18 #[throws(AE)]
19 pub fn process_component<'b>(warnings: &mut Warnings,
20                              after_leader: &'b [u8], expected: PartName)
21                              -> Option<Component<'b>> {
22   let rhs = after_leader;
23   let mut rhs =
24        if let Some(rhs) = rhs.strip_prefix(b"\r\n") { rhs         }
25   else if let Some(_  ) = rhs.strip_prefix(b"--"  ) { return None }
26   else if let Some(rhs) = rhs.strip_prefix(b"\n"  ) { rhs         }
27   else { throw!(anyhow!("invalid multipart delimiter")) };
28
29   let mut part_name = None;
30
31   loop {
32     // RHS points to the start of a header line
33     let nl = memchr::memchr(b'\n', rhs)
34       .ok_or_else(|| anyhow!("part headers truncated"))?;
35     let l = &rhs[0..nl]; rhs = &rhs[nl+1..];
36     if l == b"\r" || l == b"" { break } // end of headers
37     if l.starts_with(b"--") { throw!(anyhow!("boundary in part headers")) }
38
39     match (||{
40       let l = str::from_utf8(l).context("interpret part headers as utf-8")?;
41
42       let (_, disposition) = if let Some(y) =
43         regex_captures!(r#"^Content-Disposition[ \t]*:[ \t]*(.*)$"#i, l) { y }
44         else { return Ok(()) };
45
46       let disposition = disposition.trim_end();
47       if disposition.len() >= 100 { throw!(anyhow!(
48         "Content-Disposition value implausibly long"
49       )) }
50       // This let's us pretend it's a mime type, so we can use mime::Mime
51       let disposition = format!("dummy/{}", disposition);
52
53       let disposition: mime::Mime = disposition.parse()
54         .context("parse Content-Disposition")?;
55       let name = disposition.get_param("name")
56         .ok_or_else(|| anyhow!(r#"find "name" in Content-Disposition"#))?;
57
58       let name = match name.as_ref() {
59         "m" => PartName::m,
60         "d" => PartName::d,
61         _   => PartName::Other,
62       };
63
64       if let Some(_) = mem::replace(&mut part_name, Some(name)) {
65         throw!(anyhow!(r#"multiple "name"s in Content-Disposition(s)"#))
66       }
67       Ok::<_,AE>(())
68     })() {
69       Err(e) => warnings.add(&e)?,
70       Ok(()) => { },
71     };
72   }
73
74   Some(Component { name: part_name.unwrap_or(expected), payload_start: rhs })
75 }