1 // Copyright 2021 Ian Jackson and contributors to Hippotat
2 // SPDX-License-Identifier: GPL-3.0-or-later
3 // There is NO WARRANTY.
8 pub struct Component<'b> {
10 pub payload: &'b [u8],
14 #[derive(Eq,PartialEq,Ord,PartialOrd,Hash)]
15 #[allow(non_camel_case_types)]
16 pub enum PartName { m, d, Other }
18 pub type BoundaryFinder = memchr::memmem::Finder<'static>;
21 /// Processes the start of a component (or terminating boundary).
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;
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")) };
35 let mut part_name = None;
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")) }
46 let l = str::from_utf8(l).context("interpret part headers as utf-8")?;
48 let (_, disposition) = if let Some(y) =
49 regex_captures!(r#"^Content-Disposition[ \t]*:[ \t]*(.*)$"#i, l) { y }
50 else { return Ok(()) };
52 let disposition = disposition.trim_end();
53 if disposition.len() >= 100 { throw!(anyhow!(
54 "Content-Disposition value implausibly long"
56 // This let's us pretend it's a mime type, so we can use mime::Mime
57 let disposition = format!("dummy/{}", disposition);
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"#))?;
64 let name = match name.as_ref() {
70 if let Some(_) = mem::replace(&mut part_name, Some(name)) {
71 throw!(anyhow!(r#"multiple "name"s in Content-Disposition(s)"#))
75 Err(e) => warnings.add(&e)?,
80 Some(Component { name: part_name.unwrap_or(expected), payload: rhs })
83 pub struct ComponentIterator<'b> {
84 at_boundary: &'b [u8],
85 boundary_finder: BoundaryFinder,
88 #[derive(Error,Debug)]
89 #[error("missing mime multipart boundary")]
90 pub struct MissingBoundary;
92 impl<'b> ComponentIterator<'b> {
93 #[throws(MissingBoundary)]
94 pub fn resume_mid_component(buf: &'b [u8], boundary_finder: BoundaryFinder)
96 let next_boundary = boundary_finder.find(buf).ok_or(MissingBoundary)?;
97 let part = &buf[0..next_boundary];
98 let part = Self::payload_trim(part);
99 (part, ComponentIterator {
100 at_boundary: &buf[next_boundary..],
105 fn payload_trim(payload: &[u8]) -> &[u8] {
106 payload.strip_suffix(b"\r").unwrap_or(payload)
110 pub fn next(&mut self, warnings: &mut Warnings, expected: PartName)
111 -> Option<Component<'b>> {
112 if self.at_boundary.is_empty() { return None }
114 let mut comp = match {
115 let boundary_len = self.boundary_finder.needle().len();
116 process_boundary(warnings,
117 &self.at_boundary[boundary_len..],
121 self.at_boundary = &self.at_boundary[0..0];
127 let next_boundary = self.boundary_finder.find(&comp.payload)
128 .ok_or(MissingBoundary)?;
130 comp.payload = Self::payload_trim(&comp.payload[0..next_boundary]);
131 self.at_boundary = &self.at_boundary[next_boundary..];
136 pub struct MetadataFieldIterator<'b> {
139 iter: memchr::Memchr<'b>,
142 impl<'b> MetadataFieldIterator<'b> {
143 pub fn new(buf: &'b [u8]) -> Self { Self {
146 iter: memchr::Memchr::new(b'\n', buf),
150 pub fn need_next(&mut self) -> &'b str
152 self.next().ok_or_else(|| anyhow!("missing"))??
156 pub fn need_parse<T>(&mut self) -> T
160 self.parse()?.ok_or_else(|| anyhow!("missing"))?
164 pub fn parse<T>(&mut self) -> Option<T>
168 let s = if let Some(r) = self.next() { r? } else { return None };
172 pub fn remaining_bytes_len(&self) -> usize {
173 if let Some(last) = self.last {
174 self.buf.len() - last
181 impl<'b> Iterator for MetadataFieldIterator<'b> {
182 type Item = Result<&'b str, std::str::Utf8Error>;
183 fn next(&mut self) -> Option<Result<&'b str, std::str::Utf8Error>> {
184 let last = self.last?;
185 let (s, last) = match self.iter.next() {
186 Some(nl) => (&self.buf[last..nl], Some(nl+1)),
187 None => (&self.buf[last..], None),
190 let s = str::from_utf8(s).map(|s| s.trim());
194 impl<'b> std::iter::FusedIterator for MetadataFieldIterator<'b> { }