http_type/body/impl.rs
1use super::*;
2
3/// Implementation for `MultipartFormData`.
4impl MultipartFormData {
5 /// Reads the `boundary` parameter out of a `multipart/form-data` content type.
6 ///
7 /// The parameter is matched case-insensitively and accepts both a quoted and
8 /// a bare value, so the clients that emit `boundary="abc"` and the clients
9 /// that emit `boundary=abc` are both accepted. A parameter that carries no
10 /// `=` is skipped rather than aborting the scan.
11 ///
12 /// # Arguments
13 ///
14 /// - `C` - The content type header value, which requires the `AsRef<str>` bound.
15 ///
16 /// # Returns
17 ///
18 /// - `Option<MultipartFormDataBoundary>` - The declared boundary, or `None` when absent.
19 pub fn get_boundary<C>(content_type: C) -> Option<MultipartFormDataBoundary>
20 where
21 C: AsRef<str>,
22 {
23 for parameter in Self::split_header_parameters(content_type.as_ref())
24 .into_iter()
25 .skip(1)
26 {
27 let Some((key, value)) = parameter.trim().split_once(EQUAL) else {
28 continue;
29 };
30 if !key
31 .trim()
32 .eq_ignore_ascii_case(MULTIPART_BOUNDARY_PARAMETER)
33 {
34 continue;
35 }
36 let value: &str = Self::unquote(value.trim());
37 if !value.is_empty() {
38 return Some(value.to_string());
39 }
40 }
41 None
42 }
43
44 /// Splits a header value on semicolons that appear outside quoted strings.
45 ///
46 /// # Arguments
47 ///
48 /// - `&str` - The header value to split into parameter segments.
49 ///
50 /// # Returns
51 ///
52 /// - `Vec<&str>` - The unquoted-semicolon-delimited segments.
53 pub(crate) fn split_header_parameters(input: &str) -> Vec<&str> {
54 let mut segments: Vec<&str> = Vec::new();
55 let mut start: usize = 0;
56 let mut quoted: bool = false;
57 let mut escaped: bool = false;
58 for (offset, byte) in input.bytes().enumerate() {
59 match byte {
60 _ if escaped => escaped = false,
61 b'\\' if quoted => escaped = true,
62 b'"' => quoted = !quoted,
63 b';' if !quoted => {
64 segments.push(&input[start..offset]);
65 start = offset + 1;
66 }
67 _ => {}
68 }
69 }
70 segments.push(&input[start..]);
71 segments
72 }
73
74 /// Checks whether a content type declares a `multipart/form-data` body.
75 ///
76 /// # Arguments
77 ///
78 /// - `C` - The content type header value, which requires the `AsRef<str>` bound.
79 ///
80 /// # Returns
81 ///
82 /// - `bool` - Whether the content type is `multipart/form-data`.
83 pub fn is_form_data<C>(content_type: C) -> bool
84 where
85 C: AsRef<str>,
86 {
87 content_type
88 .as_ref()
89 .split(SEMICOLON)
90 .next()
91 .unwrap_or(EMPTY_STR)
92 .trim()
93 .eq_ignore_ascii_case(MULTIPART_FORM_DATA)
94 }
95
96 /// Strips one pair of surrounding quotes from a header parameter value.
97 ///
98 /// # Arguments
99 ///
100 /// - `&str` - The raw parameter value.
101 ///
102 /// # Returns
103 ///
104 /// - `&str` - The value without its surrounding quotes.
105 fn unquote(value: &str) -> &str {
106 value
107 .strip_prefix(MULTIPART_PARAMETER_QUOTE)
108 .and_then(|value: &str| value.strip_suffix(MULTIPART_PARAMETER_QUOTE))
109 .unwrap_or(value)
110 }
111
112 /// Finds the first occurrence of a needle inside a haystack.
113 ///
114 /// # Arguments
115 ///
116 /// - `&[u8]` - The bytes to search in.
117 /// - `&[u8]` - The bytes to search for.
118 ///
119 /// # Returns
120 ///
121 /// - `Option<usize>` - The offset of the first occurrence, or `None` when absent.
122 fn find_subslice(haystack: &[u8], needle: &[u8]) -> Option<usize> {
123 if needle.is_empty() || needle.len() > haystack.len() {
124 return None;
125 }
126 haystack
127 .windows(needle.len())
128 .position(|window: &[u8]| window == needle)
129 }
130
131 /// Builds the byte delimiter that marks a boundary line in the body.
132 ///
133 /// # Arguments
134 ///
135 /// - `&str` - The declared boundary, without its leading dash pair.
136 ///
137 /// # Returns
138 ///
139 /// - `Vec<u8>` - The delimiter bytes, dash pair included.
140 fn build_delimiter(boundary: &str) -> Vec<u8> {
141 let mut delimiter: Vec<u8> = Vec::with_capacity(boundary.len() + 4);
142 delimiter.extend_from_slice(MULTIPART_DELIMITER_DASH.as_bytes());
143 delimiter.extend_from_slice(boundary.as_bytes());
144 delimiter
145 }
146
147 /// Checks whether the bytes after a delimiter are a closing dash pair.
148 ///
149 /// The closing boundary writes a second dash pair right after the boundary
150 /// token, optionally followed by the line break that ends the body.
151 ///
152 /// # Arguments
153 ///
154 /// - `&[u8]` - The bytes that follow the delimiter.
155 ///
156 /// # Returns
157 ///
158 /// - `bool` - Whether the delimiter is closed by a dash pair.
159 fn is_closing_delimiter(remainder: &[u8]) -> bool {
160 let Some(after_dash) = remainder.strip_prefix(MULTIPART_DELIMITER_DASH.as_bytes()) else {
161 return false;
162 };
163 after_dash.is_empty()
164 || after_dash.starts_with(HTTP_BR.as_bytes())
165 || after_dash.starts_with(MULTIPART_LINE_FEED)
166 }
167
168 /// Checks whether the bytes after a delimiter close a boundary line.
169 ///
170 /// A boundary line ends at a line break or at the end of the body, so the
171 /// dash pair of the closing boundary is matched here rather than being part
172 /// of the delimiter itself.
173 ///
174 /// # Arguments
175 ///
176 /// - `&[u8]` - The bytes that follow the delimiter.
177 ///
178 /// # Returns
179 ///
180 /// - `bool` - Whether the delimiter is followed by a boundary line ending.
181 fn is_boundary_tail(remainder: &[u8]) -> bool {
182 remainder.starts_with(HTTP_BR.as_bytes())
183 || remainder.starts_with(MULTIPART_LINE_FEED)
184 || Self::is_closing_delimiter(remainder)
185 }
186
187 /// Finds every byte offset at which the boundary delimiter starts.
188 ///
189 /// # Arguments
190 ///
191 /// - `&[u8]` - The raw request body.
192 /// - `&[u8]` - The boundary delimiter, dash pair included.
193 ///
194 /// # Returns
195 ///
196 /// - `Vec<usize>` - The ascending offsets of every delimiter occurrence.
197 fn find_delimiter_positions(body: &[u8], delimiter: &[u8]) -> Vec<usize> {
198 let mut positions: Vec<usize> = Vec::new();
199 let mut offset: usize = 0;
200 while offset < body.len() {
201 let Some(found) = Self::find_subslice(&body[offset..], delimiter) else {
202 break;
203 };
204 let position: usize = offset + found;
205 let at_line_start: bool = position == 0 || body[position - 1] == b'\n';
206 let after: usize = position + delimiter.len();
207 if at_line_start && (after == body.len() || Self::is_boundary_tail(&body[after..])) {
208 positions.push(position);
209 if Self::is_closing_delimiter(&body[after..]) {
210 break;
211 }
212 }
213 offset = position + 1;
214 }
215 positions
216 }
217
218 /// Removes the line breaks that belong to a boundary line from a segment.
219 ///
220 /// The break that follows the opening delimiter is stripped from the front,
221 /// and the break that precedes the closing delimiter is stripped from the
222 /// back: per the multipart grammar both belong to the boundary line, not to
223 /// the part content.
224 ///
225 /// # Arguments
226 ///
227 /// - `&[u8]` - The raw segment between two boundary lines.
228 ///
229 /// # Returns
230 ///
231 /// - `&[u8]` - The segment without its surrounding boundary line breaks.
232 fn trim_boundary_breaks(segment: &[u8]) -> &[u8] {
233 let segment: &[u8] = segment
234 .strip_prefix(HTTP_BR.as_bytes())
235 .or_else(|| segment.strip_prefix(MULTIPART_LINE_FEED))
236 .unwrap_or(segment);
237 if let Some(trimmed) = segment.strip_suffix(HTTP_BR.as_bytes()) {
238 return trimmed;
239 }
240 segment.strip_suffix(MULTIPART_LINE_FEED).unwrap_or(segment)
241 }
242
243 /// Splits a body into the raw segments carried between boundary lines.
244 ///
245 /// Both `CRLF` and bare `LF` line breaks are accepted, and the breaks that
246 /// belong to a boundary line are not part of a segment. The final boundary
247 /// must be the closing one: a body whose last boundary opens a part that is
248 /// never closed is truncated, and reporting it as `None` keeps a truncated
249 /// upload from passing as a complete one.
250 ///
251 /// # Arguments
252 ///
253 /// - `&'a [u8]` - The raw request body.
254 /// - `&str` - The declared boundary, without its leading dash pair.
255 ///
256 /// # Returns
257 ///
258 /// - `Option<MultipartFormDataSegments<'a>>` - The body segments, or `None` when malformed.
259 fn split_segments<'a>(body: &'a [u8], boundary: &str) -> Option<MultipartFormDataSegments<'a>> {
260 let delimiter: Vec<u8> = Self::build_delimiter(boundary);
261 let positions: Vec<usize> = Self::find_delimiter_positions(body, &delimiter);
262 let last_position: usize = positions.last().copied()?;
263 let last_end: usize = last_position + delimiter.len();
264 if !Self::is_closing_delimiter(&body[last_end..]) {
265 return None;
266 }
267 let mut segments: MultipartFormDataSegments = Vec::with_capacity(positions.len());
268 for index in 0..positions.len().saturating_sub(1) {
269 let start: usize = positions[index] + delimiter.len();
270 let end: usize = positions[index + 1];
271 segments.push(Self::trim_boundary_breaks(&body[start..end]));
272 }
273 Some(segments)
274 }
275
276 /// Splits a part into its header block and its content.
277 ///
278 /// # Arguments
279 ///
280 /// - `&[u8]` - The raw segment of a single part.
281 ///
282 /// # Returns
283 ///
284 /// - `(&[u8], &[u8])` - The header block and the content of the part.
285 fn split_part(segment: &[u8]) -> (&[u8], &[u8]) {
286 let fallback: &[u8] = &segment[segment.len()..];
287 if let Some(position) = Self::find_subslice(segment, HTTP_DOUBLE_BR.as_bytes()) {
288 let data_start: usize = position + HTTP_DOUBLE_BR.len();
289 return (&segment[..position], &segment[data_start..]);
290 }
291 if let Some(position) = Self::find_subslice(segment, MULTIPART_HEADER_SEPARATOR) {
292 let data_start: usize = position + MULTIPART_HEADER_SEPARATOR_LEN;
293 return (&segment[..position], &segment[data_start..]);
294 }
295 (segment, fallback)
296 }
297
298 /// Decodes the header block of a single part.
299 ///
300 /// # Arguments
301 ///
302 /// - `&[u8]` - The header block of the part, terminated by a blank line.
303 ///
304 /// # Returns
305 ///
306 /// - `Option<BodyPartHeaders>` - The decoded headers, or `None` when not valid text.
307 fn parse_part_headers(header_block: &[u8]) -> Option<BodyPartHeaders> {
308 let header_text: &str = from_utf8(header_block).ok()?;
309 let mut headers: BodyPartHeaders = hash_map_xx_hash3_64();
310 for raw_line in header_text.split('\n') {
311 let line: &str = raw_line.strip_suffix('\r').unwrap_or(raw_line).trim();
312 if line.is_empty() {
313 continue;
314 }
315 let (key, value) = line.split_once(COLON)?;
316 let key: String = key.trim().to_ascii_lowercase();
317 if key.is_empty() {
318 continue;
319 }
320 headers.insert(key, value.trim().to_string());
321 }
322 Some(headers)
323 }
324
325 /// Reads the `name` and `filename` parameters of a part content disposition.
326 ///
327 /// # Arguments
328 ///
329 /// - `&str` - The part `Content-Disposition` header value.
330 ///
331 /// # Returns
332 ///
333 /// - `(BodyPartName, BodyPartFileName)` - The declared field name and file name.
334 fn parse_part_disposition(disposition: &str) -> (BodyPartName, BodyPartFileName) {
335 let mut name: BodyPartName = String::new();
336 let mut file_name: BodyPartFileName = String::new();
337 for parameter in Self::split_header_parameters(disposition)
338 .into_iter()
339 .skip(1)
340 {
341 let Some((key, value)) = parameter.trim().split_once(EQUAL) else {
342 continue;
343 };
344 let value: &str = Self::unquote(value.trim());
345 match key.trim().to_ascii_lowercase().as_str() {
346 MULTIPART_NAME_PARAMETER => name = value.to_string(),
347 FILENAME => file_name = value.to_string(),
348 _ => {}
349 }
350 }
351 (name, file_name)
352 }
353
354 /// Decodes every part of a `multipart/form-data` body.
355 ///
356 /// A body that carries no declared boundary, a body whose final boundary is
357 /// not the closing one, and a part that declares no `name` all yield `None`.
358 ///
359 /// # Arguments
360 ///
361 /// - `B` - The raw request body, which requires the `AsRef<[u8]>` bound.
362 /// - `&str` - The declared boundary, without its leading dash pair.
363 ///
364 /// # Returns
365 ///
366 /// - `Option<MultipartFormDataParts>` - The decoded parts, or `None` when malformed.
367 pub fn parse<B>(body: B, boundary: &str) -> Option<MultipartFormDataParts>
368 where
369 B: AsRef<[u8]>,
370 {
371 let segments: MultipartFormDataSegments = Self::split_segments(body.as_ref(), boundary)?;
372 let mut parts: MultipartFormDataParts = Vec::with_capacity(segments.len());
373 for segment in segments {
374 if segment.is_empty() {
375 continue;
376 }
377 let (header_block, data) = Self::split_part(segment);
378 let headers: BodyPartHeaders = Self::parse_part_headers(header_block)?;
379 let disposition: String = headers
380 .get(MULTIPART_CONTENT_DISPOSITION)
381 .cloned()
382 .unwrap_or_default();
383 let (name, file_name) = Self::parse_part_disposition(&disposition);
384 if name.is_empty() || parts.len() >= MULTIPART_MAX_PARTS {
385 return None;
386 }
387 let content_type: BodyPartContentType =
388 headers.get(CONTENT_TYPE).cloned().unwrap_or_default();
389 parts.push(BodyPart::new(
390 name,
391 file_name,
392 content_type,
393 headers,
394 data.to_vec(),
395 ));
396 }
397 Some(parts)
398 }
399
400 /// Tries to get a part by its form field name.
401 ///
402 /// # Arguments
403 ///
404 /// - `&[BodyPart]` - The decoded parts of the body.
405 /// - `K` - The form field name, which requires the `AsRef<str>` bound.
406 ///
407 /// # Returns
408 ///
409 /// - `Option<&BodyPart>` - The first part carrying that name, or `None`.
410 pub fn try_get_part<K>(parts: &[BodyPart], name: K) -> Option<&BodyPart>
411 where
412 K: AsRef<str>,
413 {
414 let name: &str = name.as_ref();
415 parts
416 .iter()
417 .find(|part: &&BodyPart| part.get_name() == name)
418 }
419
420 /// Tries to get a plain text field by its form field name.
421 ///
422 /// A part that uploads a file is skipped, so a file field never silently
423 /// decodes as text.
424 ///
425 /// # Arguments
426 ///
427 /// - `&[BodyPart]` - The decoded parts of the body.
428 /// - `K` - The form field name, which requires the `AsRef<str>` bound.
429 ///
430 /// # Returns
431 ///
432 /// - `Option<BodyFormValue>` - The field value, or `None` when absent or a file.
433 pub fn try_get_part_text<K>(parts: &[BodyPart], name: K) -> Option<BodyFormValue>
434 where
435 K: AsRef<str>,
436 {
437 let part: &BodyPart = Self::try_get_part(parts, name)?;
438 if !part.get_file_name().is_empty() {
439 return None;
440 }
441 Some(String::from_utf8_lossy(part.get_data()).into_owned())
442 }
443
444 /// Decodes an `application/x-www-form-urlencoded` body into its fields.
445 ///
446 /// # Arguments
447 ///
448 /// - `B` - The raw request body, which requires the `AsRef<[u8]>` bound.
449 ///
450 /// # Returns
451 ///
452 /// - `BodyForm` - The decoded form fields.
453 pub fn parse_url_encoded<B>(body: B) -> BodyForm
454 where
455 B: AsRef<[u8]>,
456 {
457 let decoded: String = String::from_utf8_lossy(body.as_ref()).into_owned();
458 let mut form: BodyForm = hash_map_xx_hash3_64();
459 for pair in decoded.split(AND) {
460 if pair.is_empty() {
461 continue;
462 }
463 let (key, value) = pair.split_once(EQUAL).unwrap_or((pair, EMPTY_STR));
464 let key: BodyFormKey = Self::decode_form_component(key);
465 if key.is_empty() {
466 continue;
467 }
468 form.insert(key, Self::decode_form_component(value));
469 }
470 form
471 }
472
473 /// Decodes one percent-encoded form component.
474 ///
475 /// `+` is decoded as a space, `%XX` as the matching byte, and an invalid
476 /// escape is kept verbatim instead of dropping the component.
477 ///
478 /// # Arguments
479 ///
480 /// - `&str` - The raw component of the form body.
481 ///
482 /// # Returns
483 ///
484 /// - `String` - The decoded component.
485 fn decode_form_component(component: &str) -> String {
486 let bytes: Vec<u8> = component.bytes().collect();
487 let mut decoded: Vec<u8> = Vec::with_capacity(bytes.len());
488 let mut index: usize = 0;
489 while index < bytes.len() {
490 let byte: u8 = bytes[index];
491 match byte {
492 URL_ENCODED_PLUS => {
493 decoded.push(URL_ENCODED_SPACE);
494 index += 1;
495 }
496 byte if byte == URL_ENCODED_PERCENT && index + 2 < bytes.len() => {
497 match Self::parse_hex_pair(&bytes[index + 1], &bytes[index + 2]) {
498 Some(value) => {
499 decoded.push(value);
500 index += 3;
501 }
502 None => {
503 decoded.push(byte);
504 index += 1;
505 }
506 }
507 }
508 _ => {
509 decoded.push(byte);
510 index += 1;
511 }
512 }
513 }
514 String::from_utf8_lossy(&decoded).into_owned()
515 }
516
517 /// Reads the two hexadecimal digits of a percent escape.
518 ///
519 /// # Arguments
520 ///
521 /// - `&u8` - The high digit of the escape.
522 /// - `&u8` - The low digit of the escape.
523 ///
524 /// # Returns
525 ///
526 /// - `Option<u8>` - The decoded byte, or `None` when a digit is not hexadecimal.
527 fn parse_hex_pair(high: &u8, low: &u8) -> Option<u8> {
528 let high_digit: u8 = Self::hex_digit(high)?;
529 let low_digit: u8 = Self::hex_digit(low)?;
530 Some(high_digit * HEX_RADIX + low_digit)
531 }
532
533 /// Converts one hexadecimal digit into its numeric value.
534 ///
535 /// # Arguments
536 ///
537 /// - `&u8` - The ASCII byte of the digit.
538 ///
539 /// # Returns
540 ///
541 /// - `Option<u8>` - The numeric value, or `None` when the byte is not hexadecimal.
542 fn hex_digit(byte: &u8) -> Option<u8> {
543 match byte {
544 HEX_DIGIT_ZERO..=HEX_DIGIT_NINE => Some(byte - HEX_DIGIT_ZERO),
545 HEX_DIGIT_LOWER_A..=HEX_DIGIT_LOWER_F => {
546 Some(byte - HEX_DIGIT_LOWER_A + HEX_LOWER_OFFSET)
547 }
548 HEX_DIGIT_UPPER_A..=HEX_DIGIT_UPPER_F => {
549 Some(byte - HEX_DIGIT_UPPER_A + HEX_LOWER_OFFSET)
550 }
551 _ => None,
552 }
553 }
554}
555
556/// Inherent implementation of [`BodyPart`].
557impl BodyPart {
558 /// Tries to get the form field name of this part.
559 ///
560 /// # Returns
561 ///
562 /// - `Option<&BodyPartName>` - The declared field name, or `None` when
563 /// the part declares none.
564 pub fn try_get_name(&self) -> Option<&BodyPartName> {
565 (!self.get_name().is_empty()).then_some(self.get_name())
566 }
567
568 /// Tries to get the uploaded file name of this part.
569 ///
570 /// # Returns
571 ///
572 /// - `Option<&BodyPartFileName>` - The declared file name, or `None`
573 /// when this part is a plain field rather than a file upload.
574 pub fn try_get_file_name(&self) -> Option<&BodyPartFileName> {
575 (!self.get_file_name().is_empty()).then_some(self.get_file_name())
576 }
577
578 /// Tries to get the media type declared by this part.
579 ///
580 /// # Returns
581 ///
582 /// - `Option<&BodyPartContentType>` - The declared media type, or
583 /// `None` when the part declares none.
584 pub fn try_get_content_type(&self) -> Option<&BodyPartContentType> {
585 (!self.get_content_type().is_empty()).then_some(self.get_content_type())
586 }
587
588 /// Tries to get the value of one of this part's headers.
589 ///
590 /// # Arguments
591 ///
592 /// - `K` - The header name, which must implement `AsRef<str>`.
593 ///
594 /// # Returns
595 ///
596 /// - `Option<&BodyPartHeaderValue>` - The header value, or `None`
597 /// when this part carries no such header.
598 pub fn try_get_header<K>(&self, key: K) -> Option<&BodyPartHeaderValue>
599 where
600 K: AsRef<str>,
601 {
602 let key_ref: &str = key.as_ref();
603 if !key_ref
604 .as_bytes()
605 .iter()
606 .any(|byte: &u8| byte.is_ascii_uppercase())
607 {
608 return self.get_headers().get(key_ref);
609 }
610 self.get_headers().get(&key_ref.to_ascii_lowercase())
611 }
612
613 /// Tries to get this part's raw content.
614 ///
615 /// # Returns
616 ///
617 /// - `Option<&[u8]>` - The raw bytes, or `None` when the part is empty.
618 pub fn try_get_data(&self) -> Option<&[u8]> {
619 (!self.get_data().is_empty()).then(|| self.get_data().as_slice())
620 }
621
622 /// Tries to get this part's raw content as UTF-8 text.
623 ///
624 /// Invalid UTF-8 is replaced rather than rejected, so a binary upload
625 /// read as text yields its readable bytes instead of `None`.
626 ///
627 /// # Returns
628 ///
629 /// - `Option<BodyFormValue>` - The decoded text, or `None` when the
630 /// part is empty.
631 pub fn try_get_text(&self) -> Option<BodyFormValue> {
632 self.try_get_data()
633 .map(|data: &[u8]| String::from_utf8_lossy(data).into_owned())
634 }
635}