hyperlane_plugin_multipart/
impl.rs1use super::*;
2
3impl Display for MultipartError {
5 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
15 let msg: &str = match self {
16 Self::MissingBoundary => ERR_MISSING_BOUNDARY,
17 Self::MalformedBody => ERR_MALFORMED_BODY,
18 Self::TotalTooLarge => ERR_TOTAL_TOO_LARGE,
19 Self::TooManyParts => ERR_TOO_MANY_PARTS,
20 Self::TooManyFiles => ERR_TOO_MANY_FILES,
21 Self::FileTooLarge => ERR_FILE_TOO_LARGE,
22 Self::FieldTooLarge => ERR_FIELD_TOO_LARGE,
23 Self::DisallowedMime => ERR_DISALLOWED_MIME,
24 };
25 f.write_str(msg)
26 }
27}
28
29impl Error for MultipartError {}
31
32impl ParsedMultipart {
34 #[inline]
44 pub fn from_context(ctx: &Context) -> Option<Self> {
45 ctx.try_get_attribute::<Self, _>(ATTR_PARSED_MULTIPART)
46 }
47
48 pub fn field(&self, name: &str) -> Option<&str> {
58 self.get_fields()
59 .iter()
60 .find(|(k, _): &&(String, String)| k.as_str() == name)
61 .map(|(_, v): &(String, String)| v.as_str())
62 }
63
64 pub fn file(&self, field_name: &str) -> Option<&UploadedFile> {
74 self.get_files()
75 .iter()
76 .find(|f: &&UploadedFile| f.get_field_name().as_str() == field_name)
77 }
78}
79
80impl Default for MultipartConfig {
82 fn default() -> Self {
88 Self {
89 max_total_bytes: DEFAULT_MAX_TOTAL_BYTES,
90 max_parts: DEFAULT_MAX_PARTS,
91 max_files: DEFAULT_MAX_FILES,
92 max_file_bytes: DEFAULT_MAX_FILE_BYTES,
93 max_field_bytes: DEFAULT_MAX_FIELD_BYTES,
94 allowed_mime_prefixes: Vec::new(),
95 sniff_mime: true,
96 }
97 }
98}
99
100impl MultipartConfig {
102 pub fn with_max_total_bytes(mut self, bytes: usize) -> Self {
112 self.set_max_total_bytes(bytes);
113 self
114 }
115
116 pub fn with_max_file_bytes(mut self, bytes: usize) -> Self {
126 self.set_max_file_bytes(bytes);
127 self
128 }
129
130 pub fn with_max_files(mut self, files: usize) -> Self {
140 self.set_max_files(files);
141 self
142 }
143
144 pub fn with_allowed_mime_prefixes<I, S>(mut self, prefixes: I) -> Self
154 where
155 I: IntoIterator<Item = S>,
156 S: Into<String>,
157 {
158 self.set_allowed_mime_prefixes(prefixes.into_iter().map(Into::into).collect());
159 self
160 }
161}
162
163impl MultipartPlugin {
165 pub fn new(config: MultipartConfig) -> Self {
175 let allowed_mime_lower: Box<[String]> = config
176 .get_allowed_mime_prefixes()
177 .iter()
178 .map(|m: &String| m.trim().to_ascii_lowercase())
179 .filter(|m: &String| !m.is_empty())
180 .collect::<Vec<String>>()
181 .into_boxed_slice();
182 let bad_request_wire: Vec<u8> =
183 build_error_wire(HttpStatus::BadRequest, DEFAULT_BAD_MULTIPART_BODY);
184 let too_large_wire: Vec<u8> =
185 build_error_wire(HttpStatus::PayloadTooLarge, DEFAULT_TOO_LARGE_BODY);
186 let disallowed_mime_wire: Vec<u8> = build_error_wire(
187 HttpStatus::UnsupportedMediaType,
188 DEFAULT_DISALLOWED_MIME_BODY,
189 );
190 Self {
191 config,
192 allowed_mime_lower,
193 bad_request_wire,
194 too_large_wire,
195 disallowed_mime_wire,
196 }
197 }
198
199 pub fn init(config: MultipartConfig) -> &'static Self {
209 MULTIPART_PLUGIN.get_or_init(|| Self::new(config))
210 }
211
212 #[inline(always)]
218 pub fn get() -> Option<&'static Self> {
219 MULTIPART_PLUGIN.get()
220 }
221
222 #[inline]
232 fn is_mime_allowed(&self, mime: &str) -> bool {
233 let Self {
234 allowed_mime_lower, ..
235 } = self;
236 if allowed_mime_lower.is_empty() {
237 return true;
238 }
239 allowed_mime_lower.iter().any(|prefix: &String| {
240 mime.len() >= prefix.len()
241 && mime.as_bytes()[..prefix.len()].eq_ignore_ascii_case(prefix.as_bytes())
242 })
243 }
244
245 pub fn parse_request(&self, request: &Request) -> Result<ParsedMultipart, MultipartError> {
255 let ct: &str = request
256 .get_headers()
257 .get(CONTENT_TYPE)
258 .and_then(|vals: &VecDeque<String>| vals.back())
259 .map(String::as_str)
260 .ok_or(MultipartError::MissingBoundary)?;
261 self.parse_bytes(ct, request.get_body())
262 }
263
264 pub fn parse_bytes(
275 &self,
276 content_type: &str,
277 body: &[u8],
278 ) -> Result<ParsedMultipart, MultipartError> {
279 let Self { config, .. } = self;
280 if config.get_max_total_bytes() > 0 && body.len() > config.get_max_total_bytes() {
281 return Err(MultipartError::TotalTooLarge);
282 }
283 let boundary: &str =
284 extract_boundary(content_type).ok_or(MultipartError::MissingBoundary)?;
285 let mut delim: Vec<u8> = Vec::with_capacity(boundary.len() + 2);
286 delim.extend_from_slice(DOUBLE_DASH);
287 delim.extend_from_slice(boundary.as_bytes());
288 let first_pos: usize = find_bytes(body, &delim).ok_or(MultipartError::MalformedBody)?;
289 let mut cursor: usize = first_pos + delim.len();
290 let mut parsed: ParsedMultipart = ParsedMultipart::default();
291 let mut part_count: usize = 0;
292 loop {
293 if cursor + 2 <= body.len() && &body[cursor..cursor + 2] == DOUBLE_DASH {
294 break;
295 }
296 if cursor + 2 <= body.len() && &body[cursor..cursor + 2] == b"\r\n" {
297 cursor += 2;
298 } else if cursor < body.len() && body[cursor] == b'\n' {
299 cursor += 1;
300 } else {
301 return Err(MultipartError::MalformedBody);
302 }
303 part_count += 1;
304 if config.get_max_parts() > 0 && part_count > config.get_max_parts() {
305 return Err(MultipartError::TooManyParts);
306 }
307 let remaining: &[u8] = &body[cursor..];
308 let next_rel: usize =
309 find_bytes(remaining, &delim).ok_or(MultipartError::MalformedBody)?;
310 let mut part_slice: &[u8] = &remaining[..next_rel];
311 if part_slice.ends_with(b"\r\n") {
312 part_slice = &part_slice[..part_slice.len() - 2];
313 } else if part_slice.ends_with(b"\n") {
314 part_slice = &part_slice[..part_slice.len() - 1];
315 }
316 let header_end: usize =
317 find_bytes(part_slice, CRLF_CRLF).ok_or(MultipartError::MalformedBody)?;
318 let head_str: &str =
319 from_utf8(&part_slice[..header_end]).map_err(|_| MultipartError::MalformedBody)?;
320 let payload: &[u8] = &part_slice[header_end + CRLF_CRLF.len()..];
321 let mut field_name: String = String::new();
322 let mut raw_filename: Option<String> = None;
323 let mut declared_ct: Option<String> = None;
324 for line in head_str.split("\r\n") {
325 if let Some((k, v)) = line.split_once(':') {
326 let key_trim: &str = k.trim();
327 let val_trim: &str = v.trim();
328 if key_trim.eq_ignore_ascii_case(HEADER_CONTENT_DISPOSITION) {
329 let (n, f): (String, Option<String>) = parse_content_disposition(val_trim);
330 field_name = n;
331 raw_filename = f;
332 } else if key_trim.eq_ignore_ascii_case(HEADER_CONTENT_TYPE_LOWER) {
333 declared_ct = Some(val_trim.to_owned());
334 }
335 }
336 }
337 if field_name.is_empty() {
338 return Err(MultipartError::MalformedBody);
339 }
340 if let Some(fname) = raw_filename {
341 if config.get_max_files() > 0 && parsed.files.len() >= config.get_max_files() {
342 return Err(MultipartError::TooManyFiles);
343 }
344 if config.get_max_file_bytes() > 0 && payload.len() > config.get_max_file_bytes() {
345 return Err(MultipartError::FileTooLarge);
346 }
347 let effective_mime: String = if config.get_sniff_mime()
348 && let Some(sniffed) = sniff_magic_mime(payload)
349 {
350 sniffed.to_owned()
351 } else {
352 declared_ct.unwrap_or_else(|| MIME_OCTET_STREAM.to_owned())
353 };
354 if !self.is_mime_allowed(&effective_mime) {
355 return Err(MultipartError::DisallowedMime);
356 }
357 parsed.files.push(UploadedFile {
358 field_name,
359 filename: sanitize_filename(&fname),
360 content_type: effective_mime,
361 data: payload.to_vec(),
362 });
363 } else {
364 if config.get_max_field_bytes() > 0 && payload.len() > config.get_max_field_bytes()
365 {
366 return Err(MultipartError::FieldTooLarge);
367 }
368 let text: String = from_utf8(payload)
369 .map_err(|_| MultipartError::MalformedBody)?
370 .to_owned();
371 parsed.fields.push((field_name, text));
372 }
373 cursor += next_rel + delim.len();
374 }
375 Ok(parsed)
376 }
377}
378
379impl ServerHook for MultipartHook {
381 #[inline(always)]
392 async fn new(_: &mut Stream, _: &mut Context) -> Self {
393 Self
394 }
395
396 #[inline(always)]
408 async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
409 let Some(plugin) = MultipartPlugin::get() else {
410 return Status::Continue;
411 };
412 let is_multipart: bool = ctx
413 .get_request()
414 .get_headers()
415 .get(CONTENT_TYPE)
416 .and_then(|vals: &VecDeque<String>| vals.back())
417 .is_some_and(|ct: &String| {
418 let t: &str = ct.trim();
419 t.len() >= MULTIPART_FORM_DATA_PREFIX.len()
420 && t.as_bytes()[..MULTIPART_FORM_DATA_PREFIX.len()]
421 .eq_ignore_ascii_case(MULTIPART_FORM_DATA_PREFIX.as_bytes())
422 });
423 if !is_multipart {
424 return Status::Continue;
425 }
426 match plugin.parse_request(ctx.get_request()) {
427 Ok(form) => {
428 ctx.set_attribute(ATTR_PARSED_MULTIPART, form);
429 Status::Continue
430 }
431 Err(
432 MultipartError::TotalTooLarge
433 | MultipartError::TooManyParts
434 | MultipartError::TooManyFiles
435 | MultipartError::FileTooLarge
436 | MultipartError::FieldTooLarge,
437 ) => {
438 let MultipartPlugin { too_large_wire, .. } = plugin;
439 let _: Result<(), ResponseError> = stream.try_send(too_large_wire).await;
440 Status::Reject
441 }
442 Err(MultipartError::DisallowedMime) => {
443 let MultipartPlugin {
444 disallowed_mime_wire,
445 ..
446 } = plugin;
447 let _: Result<(), ResponseError> = stream.try_send(disallowed_mime_wire).await;
448 Status::Reject
449 }
450 Err(MultipartError::MissingBoundary | MultipartError::MalformedBody) => {
451 let MultipartPlugin {
452 bad_request_wire, ..
453 } = plugin;
454 let _: Result<(), ResponseError> = stream.try_send(bad_request_wire).await;
455 Status::Reject
456 }
457 }
458 }
459}