chiark / gitweb /
1c0be403351b4d91fe691afc6d7d39e10b79d8fe
[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 }
76
77 pub struct MetadataFieldIterator<'b> {
78   buf: &'b [u8],
79   last: Option<usize>,
80   iter: memchr::Memchr<'b>,
81 }
82
83 impl<'b> MetadataFieldIterator<'b> {
84   pub fn new(buf: &'b [u8]) -> Self { Self {
85     buf,
86     last: Some(0),
87     iter: memchr::Memchr::new(b'\n', buf),
88   } }
89
90   #[throws(AE)]
91   pub fn need_next(&mut self) -> &'b str
92   {
93     self.next().ok_or_else(|| anyhow!("missing"))??
94   }
95
96   #[throws(AE)]
97   pub fn need_parse<T>(&mut self) -> T
98   where T: FromStr,
99         AE: From<T::Err>,
100   {
101     self.parse()?.ok_or_else(|| anyhow!("missing"))?
102   }
103
104   #[throws(AE)]
105   pub fn parse<T>(&mut self) -> Option<T>
106   where T: FromStr,
107         AE: From<T::Err>,
108   {
109     let s = if let Some(r) = self.next() { r? } else { return None };
110     Some(s.parse()?)
111   }
112 }
113                                       
114 impl<'b> Iterator for MetadataFieldIterator<'b> {
115   type Item = Result<&'b str, std::str::Utf8Error>;
116   fn next(&mut self) -> Option<Result<&'b str, std::str::Utf8Error>> {
117     let last = self.last?;
118     let (s, last) = match self.iter.next() {
119       Some(nl) => (&self.buf[last..nl], Some(nl+1)),
120       None     => (&self.buf[last..],   None),
121     };
122     self.last = last;
123     let s = str::from_utf8(s).map(|s| s.trim());
124     Some(s)
125   }
126 }
127 impl<'b> std::iter::FusedIterator for MetadataFieldIterator<'b> { }