chiark / gitweb /
multipart: process_boundary: Rename, and better docs
[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: &'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 pub type BoundaryFinder = memchr::memmem::Finder<'static>;
19
20 #[throws(AE)]
21 /// Processes the start of a component (or terminating boundary).
22 ///
23 /// Returned payload is only the start of the payload; the next
24 /// boundary has not been identified.
25 pub fn process_boundary<'b>(warnings: &mut Warnings,
26                             after_leader: &'b [u8], expected: PartName)
27                             -> Option<Component<'b>> {
28   let rhs = after_leader;
29   let mut rhs =
30        if let Some(rhs) = rhs.strip_prefix(b"\r\n") { rhs         }
31   else if let Some(_  ) = rhs.strip_prefix(b"--"  ) { return None }
32   else if let Some(rhs) = rhs.strip_prefix(b"\n"  ) { rhs         }
33   else { throw!(anyhow!("invalid multipart delimiter")) };
34
35   let mut part_name = None;
36
37   loop {
38     // RHS points to the start of a header line
39     let nl = memchr::memchr(b'\n', rhs)
40       .ok_or_else(|| anyhow!("part headers truncated"))?;
41     let l = &rhs[0..nl]; rhs = &rhs[nl+1..];
42     if l == b"\r" || l == b"" { break } // end of headers
43     if l.starts_with(b"--") { throw!(anyhow!("boundary in part headers")) }
44
45     match (||{
46       let l = str::from_utf8(l).context("interpret part headers as utf-8")?;
47
48       let (_, disposition) = if let Some(y) =
49         regex_captures!(r#"^Content-Disposition[ \t]*:[ \t]*(.*)$"#i, l) { y }
50         else { return Ok(()) };
51
52       let disposition = disposition.trim_end();
53       if disposition.len() >= 100 { throw!(anyhow!(
54         "Content-Disposition value implausibly long"
55       )) }
56       // This let's us pretend it's a mime type, so we can use mime::Mime
57       let disposition = format!("dummy/{}", disposition);
58
59       let disposition: mime::Mime = disposition.parse()
60         .context("parse Content-Disposition")?;
61       let name = disposition.get_param("name")
62         .ok_or_else(|| anyhow!(r#"find "name" in Content-Disposition"#))?;
63
64       let name = match name.as_ref() {
65         "m" => PartName::m,
66         "d" => PartName::d,
67         _   => PartName::Other,
68       };
69
70       if let Some(_) = mem::replace(&mut part_name, Some(name)) {
71         throw!(anyhow!(r#"multiple "name"s in Content-Disposition(s)"#))
72       }
73       Ok::<_,AE>(())
74     })() {
75       Err(e) => warnings.add(&e)?,
76       Ok(()) => { },
77     };
78   }
79
80   Some(Component { name: part_name.unwrap_or(expected), payload: rhs })
81 }
82
83 pub struct MetadataFieldIterator<'b> {
84   buf: &'b [u8],
85   last: Option<usize>,
86   iter: memchr::Memchr<'b>,
87 }
88
89 impl<'b> MetadataFieldIterator<'b> {
90   pub fn new(buf: &'b [u8]) -> Self { Self {
91     buf,
92     last: Some(0),
93     iter: memchr::Memchr::new(b'\n', buf),
94   } }
95
96   #[throws(AE)]
97   pub fn need_next(&mut self) -> &'b str
98   {
99     self.next().ok_or_else(|| anyhow!("missing"))??
100   }
101
102   #[throws(AE)]
103   pub fn need_parse<T>(&mut self) -> T
104   where T: FromStr,
105         AE: From<T::Err>,
106   {
107     self.parse()?.ok_or_else(|| anyhow!("missing"))?
108   }
109
110   #[throws(AE)]
111   pub fn parse<T>(&mut self) -> Option<T>
112   where T: FromStr,
113         AE: From<T::Err>,
114   {
115     let s = if let Some(r) = self.next() { r? } else { return None };
116     Some(s.parse()?)
117   }
118
119   pub fn remaining_bytes_len(&self) -> usize {
120     if let Some(last) = self.last {
121       self.buf.len() - last
122     } else {
123       0
124     }
125   }
126 }
127                                       
128 impl<'b> Iterator for MetadataFieldIterator<'b> {
129   type Item = Result<&'b str, std::str::Utf8Error>;
130   fn next(&mut self) -> Option<Result<&'b str, std::str::Utf8Error>> {
131     let last = self.last?;
132     let (s, last) = match self.iter.next() {
133       Some(nl) => (&self.buf[last..nl], Some(nl+1)),
134       None     => (&self.buf[last..],   None),
135     };
136     self.last = last;
137     let s = str::from_utf8(s).map(|s| s.trim());
138     Some(s)
139   }
140 }
141 impl<'b> std::iter::FusedIterator for MetadataFieldIterator<'b> { }