form_net/multipart/filename.rs
1//! Views of a client's file name. form-net never uses a file name as a path.
2
3use core::fmt;
4
5use crate::error::{EncodingError, FormError, Location};
6
7/// Where a file name came from.
8#[non_exhaustive]
9#[derive(Clone, Copy, Debug, PartialEq, Eq)]
10pub enum FileNameSource {
11 /// The `filename` parameter.
12 Plain,
13 /// An accepted `filename*` parameter (RFC 8187, decoded).
14 Extended,
15}
16
17/// The client's file name, with a view for each way a caller might want it.
18///
19/// **form-net never uses a client file name as a path or as part of one.**
20/// `Debug` prints the length only: file names are user data.
21///
22/// # Examples
23///
24/// ```
25/// let body = b"--X\r\nContent-Disposition: form-data; name=\"doc\"; filename=\"C:\\Users\\me\\a b.pdf\"\r\n\r\nx\r\n--X--";
26/// let mp = form_net::parse_multipart(b"multipart/form-data; boundary=X", body)?;
27/// let name = mp.file("doc").unwrap().filename().unwrap();
28/// assert_eq!(name.raw(), b"C:\\Users\\me\\a b.pdf");
29/// assert_eq!(name.basename(), b"a b.pdf");
30/// # Ok::<(), form_net::FormError>(())
31/// ```
32#[derive(Clone, Copy)]
33pub struct FileName<'a> {
34 raw: &'a [u8],
35 source: FileNameSource,
36}
37
38impl<'a> FileName<'a> {
39 pub(crate) const fn new(raw: &'a [u8], source: FileNameSource) -> Self {
40 Self { raw, source }
41 }
42
43 /// The bytes as sent between the quotes of `filename`, untouched; or the
44 /// decoded bytes of an accepted `filename*`.
45 ///
46 /// # Examples
47 ///
48 /// ```
49 /// # let body = b"--X\r\nContent-Disposition: form-data; name=f; filename=\"a%22b.txt\"\r\n\r\n\r\n--X--";
50 /// # let mp = form_net::parse_multipart(b"multipart/form-data; boundary=X", body)?;
51 /// let name = mp.file("f").unwrap().filename().unwrap();
52 /// assert_eq!(name.raw(), b"a%22b.txt");
53 /// # Ok::<(), form_net::FormError>(())
54 /// ```
55 #[must_use]
56 pub const fn raw(&self) -> &'a [u8] {
57 self.raw
58 }
59
60 /// The raw bytes as UTF-8.
61 ///
62 /// # Errors
63 ///
64 /// `Encoding { InvalidUtf8 }`.
65 ///
66 /// # Examples
67 ///
68 /// ```
69 /// # let body = "--X\r\nContent-Disposition: form-data; name=f; filename=\"café.txt\"\r\n\r\n\r\n--X--";
70 /// # let mp = form_net::parse_multipart(b"multipart/form-data; boundary=X", body.as_bytes())?;
71 /// assert_eq!(mp.file("f").unwrap().filename().unwrap().as_str()?, "café.txt");
72 /// # Ok::<(), form_net::FormError>(())
73 /// ```
74 pub fn as_str(&self) -> Result<&'a str, FormError> {
75 core::str::from_utf8(self.raw)
76 .map_err(|_| FormError::encoding(EncodingError::InvalidUtf8, Location::at(0)))
77 }
78
79 /// Whether the name is empty: a file input left empty.
80 ///
81 /// # Examples
82 ///
83 /// ```
84 /// # let body = b"--X\r\nContent-Disposition: form-data; name=f; filename=\"\"\r\n\r\n\r\n--X--";
85 /// # let mp = form_net::parse_multipart(b"multipart/form-data; boundary=X", body)?;
86 /// assert!(mp.file("f").unwrap().filename().unwrap().is_empty());
87 /// # Ok::<(), form_net::FormError>(())
88 /// ```
89 #[must_use]
90 pub const fn is_empty(&self) -> bool {
91 self.raw.is_empty()
92 }
93
94 /// `Plain` for `filename`, `Extended` for `filename*`.
95 ///
96 /// # Examples
97 ///
98 /// ```
99 /// use form_net::FileNameSource;
100 /// # let body = b"--X\r\nContent-Disposition: form-data; name=f; filename=a\r\n\r\n\r\n--X--";
101 /// # let mp = form_net::parse_multipart(b"multipart/form-data; boundary=X", body)?;
102 /// assert_eq!(mp.file("f").unwrap().filename().unwrap().source(), FileNameSource::Plain);
103 /// # Ok::<(), form_net::FormError>(())
104 /// ```
105 #[must_use]
106 pub const fn source(&self) -> FileNameSource {
107 self.source
108 }
109
110 /// The bytes after the last `/` or `\` (some non-browser clients send
111 /// full client paths).
112 ///
113 /// # Examples
114 ///
115 /// ```
116 /// # let body = b"--X\r\nContent-Disposition: form-data; name=f; filename=\"a/b\\c.txt\"\r\n\r\n\r\n--X--";
117 /// # let mp = form_net::parse_multipart(b"multipart/form-data; boundary=X", body)?;
118 /// assert_eq!(mp.file("f").unwrap().filename().unwrap().basename(), b"c.txt");
119 /// # Ok::<(), form_net::FormError>(())
120 /// ```
121 #[must_use]
122 pub fn basename(&self) -> &'a [u8] {
123 match self.raw.iter().rposition(|&b| b == b'/' || b == b'\\') {
124 Some(i) => self.raw.get(i.wrapping_add(1)..).unwrap_or(&[]),
125 None => self.raw,
126 }
127 }
128
129 /// Writes the name into `out` with the HTML escapes `%0A`, `%0D`, `%22`
130 /// decoded to LF, CR, `"`, and nothing else, and returns it as text.
131 /// Browsers do not escape `%` itself, so a file the user named `a%22b`
132 /// reads as `a"b`; that ambiguity is inherent in the HTML encoding.
133 ///
134 /// # Errors
135 ///
136 /// `BufferTooSmall` when `out` is shorter than [`raw`](Self::raw);
137 /// `Encoding { InvalidUtf8 }`.
138 ///
139 /// # Examples
140 ///
141 /// ```
142 /// # let body = b"--X\r\nContent-Disposition: form-data; name=f; filename=\"a%22b.txt\"\r\n\r\n\r\n--X--";
143 /// # let mp = form_net::parse_multipart(b"multipart/form-data; boundary=X", body)?;
144 /// let mut out = [0u8; 32];
145 /// let name = mp.file("f").unwrap().filename().unwrap();
146 /// assert_eq!(name.html_unescape_into(&mut out)?, "a\"b.txt");
147 /// # Ok::<(), form_net::FormError>(())
148 /// ```
149 pub fn html_unescape_into<'b>(&self, out: &'b mut [u8]) -> Result<&'b str, FormError> {
150 if out.len() < self.raw.len() {
151 return Err(FormError::BufferTooSmall {
152 needed: self.raw.len(),
153 });
154 }
155 let n = html_unescape(self.raw, out);
156 core::str::from_utf8(out.get(..n).unwrap_or(&[]))
157 .map_err(|_| FormError::encoding(EncodingError::InvalidUtf8, Location::at(0)))
158 }
159
160 /// As [`html_unescape_into`](Self::html_unescape_into), borrowed when the
161 /// name has nothing to decode.
162 ///
163 /// # Errors
164 ///
165 /// `Encoding { InvalidUtf8 }`.
166 ///
167 /// # Examples
168 ///
169 /// ```
170 /// # let body = b"--X\r\nContent-Disposition: form-data; name=f; filename=\"a%0Ab\"\r\n\r\n\r\n--X--";
171 /// # let mp = form_net::parse_multipart(b"multipart/form-data; boundary=X", body)?;
172 /// assert_eq!(mp.file("f").unwrap().filename().unwrap().html_unescaped()?, "a\nb");
173 /// # Ok::<(), form_net::FormError>(())
174 /// ```
175 #[cfg(feature = "alloc")]
176 #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
177 pub fn html_unescaped(&self) -> Result<alloc::borrow::Cow<'a, str>, FormError> {
178 if !has_html_escape(self.raw) {
179 return self.as_str().map(alloc::borrow::Cow::Borrowed);
180 }
181 let mut out = alloc::vec![0u8; self.raw.len()];
182 let n = html_unescape(self.raw, &mut out);
183 out.truncate(n);
184 alloc::string::String::from_utf8(out)
185 .map(alloc::borrow::Cow::Owned)
186 .map_err(|_| FormError::encoding(EncodingError::InvalidUtf8, Location::at(0)))
187 }
188}
189
190impl fmt::Debug for FileName<'_> {
191 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
192 write!(f, "FileName({} bytes)", self.raw.len())
193 }
194}
195
196/// The byte an HTML multipart escape at the start of `s` stands for.
197#[inline]
198fn html_escape_at(s: &[u8]) -> Option<u8> {
199 match s.get(..3)? {
200 b"%0A" => Some(b'\n'),
201 b"%0D" => Some(b'\r'),
202 b"%22" => Some(b'"'),
203 _ => None,
204 }
205}
206
207pub(crate) fn has_html_escape(s: &[u8]) -> bool {
208 let mut i = 0usize;
209 loop {
210 i = crate::scan::find_byte(s, i, b'%');
211 if i >= s.len() {
212 return false;
213 }
214 if html_escape_at(s.get(i..).unwrap_or(&[])).is_some() {
215 return true;
216 }
217 i = i.wrapping_add(1);
218 }
219}
220
221/// Decodes the three HTML escapes of `src` into `out` (at least as long) and
222/// returns the length written.
223pub(crate) fn html_unescape(src: &[u8], out: &mut [u8]) -> usize {
224 let mut i = 0usize;
225 let mut w = 0usize;
226 while i < src.len() {
227 let rest = src.get(i..).unwrap_or(&[]);
228 let (byte, step) = match html_escape_at(rest) {
229 Some(b) => (b, 3usize),
230 None => (*rest.first().unwrap_or(&0), 1usize),
231 };
232 if let Some(slot) = out.get_mut(w) {
233 *slot = byte;
234 }
235 w = w.wrapping_add(1);
236 i = i.wrapping_add(step);
237 }
238 w
239}
240
241#[cfg(test)]
242mod tests {
243 use super::*;
244
245 fn name(raw: &[u8]) -> FileName<'_> {
246 FileName::new(raw, FileNameSource::Plain)
247 }
248
249 #[test]
250 fn test_basename_cases() {
251 assert_eq!(name(b"a/b\\c.txt").basename(), b"c.txt");
252 assert_eq!(name(b"c.txt").basename(), b"c.txt");
253 assert_eq!(name(b"/").basename(), b"");
254 assert_eq!(name(b"").basename(), b"");
255 assert_eq!(name(b"\\\\").basename(), b"");
256 }
257
258 #[test]
259 fn test_html_unescape_only_three_escapes() {
260 let mut out = [0u8; 32];
261 assert_eq!(
262 name(b"%0A%0D%22").html_unescape_into(&mut out).unwrap(),
263 "\n\r\""
264 );
265 assert_eq!(
266 name(b"%25%0a%41").html_unescape_into(&mut out).unwrap(),
267 "%25%0a%41"
268 );
269 assert_eq!(name(b"%2").html_unescape_into(&mut out).unwrap(), "%2");
270 assert!(name(b"\xff").html_unescape_into(&mut out).is_err());
271 let mut small = [0u8; 2];
272 assert_eq!(
273 name(b"abc").html_unescape_into(&mut small),
274 Err(FormError::BufferTooSmall { needed: 3 })
275 );
276 }
277
278 #[cfg(feature = "alloc")]
279 #[test]
280 fn test_html_unescaped_borrows_when_plain() {
281 assert!(matches!(
282 name(b"plain").html_unescaped().unwrap(),
283 alloc::borrow::Cow::Borrowed("plain")
284 ));
285 assert_eq!(name(b"a%22").html_unescaped().unwrap(), "a\"");
286 }
287
288 #[test]
289 fn test_debug_hides_the_name() {
290 assert_eq!(
291 alloc::format!("{:?}", name(b"secret.pdf")),
292 "FileName(10 bytes)"
293 );
294 }
295}