1use std::future::{Future, poll_fn, ready};
3use std::{borrow::Cow, convert::Infallible, fmt, mem, pin::Pin, str, sync::Arc};
4use std::{task::Context, task::Poll, task::ready};
5
6use encoding_rs::UTF_8;
7use mime::Mime;
8
9use crate::http::{HttpMessage, error, header};
10use crate::util::{Bytes, Stream};
11use crate::web::{FromRequest, HttpRequest, State, error::PayloadError};
12
13#[derive(Debug)]
48pub struct Payload(pub crate::http::Payload);
49
50impl Payload {
51 #[inline]
52 pub fn into_inner(self) -> crate::http::Payload {
54 self.0
55 }
56
57 #[inline]
58 pub async fn recv(&mut self) -> Option<Result<Bytes, error::PayloadError>> {
60 self.0.recv().await
61 }
62
63 #[inline]
64 pub fn poll_recv(
68 &mut self,
69 cx: &mut Context<'_>,
70 ) -> Poll<Option<Result<Bytes, error::PayloadError>>> {
71 self.0.poll_recv(cx)
72 }
73}
74
75impl Stream for Payload {
76 type Item = Result<Bytes, error::PayloadError>;
77
78 #[inline]
79 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
80 self.poll_recv(cx)
81 }
82}
83
84impl<St: State> FromRequest<St> for Payload {
113 type Error = Infallible;
114
115 #[inline]
116 fn from_request(
117 _: &St,
118 _: &HttpRequest,
119 payload: &mut crate::http::Payload,
120 ) -> impl Future<Output = Result<Payload, Self::Error>> {
121 ready(Ok(Payload(payload.take())))
122 }
123}
124
125impl<St: State> FromRequest<St> for Bytes {
150 type Error = PayloadError;
151
152 fn from_request(
154 _: &St,
155 req: &HttpRequest,
156 payload: &mut crate::http::Payload,
157 ) -> impl Future<Output = Result<Bytes, Self::Error>> {
158 let tmp;
159 let cfg = if let Some(cfg) = req.app_value::<PayloadConfig>() {
160 cfg
161 } else {
162 tmp = PayloadConfig::default();
163 &tmp
164 };
165
166 match cfg.check_mimetype(req) {
167 Ok(()) => HttpMessageBody::new(req, payload).limit(cfg.limit),
168 Err(e) => HttpMessageBody::err(e),
169 }
170 }
171}
172
173impl<St: State> FromRequest<St> for String {
203 type Error = PayloadError;
204
205 fn from_request(
207 _: &St,
208 req: &HttpRequest,
209 payload: &mut crate::http::Payload,
210 ) -> impl Future<Output = Result<String, Self::Error>> {
211 let tmp;
212 let cfg = if let Some(cfg) = req.app_value::<PayloadConfig>() {
213 cfg
214 } else {
215 tmp = PayloadConfig::default();
216 &tmp
217 };
218
219 let checked = cfg
221 .check_mimetype(req)
222 .and_then(|()| req.encoding().map_err(PayloadError::from));
223 let (mut body, encoding) = match checked {
224 Ok(enc) => (HttpMessageBody::new(req, payload).limit(cfg.limit), enc),
225 Err(e) => (HttpMessageBody::err(e), UTF_8),
226 };
227
228 poll_fn(move |cx| {
229 let body = ready!(Pin::new(&mut body).poll(cx))?;
230 Poll::Ready(if encoding == UTF_8 {
231 str::from_utf8(body.as_ref())
232 .map(str::to_owned)
233 .map_err(|_| PayloadError::Decoding)
234 } else {
235 encoding
236 .decode_without_bom_handling_and_without_replacement(&body)
237 .map(Cow::into_owned)
238 .ok_or(PayloadError::Decoding)
239 })
240 })
241 }
242}
243
244#[derive(Clone)]
251pub struct PayloadConfig {
252 limit: usize,
253 content_type: Option<Arc<dyn Fn(Mime) -> bool + Send + Sync>>,
254}
255
256impl PayloadConfig {
257 #[must_use]
258 pub fn new(limit: usize) -> Self {
260 PayloadConfig {
261 limit,
262 ..Default::default()
263 }
264 }
265
266 #[must_use]
267 pub fn limit(mut self, limit: usize) -> Self {
271 self.limit = limit;
272 self
273 }
274
275 #[must_use]
276 pub fn content_type<F>(mut self, predicate: F) -> Self
282 where
283 F: Fn(Mime) -> bool + Send + Sync + 'static,
284 {
285 self.content_type = Some(Arc::new(predicate));
286 self
287 }
288
289 #[must_use]
290 pub fn mimetype(self, mt: Mime) -> Self {
296 self.content_type(move |req_mt| req_mt == mt)
297 }
298
299 fn check_mimetype(&self, req: &HttpRequest) -> Result<(), PayloadError> {
300 if let Some(ref predicate) = self.content_type {
302 match req.mime_type() {
303 Ok(Some(req_mt)) => {
304 if !predicate(req_mt) {
305 return Err(PayloadError::from(error::ContentTypeError::Unexpected));
306 }
307 }
308 Ok(None) => {
309 return Err(PayloadError::from(error::ContentTypeError::Expected));
310 }
311 Err(err) => {
312 return Err(err.into());
313 }
314 }
315 }
316 Ok(())
317 }
318}
319
320impl Default for PayloadConfig {
321 fn default() -> Self {
322 PayloadConfig {
323 limit: 262_144,
324 content_type: None,
325 }
326 }
327}
328
329impl fmt::Debug for PayloadConfig {
330 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
331 f.debug_struct("PayloadConfig")
332 .field("limit", &self.limit)
333 .field(
334 "content_type",
335 &self
336 .content_type
337 .as_ref()
338 .map(|_| "Arc<dyn Fn(mime::Mime) -> bool + Send + Sync>"),
339 )
340 .finish()
341 }
342}
343
344enum HttpMessageBody {
352 Body(super::ReadBody<super::BodyStream>),
353 Err(PayloadError),
354 Done,
355}
356
357impl HttpMessageBody {
358 fn new(req: &HttpRequest, payload: &mut crate::http::Payload) -> HttpMessageBody {
360 let mut len = None;
361 if let Some(l) = req.headers().get(&header::CONTENT_LENGTH) {
362 if let Ok(s) = l.to_str() {
363 if let Ok(l) = s.parse::<usize>() {
364 len = Some(l);
365 } else {
366 return Self::err(PayloadError::Payload(error::PayloadError::UnknownLength));
367 }
368 } else {
369 return Self::err(PayloadError::Payload(error::PayloadError::UnknownLength));
370 }
371 }
372
373 HttpMessageBody::Body(super::ReadBody::from_request(req, payload, 262_144).length(len))
374 }
375
376 fn limit(mut self, limit: usize) -> Self {
378 if let HttpMessageBody::Body(body) = &mut self {
379 body.limit = limit;
380 }
381 self
382 }
383
384 fn err(e: PayloadError) -> Self {
385 HttpMessageBody::Err(e)
386 }
387}
388
389impl Future for HttpMessageBody {
390 type Output = Result<Bytes, PayloadError>;
391
392 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
393 let this = self.get_mut();
394 let body = match this {
395 HttpMessageBody::Body(body) => body,
396 HttpMessageBody::Err(_) => {
397 let HttpMessageBody::Err(err) = mem::replace(this, HttpMessageBody::Done) else {
398 unreachable!()
399 };
400 return Poll::Ready(Err(err));
401 }
402 HttpMessageBody::Done => panic!("polled after completion"),
403 };
404 if let Some(len) = body.length
405 && len > body.limit
406 {
407 return Poll::Ready(Err(PayloadError::from(error::PayloadError::Overflow)));
408 }
409 Pin::new(body).poll(cx).map_err(|err| match err {
410 super::ReadBodyError::Overflow(_) => PayloadError::from(error::PayloadError::Overflow),
411 super::ReadBodyError::Payload(err) => PayloadError::from(err),
412 })
413 }
414}
415
416#[cfg(test)]
417mod tests {
418 use super::*;
419 use crate::web::test::{TestRequest, from_request};
420
421 #[crate::rt_test]
428 async fn test_payload_config() {
429 let req = TestRequest::default().to_http_request();
430 let cfg = PayloadConfig::default()
431 .limit(5)
432 .mimetype(mime::APPLICATION_JSON);
433 assert!(cfg.check_mimetype(&req).is_err());
434
435 let req =
436 TestRequest::with_header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
437 .to_http_request();
438 assert!(cfg.check_mimetype(&req).is_err());
439
440 let req =
441 TestRequest::with_header(header::CONTENT_TYPE, "application/json").to_http_request();
442 assert!(cfg.check_mimetype(&req).is_ok());
443
444 let cfg = PayloadConfig::default()
445 .content_type(|mt| mt.type_() == mime::TEXT && mt.subtype() == mime::PLAIN);
446 let req =
447 TestRequest::with_header(header::CONTENT_TYPE, "application/json").to_http_request();
448 assert!(cfg.check_mimetype(&req).is_err());
449
450 let req = TestRequest::with_header(header::CONTENT_TYPE, "text/plain; charset=utf-8")
451 .to_http_request();
452 assert!(cfg.check_mimetype(&req).is_ok());
453 assert!(format!("{cfg:?}").contains("PayloadConfig"));
454 }
455
456 #[crate::rt_test]
463 async fn test_payload_overflow_status() {
464 use crate::web::{DefaultError, WebResponseError};
465
466 fn status(err: &PayloadError) -> crate::http::StatusCode {
467 WebResponseError::<(), DefaultError>::error_response(err, &()).status()
468 }
469
470 for declared in [true, false] {
471 let mut req = TestRequest::default()
472 .app_value(PayloadConfig::new(5))
473 .payload(Bytes::from_static(b"hello=world"));
474 if declared {
475 req = req.header(header::CONTENT_LENGTH, "11");
476 }
477 let (req, mut pl, ()) = req.to_http_parts();
478 let err = from_request::<_, Bytes>(&(), &req, &mut pl)
479 .await
480 .unwrap_err();
481 assert_eq!(status(&err), crate::http::StatusCode::PAYLOAD_TOO_LARGE);
482
483 let mut req = TestRequest::default()
484 .app_value(PayloadConfig::new(5))
485 .payload(Bytes::from_static(b"hello=world"));
486 if declared {
487 req = req.header(header::CONTENT_LENGTH, "11");
488 }
489 let (req, mut pl, ()) = req.to_http_parts();
490 let err = from_request::<_, String>(&(), &req, &mut pl)
491 .await
492 .unwrap_err();
493 assert_eq!(status(&err), crate::http::StatusCode::PAYLOAD_TOO_LARGE);
494 }
495
496 let (req, mut pl, ()) = TestRequest::default()
497 .app_value(PayloadConfig::default().mimetype(mime::APPLICATION_JSON))
498 .payload(Bytes::from_static(b"hello=world"))
499 .to_http_parts();
500 let err = from_request::<_, Bytes>(&(), &req, &mut pl)
501 .await
502 .unwrap_err();
503 assert_eq!(status(&err), crate::http::StatusCode::BAD_REQUEST);
504 }
505
506 #[crate::rt_test]
512 async fn test_payload() {
513 let (req, mut pl, ()) = TestRequest::with_header(header::CONTENT_LENGTH, "11")
514 .payload(Bytes::from_static(b"hello=world"))
515 .to_http_parts();
516
517 let mut s = from_request::<_, Payload>(&(), &req, &mut pl)
518 .await
519 .unwrap();
520 let b = crate::util::stream_recv(&mut s).await.unwrap().unwrap();
521 assert_eq!(b, Bytes::from_static(b"hello=world"));
522 }
523
524 #[crate::rt_test]
530 async fn test_payload_recv() {
531 let (req, mut pl, ()) = TestRequest::with_header(header::CONTENT_LENGTH, "11")
532 .payload(Bytes::from_static(b"hello=world"))
533 .to_http_parts();
534
535 let mut s = from_request::<_, Payload>(&(), &req, &mut pl)
536 .await
537 .unwrap();
538 let b = s.recv().await.unwrap().unwrap();
539 assert_eq!(b, Bytes::from_static(b"hello=world"));
540 }
541
542 #[crate::rt_test]
548 async fn test_bytes() {
549 let (req, mut pl, ()) = TestRequest::with_header(header::CONTENT_LENGTH, "11")
550 .payload(Bytes::from_static(b"hello=world"))
551 .to_http_parts();
552
553 let s = from_request::<_, Bytes>(&(), &req, &mut pl).await.unwrap();
554 assert_eq!(s, Bytes::from_static(b"hello=world"));
555
556 let (req, mut pl, ()) = TestRequest::with_header(header::CONTENT_LENGTH, "11")
557 .payload(Bytes::from_static(b"hello=world"))
558 .app_value(PayloadConfig::default().mimetype(mime::APPLICATION_JSON))
559 .to_http_parts();
560 assert!(from_request::<_, Bytes>(&(), &req, &mut pl).await.is_err());
561 }
562
563 #[crate::rt_test]
569 async fn test_string() {
570 let (req, mut pl, ()) = TestRequest::with_header(header::CONTENT_LENGTH, "11")
571 .payload(Bytes::from_static(b"hello=world"))
572 .to_http_parts();
573
574 let s = from_request::<_, String>(&(), &req, &mut pl).await.unwrap();
575 assert_eq!(s, "hello=world");
576
577 let (req, mut pl, ()) = TestRequest::with_header(header::CONTENT_LENGTH, "11")
578 .header(header::CONTENT_TYPE, "text/plain; charset=cp1251")
579 .payload(Bytes::from_static(b"hello=world"))
580 .to_http_parts();
581 let s = from_request::<_, String>(&(), &req, &mut pl).await.unwrap();
582 assert_eq!(s, "hello=world");
583
584 let (req, mut pl, ()) = TestRequest::with_header(header::CONTENT_LENGTH, "11")
585 .payload(Bytes::from_static(b"hello=world"))
586 .app_value(PayloadConfig::default().mimetype(mime::APPLICATION_JSON))
587 .to_http_parts();
588 assert!(from_request::<_, String>(&(), &req, &mut pl).await.is_err());
589 }
590
591 #[crate::rt_test]
598 async fn test_message_body() {
599 let (req, mut pl, ()) = TestRequest::with_header(header::CONTENT_LENGTH, "xxxx")
600 .to_srv_request()
601 .into_parts();
602 let res = HttpMessageBody::new(&req, &mut pl).await;
603 match res.err().unwrap() {
604 PayloadError::Payload(error::PayloadError::UnknownLength) => (),
605 _ => unreachable!("error"),
606 }
607
608 let (req, mut pl, ()) = TestRequest::with_header(header::CONTENT_LENGTH, "1000000")
609 .to_srv_request()
610 .into_parts();
611 let res = HttpMessageBody::new(&req, &mut pl).await;
612 match res.err().unwrap() {
613 PayloadError::Payload(error::PayloadError::Overflow) => (),
614 _ => unreachable!("error"),
615 }
616
617 let (req, mut pl, ()) = TestRequest::default()
618 .payload(Bytes::from_static(b"test"))
619 .to_http_parts();
620 let res = HttpMessageBody::new(&req, &mut pl).await;
621 assert_eq!(res.ok().unwrap(), Bytes::from_static(b"test"));
622
623 let (req, mut pl, ()) = TestRequest::default()
624 .payload(Bytes::from_static(b"11111111111111"))
625 .to_http_parts();
626 let res = HttpMessageBody::new(&req, &mut pl).limit(5).await;
627 match res.err().unwrap() {
628 PayloadError::Payload(error::PayloadError::Overflow) => (),
629 _ => unreachable!("error"),
630 }
631 }
632
633 #[crate::rt_test]
640 async fn test_payload_errors() {
641 let cfg = PayloadConfig::new(5);
642 assert_eq!(cfg.limit, 5);
643
644 let (req, mut pl, ()) = TestRequest::with_header(header::CONTENT_LENGTH, "11")
646 .header(header::CONTENT_TYPE, "text/plain; charset=unknown")
647 .payload(Bytes::from_static(b"hello=world"))
648 .to_http_parts();
649 assert!(from_request::<_, String>(&(), &req, &mut pl).await.is_err());
650
651 let cfg = PayloadConfig::default().mimetype(mime::APPLICATION_JSON);
653 let req = TestRequest::with_header(header::CONTENT_TYPE, "invalid").to_http_request();
654 assert!(matches!(
655 cfg.check_mimetype(&req),
656 Err(PayloadError::ContentType(_))
657 ));
658
659 let (req, mut pl, ()) = TestRequest::with_header(
661 header::CONTENT_LENGTH,
662 header::HeaderValue::from_bytes(b"1\xff").unwrap(),
663 )
664 .to_http_parts();
665 let res = HttpMessageBody::new(&req, &mut pl).await;
666 assert!(matches!(
667 res,
668 Err(PayloadError::Payload(error::PayloadError::UnknownLength))
669 ));
670 }
671}