1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-06-02 13:29:24 +00:00
actix-web/src/types/form.rs

491 lines
14 KiB
Rust
Raw Normal View History

//! Form extractor
use std::rc::Rc;
use std::{fmt, ops};
2019-07-20 11:55:52 +00:00
use actix_http::{Error, HttpMessage, Payload, Response};
use bytes::BytesMut;
use encoding_rs::{Encoding, UTF_8};
2019-03-17 07:48:40 +00:00
use futures::{Future, Poll, Stream};
use serde::de::DeserializeOwned;
2019-07-20 11:55:52 +00:00
use serde::Serialize;
use crate::dev::Decompress;
2019-03-17 08:08:56 +00:00
use crate::error::UrlencodedError;
use crate::extract::FromRequest;
2019-07-20 11:55:52 +00:00
use crate::http::{
header::{ContentType, CONTENT_LENGTH},
StatusCode,
};
use crate::request::HttpRequest;
2019-07-20 11:55:52 +00:00
use crate::responder::Responder;
2019-07-20 11:55:52 +00:00
/// Form data helper (`application/x-www-form-urlencoded`)
///
/// Can be use to extract url-encoded data from the request body,
/// or send url-encoded data as the response.
///
/// ## Extract
///
/// To extract typed information from request's body, the type `T` must
/// implement the `Deserialize` trait from *serde*.
///
/// [**FormConfig**](struct.FormConfig.html) allows to configure extraction
/// process.
///
2019-07-20 11:55:52 +00:00
/// ### Example
/// ```rust
/// use actix_web::web;
/// use serde_derive::Deserialize;
///
/// #[derive(Deserialize)]
/// struct FormData {
/// username: String,
/// }
///
/// /// Extract form data using serde.
/// /// This handler get called only if content type is *x-www-form-urlencoded*
/// /// and content of the request could be deserialized to a `FormData` struct
/// fn index(form: web::Form<FormData>) -> String {
/// format!("Welcome {}!", form.username)
/// }
/// # fn main() {}
/// ```
2019-07-20 11:55:52 +00:00
///
/// ## Respond
///
/// The `Form` type also allows you to respond with well-formed url-encoded data:
/// simply return a value of type Form<T> where T is the type to be url-encoded.
/// The type must implement `serde::Serialize`;
///
/// ### Example
/// ```rust
/// use actix_web::*;
/// use serde_derive::Serialize;
///
2019-07-20 11:55:52 +00:00
/// #[derive(Serialize)]
/// struct SomeForm {
/// name: String,
/// age: u8
/// }
///
/// // Will return a 200 response with header
/// // `Content-Type: application/x-www-form-urlencoded`
/// // and body "name=actix&age=123"
/// fn index() -> web::Form<SomeForm> {
/// web::Form(SomeForm {
/// name: "actix".into(),
/// age: 123
/// })
/// }
/// # fn main() {}
/// ```
#[derive(PartialEq, Eq, PartialOrd, Ord)]
pub struct Form<T>(pub T);
impl<T> Form<T> {
/// Deconstruct to an inner value
pub fn into_inner(self) -> T {
self.0
}
}
impl<T> ops::Deref for Form<T> {
type Target = T;
fn deref(&self) -> &T {
&self.0
}
}
impl<T> ops::DerefMut for Form<T> {
fn deref_mut(&mut self) -> &mut T {
&mut self.0
}
}
impl<T> FromRequest for Form<T>
where
T: DeserializeOwned + 'static,
{
2019-04-13 23:35:25 +00:00
type Config = FormConfig;
type Error = Error;
type Future = Box<dyn Future<Item = Self, Error = Error>>;
#[inline]
fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future {
2019-04-07 21:43:07 +00:00
let req2 = req.clone();
let (limit, err) = req
.app_data::<FormConfig>()
.map(|c| (c.limit, c.ehandler.clone()))
.unwrap_or((16384, None));
Box::new(
2019-04-07 21:43:07 +00:00
UrlEncoded::new(req, payload)
.limit(limit)
.map_err(move |e| {
if let Some(err) = err {
(*err)(e, &req2)
} else {
e.into()
}
})
.map(Form),
)
}
}
impl<T: fmt::Debug> fmt::Debug for Form<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
impl<T: fmt::Display> fmt::Display for Form<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
2019-07-20 11:55:52 +00:00
impl<T: Serialize> Responder for Form<T> {
type Error = Error;
type Future = Result<Response, Error>;
fn respond_to(self, _: &HttpRequest) -> Self::Future {
let body = match serde_urlencoded::to_string(&self.0) {
Ok(body) => body,
Err(e) => return Err(e.into()),
};
Ok(Response::build(StatusCode::OK)
.set(ContentType::form_url_encoded())
.body(body))
}
}
/// Form extractor configuration
///
/// ```rust
2019-04-13 23:35:25 +00:00
/// use actix_web::{web, App, FromRequest, Result};
/// use serde_derive::Deserialize;
///
/// #[derive(Deserialize)]
/// struct FormData {
/// username: String,
/// }
///
/// /// Extract form data using serde.
/// /// Custom configuration is used for this handler, max payload size is 4k
/// fn index(form: web::Form<FormData>) -> Result<String> {
/// Ok(format!("Welcome {}!", form.username))
/// }
///
/// fn main() {
/// let app = App::new().service(
/// web::resource("/index.html")
/// // change `Form` extractor configuration
/// .data(
/// web::Form::<FormData>::configure(|cfg| cfg.limit(4097))
/// )
/// .route(web::get().to(index))
/// );
/// }
/// ```
#[derive(Clone)]
pub struct FormConfig {
limit: usize,
2019-07-17 09:48:37 +00:00
ehandler: Option<Rc<dyn Fn(UrlencodedError, &HttpRequest) -> Error>>,
}
impl FormConfig {
/// Change max size of payload. By default max size is 16Kb
pub fn limit(mut self, limit: usize) -> Self {
self.limit = limit;
self
}
/// Set custom error handler
pub fn error_handler<F>(mut self, f: F) -> Self
where
F: Fn(UrlencodedError, &HttpRequest) -> Error + 'static,
{
self.ehandler = Some(Rc::new(f));
self
}
}
impl Default for FormConfig {
fn default() -> Self {
FormConfig {
limit: 16384,
ehandler: None,
}
}
}
2019-03-17 07:48:40 +00:00
/// Future that resolves to a parsed urlencoded values.
///
/// Parse `application/x-www-form-urlencoded` encoded request's body.
/// Return `UrlEncoded` future. Form can be deserialized to any type that
/// implements `Deserialize` trait from *serde*.
///
/// Returns error:
///
/// * content type is not `application/x-www-form-urlencoded`
/// * content-length is greater than 32k
///
pub struct UrlEncoded<U> {
stream: Option<Decompress<Payload>>,
2019-03-17 07:48:40 +00:00
limit: usize,
length: Option<usize>,
encoding: &'static Encoding,
2019-03-17 07:48:40 +00:00
err: Option<UrlencodedError>,
fut: Option<Box<dyn Future<Item = U, Error = UrlencodedError>>>,
2019-03-17 07:48:40 +00:00
}
impl<U> UrlEncoded<U> {
2019-03-17 07:48:40 +00:00
/// Create a new future to URL encode a request
pub fn new(req: &HttpRequest, payload: &mut Payload) -> UrlEncoded<U> {
2019-03-17 07:48:40 +00:00
// check content type
if req.content_type().to_lowercase() != "application/x-www-form-urlencoded" {
return Self::err(UrlencodedError::ContentType);
}
let encoding = match req.encoding() {
Ok(enc) => enc,
Err(_) => return Self::err(UrlencodedError::ContentType),
};
let mut len = None;
if let Some(l) = req.headers().get(&CONTENT_LENGTH) {
2019-03-17 07:48:40 +00:00
if let Ok(s) = l.to_str() {
if let Ok(l) = s.parse::<usize>() {
len = Some(l)
} else {
return Self::err(UrlencodedError::UnknownLength);
}
} else {
return Self::err(UrlencodedError::UnknownLength);
}
};
let payload = Decompress::from_headers(payload.take(), req.headers());
2019-03-17 07:48:40 +00:00
UrlEncoded {
encoding,
stream: Some(payload),
2019-03-17 07:48:40 +00:00
limit: 32_768,
length: len,
fut: None,
err: None,
}
}
fn err(e: UrlencodedError) -> Self {
UrlEncoded {
stream: None,
2019-03-17 07:48:40 +00:00
limit: 32_768,
fut: None,
err: Some(e),
length: None,
encoding: UTF_8,
}
}
/// Change max size of payload. By default max size is 256Kb
pub fn limit(mut self, limit: usize) -> Self {
self.limit = limit;
self
}
}
impl<U> Future for UrlEncoded<U>
2019-03-17 07:48:40 +00:00
where
U: DeserializeOwned + 'static,
{
type Item = U;
type Error = UrlencodedError;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
if let Some(ref mut fut) = self.fut {
return fut.poll();
}
if let Some(err) = self.err.take() {
return Err(err);
}
// payload size
let limit = self.limit;
if let Some(len) = self.length.take() {
if len > limit {
return Err(UrlencodedError::Overflow { size: len, limit });
2019-03-17 07:48:40 +00:00
}
}
// future
let encoding = self.encoding;
let fut = self
.stream
.take()
.unwrap()
2019-03-17 07:48:40 +00:00
.from_err()
.fold(BytesMut::with_capacity(8192), move |mut body, chunk| {
if (body.len() + chunk.len()) > limit {
Err(UrlencodedError::Overflow {
size: body.len() + chunk.len(),
limit,
})
2019-03-17 07:48:40 +00:00
} else {
body.extend_from_slice(&chunk);
Ok(body)
}
})
.and_then(move |body| {
if encoding == UTF_8 {
2019-03-17 07:48:40 +00:00
serde_urlencoded::from_bytes::<U>(&body)
.map_err(|_| UrlencodedError::Parse)
} else {
let body = encoding
.decode_without_bom_handling_and_without_replacement(&body)
.map(|s| s.into_owned())
.ok_or(UrlencodedError::Parse)?;
2019-03-17 07:48:40 +00:00
serde_urlencoded::from_str::<U>(&body)
.map_err(|_| UrlencodedError::Parse)
}
});
self.fut = Some(Box::new(fut));
self.poll()
}
}
#[cfg(test)]
mod tests {
use bytes::Bytes;
2019-07-20 11:55:52 +00:00
use serde::{Deserialize, Serialize};
use super::*;
2019-07-20 11:55:52 +00:00
use crate::http::header::{HeaderValue, CONTENT_TYPE};
use crate::test::{block_on, TestRequest};
2019-07-20 11:55:52 +00:00
#[derive(Deserialize, Serialize, Debug, PartialEq)]
struct Info {
hello: String,
2019-07-20 11:55:52 +00:00
counter: i64,
}
#[test]
fn test_form() {
2019-04-07 21:43:07 +00:00
let (req, mut pl) =
2019-03-17 07:48:40 +00:00
TestRequest::with_header(CONTENT_TYPE, "application/x-www-form-urlencoded")
.header(CONTENT_LENGTH, "11")
2019-07-20 11:55:52 +00:00
.set_payload(Bytes::from_static(b"hello=world&counter=123"))
2019-04-07 21:43:07 +00:00
.to_http_parts();
2019-03-17 07:48:40 +00:00
2019-07-20 11:55:52 +00:00
let Form(s) = block_on(Form::<Info>::from_request(&req, &mut pl)).unwrap();
assert_eq!(
s,
Info {
hello: "world".into(),
counter: 123
}
);
2019-03-17 07:48:40 +00:00
}
fn eq(err: UrlencodedError, other: UrlencodedError) -> bool {
match err {
UrlencodedError::Overflow { .. } => match other {
UrlencodedError::Overflow { .. } => true,
2019-03-17 07:48:40 +00:00
_ => false,
},
UrlencodedError::UnknownLength => match other {
UrlencodedError::UnknownLength => true,
_ => false,
},
UrlencodedError::ContentType => match other {
UrlencodedError::ContentType => true,
_ => false,
},
_ => false,
}
}
#[test]
fn test_urlencoded_error() {
2019-04-07 21:43:07 +00:00
let (req, mut pl) =
2019-03-17 07:48:40 +00:00
TestRequest::with_header(CONTENT_TYPE, "application/x-www-form-urlencoded")
.header(CONTENT_LENGTH, "xxxx")
2019-04-07 21:43:07 +00:00
.to_http_parts();
let info = block_on(UrlEncoded::<Info>::new(&req, &mut pl));
2019-03-17 07:48:40 +00:00
assert!(eq(info.err().unwrap(), UrlencodedError::UnknownLength));
2019-04-07 21:43:07 +00:00
let (req, mut pl) =
2019-03-17 07:48:40 +00:00
TestRequest::with_header(CONTENT_TYPE, "application/x-www-form-urlencoded")
.header(CONTENT_LENGTH, "1000000")
2019-04-07 21:43:07 +00:00
.to_http_parts();
let info = block_on(UrlEncoded::<Info>::new(&req, &mut pl));
assert!(eq(
info.err().unwrap(),
UrlencodedError::Overflow { size: 0, limit: 0 }
));
2019-03-17 07:48:40 +00:00
2019-04-07 21:43:07 +00:00
let (req, mut pl) = TestRequest::with_header(CONTENT_TYPE, "text/plain")
2019-03-17 07:48:40 +00:00
.header(CONTENT_LENGTH, "10")
2019-04-07 21:43:07 +00:00
.to_http_parts();
let info = block_on(UrlEncoded::<Info>::new(&req, &mut pl));
2019-03-17 07:48:40 +00:00
assert!(eq(info.err().unwrap(), UrlencodedError::ContentType));
}
#[test]
fn test_urlencoded() {
2019-04-07 21:43:07 +00:00
let (req, mut pl) =
2019-03-17 07:48:40 +00:00
TestRequest::with_header(CONTENT_TYPE, "application/x-www-form-urlencoded")
.header(CONTENT_LENGTH, "11")
2019-07-20 11:55:52 +00:00
.set_payload(Bytes::from_static(b"hello=world&counter=123"))
2019-04-07 21:43:07 +00:00
.to_http_parts();
2019-03-17 07:48:40 +00:00
let info = block_on(UrlEncoded::<Info>::new(&req, &mut pl)).unwrap();
2019-03-17 07:48:40 +00:00
assert_eq!(
info,
Info {
2019-07-20 11:55:52 +00:00
hello: "world".to_owned(),
counter: 123
2019-03-17 07:48:40 +00:00
}
);
2019-04-07 21:43:07 +00:00
let (req, mut pl) = TestRequest::with_header(
2019-03-17 07:48:40 +00:00
CONTENT_TYPE,
"application/x-www-form-urlencoded; charset=utf-8",
)
2019-03-17 07:48:40 +00:00
.header(CONTENT_LENGTH, "11")
2019-07-20 11:55:52 +00:00
.set_payload(Bytes::from_static(b"hello=world&counter=123"))
2019-04-07 21:43:07 +00:00
.to_http_parts();
let info = block_on(UrlEncoded::<Info>::new(&req, &mut pl)).unwrap();
2019-03-17 07:48:40 +00:00
assert_eq!(
info,
Info {
2019-07-20 11:55:52 +00:00
hello: "world".to_owned(),
counter: 123
2019-03-17 07:48:40 +00:00
}
);
}
2019-07-20 11:55:52 +00:00
#[test]
fn test_responder() {
let req = TestRequest::default().to_http_request();
let form = Form(Info {
hello: "world".to_string(),
counter: 123,
});
let resp = form.respond_to(&req).unwrap();
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(
resp.headers().get(CONTENT_TYPE).unwrap(),
HeaderValue::from_static("application/x-www-form-urlencoded")
);
use crate::responder::tests::BodyTest;
assert_eq!(resp.body().bin_ref(), b"hello=world&counter=123");
}
}