1use std::task::{Context, Poll, ready};
3use std::{borrow::Cow, fmt, future::Future, future::poll_fn, marker::PhantomData, mem, ops};
4use std::{pin::Pin, str};
5
6use encoding_rs::{Encoding, UTF_8};
7use serde::{Serialize, de::DeserializeOwned};
8
9use crate::http::header::{CONTENT_LENGTH, CONTENT_TYPE};
10use crate::http::{HttpMessage, Payload, Response, StatusCode};
11use crate::web::error::{UrlencodedError, WebResponseError};
12use crate::web::{FromRequest, HttpRequest, Responder, State};
13
14#[derive(PartialEq, Eq, PartialOrd, Ord)]
80pub struct Form<T>(pub T);
81
82impl<T> Form<T> {
83 pub fn into_inner(self) -> T {
85 self.0
86 }
87}
88
89impl<T> ops::Deref for Form<T> {
90 type Target = T;
91
92 fn deref(&self) -> &T {
93 &self.0
94 }
95}
96
97impl<T> ops::DerefMut for Form<T> {
98 fn deref_mut(&mut self) -> &mut T {
99 &mut self.0
100 }
101}
102
103impl<St, T> FromRequest<St> for Form<T>
104where
105 St: State,
106 T: DeserializeOwned + 'static,
107{
108 type Error = UrlencodedError;
109
110 fn from_request(
112 _: &St,
113 req: &HttpRequest,
114 payload: &mut Payload,
115 ) -> impl Future<Output = Result<Self, Self::Error>> {
116 let limit = req.app_value::<FormConfig>().map_or(16384, |c| c.limit);
117
118 let mut body = UrlEncoded::new(req, payload).limit(limit);
119 poll_fn(move |cx| Pin::new(&mut body).poll(cx).map_ok(Form))
120 }
121}
122
123impl<T: fmt::Debug> fmt::Debug for Form<T> {
124 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
125 f.debug_tuple("Form").field(&self.0).finish()
126 }
127}
128
129impl<T: fmt::Display> fmt::Display for Form<T> {
130 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
131 self.0.fmt(f)
132 }
133}
134
135impl<St, T: Serialize> Responder<St> for Form<T>
136where
137 St: State,
138 serde_urlencoded::ser::Error: WebResponseError<St, St::Error>,
139{
140 async fn respond_to(self, st: &St, _: &HttpRequest) -> Response {
141 let body = match serde_urlencoded::to_string(&self.0) {
142 Ok(body) => body,
143 Err(e) => return e.error_response(st),
144 };
145
146 Response::builder(StatusCode::OK)
147 .header(CONTENT_TYPE, "application/x-www-form-urlencoded")
148 .body(body)
149 }
150}
151
152#[derive(Clone, Debug)]
185pub struct FormConfig {
186 limit: usize,
187}
188
189impl FormConfig {
190 #[must_use]
191 pub fn limit(mut self, limit: usize) -> Self {
195 self.limit = limit;
196 self
197 }
198}
199
200impl Default for FormConfig {
201 fn default() -> Self {
202 FormConfig { limit: 16384 }
203 }
204}
205
206enum UrlEncoded<U> {
219 Body(
220 super::ReadBody<super::BodyStream>,
221 &'static Encoding,
222 PhantomData<fn() -> U>,
223 ),
224 Err(UrlencodedError),
225 Done,
226}
227
228impl<U> UrlEncoded<U> {
229 fn new(req: &HttpRequest, payload: &mut Payload) -> UrlEncoded<U> {
231 if !req
233 .content_type()
234 .eq_ignore_ascii_case("application/x-www-form-urlencoded")
235 {
236 return Self::err(UrlencodedError::ContentType);
237 }
238 let Ok(encoding) = req.encoding() else {
239 return Self::err(UrlencodedError::ContentType);
240 };
241
242 let mut len = None;
243 if let Some(l) = req.headers().get(&CONTENT_LENGTH) {
244 if let Ok(s) = l.to_str() {
245 if let Ok(l) = s.parse::<usize>() {
246 len = Some(l);
247 } else {
248 return Self::err(UrlencodedError::UnknownLength);
249 }
250 } else {
251 return Self::err(UrlencodedError::UnknownLength);
252 }
253 }
254
255 UrlEncoded::Body(
256 super::ReadBody::from_request(req, payload, 32_768).length(len),
257 encoding,
258 PhantomData,
259 )
260 }
261
262 fn err(e: UrlencodedError) -> Self {
263 UrlEncoded::Err(e)
264 }
265
266 fn limit(mut self, limit: usize) -> Self {
268 if let UrlEncoded::Body(body, _, _) = &mut self {
269 body.limit = limit;
270 }
271 self
272 }
273}
274
275impl<U> Future for UrlEncoded<U>
276where
277 U: DeserializeOwned + 'static,
278{
279 type Output = Result<U, UrlencodedError>;
280
281 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
282 let this = self.get_mut();
283 let (body, encoding) = match this {
284 UrlEncoded::Body(body, encoding, _) => (body, *encoding),
285 UrlEncoded::Err(_) => {
286 let UrlEncoded::Err(err) = mem::replace(this, UrlEncoded::Done) else {
287 unreachable!()
288 };
289 return Poll::Ready(Err(err));
290 }
291 UrlEncoded::Done => panic!("polled after completion"),
292 };
293
294 let limit = body.limit;
296 if let Some(len) = body.length
297 && len > limit
298 {
299 return Poll::Ready(Err(UrlencodedError::Overflow { size: len, limit }));
300 }
301
302 let body = match ready!(Pin::new(body).poll(cx)) {
303 Ok(body) => body,
304 Err(super::ReadBodyError::Overflow(size)) => {
305 return Poll::Ready(Err(UrlencodedError::Overflow { size, limit }));
306 }
307 Err(super::ReadBodyError::Payload(err)) => {
308 return Poll::Ready(Err(UrlencodedError::Payload(err)));
309 }
310 };
311
312 Poll::Ready(
313 to_utf8_form(&body, encoding)
314 .ok_or(UrlencodedError::Parse)
315 .and_then(|body| {
316 serde_urlencoded::from_bytes::<U>(&body).map_err(|_| UrlencodedError::Parse)
317 }),
318 )
319 }
320}
321
322fn to_utf8_form<'a>(body: &'a [u8], encoding: &'static Encoding) -> Option<Cow<'a, [u8]>> {
328 let (body, encoding): (Cow<'a, [u8]>, _) = if encoding.is_ascii_compatible() {
329 (Cow::Borrowed(body), encoding)
330 } else {
331 let text = encoding.decode_without_bom_handling_and_without_replacement(body)?;
333 (Cow::Owned(text.into_owned().into_bytes()), UTF_8)
334 };
335
336 if encoding == UTF_8 {
337 str::from_utf8(&percent_decode(&body)).ok()?;
339 return Some(body);
340 }
341
342 let decode = |part: &[u8]| {
343 encoding
344 .decode_without_bom_handling_and_without_replacement(&percent_decode(part))
345 .map(Cow::into_owned)
346 };
347 let mut fields = Vec::new();
348 for field in body.split(|b| *b == b'&').filter(|f| !f.is_empty()) {
349 let (name, value) = match field.iter().position(|b| *b == b'=') {
350 Some(pos) => (&field[..pos], &field[pos + 1..]),
351 None => (field, &b""[..]),
352 };
353 fields.push((decode(name)?, decode(value)?));
354 }
355 serde_urlencoded::to_string(fields)
356 .ok()
357 .map(|body| Cow::Owned(body.into_bytes()))
358}
359
360fn percent_decode(input: &[u8]) -> Vec<u8> {
362 fn hex(b: u8) -> Option<u8> {
363 char::from(b)
364 .to_digit(16)
365 .and_then(|d| u8::try_from(d).ok())
366 }
367
368 let mut out = Vec::with_capacity(input.len());
369 let mut i = 0;
370 while i < input.len() {
371 match input[i] {
372 b'+' => out.push(b' '),
373 b'%' if let (Some(hi), Some(lo)) = (
374 input.get(i + 1).copied().and_then(hex),
375 input.get(i + 2).copied().and_then(hex),
376 ) =>
377 {
378 out.push(hi << 4 | lo);
379 i += 2;
380 }
381 b => out.push(b),
382 }
383 i += 1;
384 }
385 out
386}
387
388#[cfg(test)]
389mod tests {
390 use serde::{Deserialize, Serialize};
391
392 use super::*;
393 use crate::http::header::HeaderValue;
394 use crate::util::Bytes;
395 use crate::web::test::{TestRequest, from_request, respond_to};
396
397 #[derive(Deserialize, Serialize, Debug, PartialEq, thiserror::Error)]
398 #[error("Info({hello})")]
399 struct Info {
400 hello: String,
401 counter: i64,
402 }
403
404 fn eq(err: &UrlencodedError, other: &UrlencodedError) -> bool {
405 if let UrlencodedError::Overflow { .. } = err
406 && let UrlencodedError::Overflow { .. } = other
407 {
408 return true;
409 } else if let UrlencodedError::UnknownLength = err
410 && let UrlencodedError::UnknownLength = other
411 {
412 return true;
413 } else if let UrlencodedError::ContentType = err
414 && let UrlencodedError::ContentType = other
415 {
416 return true;
417 }
418 false
419 }
420
421 #[test]
427 fn test_basic() {
428 let mut f = Form(Info {
429 hello: "world".into(),
430 counter: 123,
431 });
432 assert_eq!(f.hello, "world");
433 f.hello = "test".to_string();
434 assert_eq!(f.hello, "test");
435 assert!(format!("{f:?}").contains("Form"));
436 assert!(format!("{f}").contains("test"));
437 }
438
439 #[crate::rt_test]
445 async fn test_form() {
446 let (req, mut pl, ()) =
447 TestRequest::with_header(CONTENT_TYPE, "application/x-www-form-urlencoded")
448 .header(CONTENT_LENGTH, "11")
449 .payload(Bytes::from_static(b"hello=world&counter=123"))
450 .to_http_parts();
451
452 let Form(s) = from_request::<_, Form<Info>>(&(), &req, &mut pl)
453 .await
454 .unwrap();
455 assert_eq!(
456 s,
457 Info {
458 hello: "world".into(),
459 counter: 123
460 }
461 );
462
463 let (req, mut pl, ()) =
464 TestRequest::with_header(CONTENT_TYPE, "application/x-www-form-urlencoded")
465 .header(CONTENT_LENGTH, "xx")
466 .payload(Bytes::from_static(b"hello=world&counter=123"))
467 .to_http_parts();
468 let res = from_request::<_, Form<Info>>(&(), &req, &mut pl).await;
469 assert!(eq(&res.err().unwrap(), &UrlencodedError::UnknownLength));
470 }
471
472 #[crate::rt_test]
478 async fn test_urlencoded_error() {
479 let (req, mut pl, ()) =
480 TestRequest::with_header(CONTENT_TYPE, "application/x-www-form-urlencoded")
481 .header(CONTENT_LENGTH, "xxxx")
482 .to_http_parts();
483 let info = UrlEncoded::<Info>::new(&req, &mut pl).await;
484 assert!(eq(&info.err().unwrap(), &UrlencodedError::UnknownLength));
485
486 let (req, mut pl, ()) =
487 TestRequest::with_header(CONTENT_TYPE, "application/x-www-form-urlencoded")
488 .header(CONTENT_LENGTH, "1000000")
489 .to_http_parts();
490 let info = UrlEncoded::<Info>::new(&req, &mut pl).await;
491 assert!(eq(
492 &info.err().unwrap(),
493 &UrlencodedError::Overflow { size: 0, limit: 0 }
494 ));
495
496 let (req, mut pl, ()) = TestRequest::with_header(CONTENT_TYPE, "text/plain")
497 .header(CONTENT_LENGTH, "10")
498 .to_http_parts();
499 let info = UrlEncoded::<Info>::new(&req, &mut pl).await;
500 assert!(eq(&info.err().unwrap(), &UrlencodedError::ContentType));
501 }
502
503 #[crate::rt_test]
509 async fn test_urlencoded() {
510 let (req, mut pl, ()) =
511 TestRequest::with_header(CONTENT_TYPE, "application/x-www-form-urlencoded")
512 .header(CONTENT_LENGTH, "11")
513 .payload(Bytes::from_static(b"hello=world&counter=123"))
514 .to_http_parts();
515
516 let info = UrlEncoded::<Info>::new(&req, &mut pl).await.unwrap();
517 assert_eq!(
518 info,
519 Info {
520 hello: "world".to_owned(),
521 counter: 123
522 }
523 );
524
525 let (req, mut pl, ()) =
526 TestRequest::with_header(CONTENT_TYPE, "Application/X-WWW-Form-URLEncoded")
527 .header(CONTENT_LENGTH, "11")
528 .payload(Bytes::from_static(b"hello=world&counter=123"))
529 .to_http_parts();
530 assert!(UrlEncoded::<Info>::new(&req, &mut pl).await.is_ok());
531
532 let (req, mut pl, ()) = TestRequest::with_header(
533 CONTENT_TYPE,
534 "application/x-www-form-urlencoded; charset=utf-8",
535 )
536 .header(CONTENT_LENGTH, "11")
537 .payload(Bytes::from_static(b"hello=world&counter=123"))
538 .to_http_parts();
539
540 let info = UrlEncoded::<Info>::new(&req, &mut pl).await.unwrap();
541 assert_eq!(
542 info,
543 Info {
544 hello: "world".to_owned(),
545 counter: 123
546 }
547 );
548
549 let (req, mut pl, ()) = TestRequest::with_header(
550 CONTENT_TYPE,
551 "application/x-www-form-urlencoded; charset=cp1251",
552 )
553 .header(CONTENT_LENGTH, "11")
554 .payload(Bytes::from_static(b"hello=world&counter=123"))
555 .to_http_parts();
556
557 let info = UrlEncoded::<Info>::new(&req, &mut pl).await.unwrap();
558 assert_eq!(
559 info,
560 Info {
561 hello: "world".to_owned(),
562 counter: 123
563 }
564 );
565 }
566
567 #[crate::rt_test]
576 async fn test_urlencoded_charset() {
577 let utf16 = |s: &str| -> Vec<u8> { s.encode_utf16().flat_map(u16::to_le_bytes).collect() };
578 let cases: Vec<(&str, Vec<u8>, Option<&str>)> = vec![
579 (
580 "windows-1252",
581 b"hello=caf%E9&counter=1".to_vec(),
582 Some("caf\u{e9}"),
583 ),
584 (
585 "windows-1252",
586 b"hello=caf\xe9&counter=1".to_vec(),
587 Some("caf\u{e9}"),
588 ),
589 (
590 "windows-1252",
591 b"hello=a%26b%3Dc+d&&counter=1&".to_vec(),
592 Some("a&b=c d"),
593 ),
594 (
595 "windows-1252",
596 b"hello=100%25%zz%4&counter=1".to_vec(),
597 Some("100%%zz%4"),
598 ),
599 ("windows-1252", b"counter=1&hello".to_vec(), Some("")),
600 ("windows-1252", b"h%65llo=x&counter=1".to_vec(), Some("x")),
601 (
602 "shift_jis",
603 b"hello=%82%A0&counter=1".to_vec(),
604 Some("\u{3042}"),
605 ),
606 ("shift_jis", b"hello=%82&counter=1".to_vec(), None),
607 ("shift_jis", b"h%82=x&counter=1".to_vec(), None),
608 (
609 "utf-8",
610 b"hello=caf%C3%A9+x&counter=1".to_vec(),
611 Some("caf\u{e9} x"),
612 ),
613 ("utf-8", b"hello=caf%E9&counter=1".to_vec(), None),
614 ("utf-8", b"hello=caf\xff&counter=1".to_vec(), None),
615 (
616 "utf-16le",
617 utf16("hello=caf%C3%A9&counter=1"),
618 Some("caf\u{e9}"),
619 ),
620 ("utf-16le", utf16("hello=caf%E9&counter=1"), None),
621 ("utf-16le", b"hello=x&counter=1".to_vec(), None),
622 ];
623 for (charset, body, expected) in cases {
624 let (req, mut pl, ()) = TestRequest::with_header(
625 CONTENT_TYPE,
626 format!("application/x-www-form-urlencoded; charset={charset}"),
627 )
628 .payload(Bytes::from(body.clone()))
629 .to_http_parts();
630 let res = UrlEncoded::<Info>::new(&req, &mut pl).await;
631 match expected {
632 Some(hello) => assert_eq!(res.unwrap().hello, hello, "{charset} {body:?}"),
633 None => assert!(
634 matches!(res, Err(UrlencodedError::Parse)),
635 "{charset} {body:?}"
636 ),
637 }
638 }
639
640 let (req, mut pl, ()) = TestRequest::with_header(
642 CONTENT_TYPE,
643 "application/x-www-form-urlencoded; charset=windows-1252",
644 )
645 .payload(Bytes::from_static(b"&a=1&&b=2&"))
646 .to_http_parts();
647 let res = UrlEncoded::<std::collections::HashMap<String, String>>::new(&req, &mut pl)
648 .await
649 .unwrap();
650 assert_eq!(res.len(), 2, "{res:?}");
651
652 let (req, mut pl, ()) =
654 TestRequest::with_header(CONTENT_TYPE, "application/x-www-form-urlencoded")
655 .payload(Bytes::from_static(b"hello=caf%FF&counter=1"))
656 .to_http_parts();
657 let res = UrlEncoded::<Info>::new(&req, &mut pl).await;
658 assert!(matches!(res, Err(UrlencodedError::Parse)));
659 }
660
661 #[crate::rt_test]
667 async fn test_responder() {
668 let req = TestRequest::default().to_http_request();
669
670 let form = Form(Info {
671 hello: "world".to_string(),
672 counter: 123,
673 });
674 let resp = respond_to(form, &req).await;
675 assert_eq!(resp.status(), StatusCode::OK);
676 assert_eq!(
677 resp.headers().get(CONTENT_TYPE).unwrap(),
678 HeaderValue::from_static("application/x-www-form-urlencoded")
679 );
680
681 assert_eq!(resp.get_body_ref(), b"hello=world&counter=123");
682 }
683
684 #[crate::rt_test]
690 async fn test_urlencoded_errors2() {
691 let (req, mut pl, ()) = TestRequest::with_header(
692 CONTENT_TYPE,
693 "application/x-www-form-urlencoded; charset=unknown",
694 )
695 .to_http_parts();
696 let info = UrlEncoded::<Info>::new(&req, &mut pl).await;
697 assert!(eq(&info.err().unwrap(), &UrlencodedError::ContentType));
698
699 let (req, mut pl, ()) =
700 TestRequest::with_header(CONTENT_TYPE, "application/x-www-form-urlencoded")
701 .header(CONTENT_LENGTH, HeaderValue::from_bytes(b"1\xff").unwrap())
702 .to_http_parts();
703 let info = UrlEncoded::<Info>::new(&req, &mut pl).await;
704 assert!(eq(&info.err().unwrap(), &UrlencodedError::UnknownLength));
705
706 let (req, mut pl, ()) =
708 TestRequest::with_header(CONTENT_TYPE, "application/x-www-form-urlencoded")
709 .payload(Bytes::from_static(b"hello=world&counter=123"))
710 .to_http_parts();
711 let info = UrlEncoded::<Info>::new(&req, &mut pl).limit(5).await;
712 assert!(eq(
713 &info.err().unwrap(),
714 &UrlencodedError::Overflow { size: 0, limit: 0 }
715 ));
716 }
717
718 #[crate::rt_test]
724 async fn test_responder_error() {
725 let req = TestRequest::default().to_http_request();
726 let resp = respond_to(Form(1), &req).await;
727 assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
728 }
729}