2018-02-28 00:03:28 +01:00
|
|
|
use bytes::{Bytes, BytesMut};
|
2018-04-14 01:02:01 +02:00
|
|
|
use encoding::all::UTF_8;
|
2018-02-28 00:03:28 +01:00
|
|
|
use encoding::label::encoding_from_whatwg_label;
|
2018-04-14 01:02:01 +02:00
|
|
|
use encoding::types::{DecoderTrap, Encoding};
|
2018-04-29 07:55:47 +02:00
|
|
|
use encoding::EncodingRef;
|
2018-06-13 19:43:03 +02:00
|
|
|
use futures::{Future, Poll, Stream, Async};
|
2018-02-28 00:03:28 +01:00
|
|
|
use http::{header, HeaderMap};
|
2018-04-14 01:02:01 +02:00
|
|
|
use http_range::HttpRange;
|
|
|
|
use mime::Mime;
|
|
|
|
use serde::de::DeserializeOwned;
|
|
|
|
use serde_urlencoded;
|
|
|
|
use std::str;
|
2018-02-28 00:03:28 +01:00
|
|
|
|
2018-05-17 21:20:20 +02:00
|
|
|
use error::{
|
|
|
|
ContentTypeError, HttpRangeError, ParseError, PayloadError, UrlencodedError,
|
|
|
|
};
|
2018-03-06 04:28:42 +01:00
|
|
|
use header::Header;
|
2018-04-14 01:02:01 +02:00
|
|
|
use json::JsonBody;
|
2018-02-28 00:03:28 +01:00
|
|
|
use multipart::Multipart;
|
|
|
|
|
2018-02-28 08:30:26 +01:00
|
|
|
/// Trait that implements general purpose operations on http messages
|
2018-02-28 00:03:28 +01:00
|
|
|
pub trait HttpMessage {
|
2018-02-28 08:30:26 +01:00
|
|
|
/// Read the message headers.
|
2018-02-28 00:03:28 +01:00
|
|
|
fn headers(&self) -> &HeaderMap;
|
|
|
|
|
2018-03-06 04:28:42 +01:00
|
|
|
#[doc(hidden)]
|
|
|
|
/// Get a header
|
2018-04-14 01:02:01 +02:00
|
|
|
fn get_header<H: Header>(&self) -> Option<H>
|
|
|
|
where
|
|
|
|
Self: Sized,
|
|
|
|
{
|
2018-03-08 02:40:13 +01:00
|
|
|
if self.headers().contains_key(H::name()) {
|
|
|
|
H::parse(self).ok()
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
2018-03-06 04:28:42 +01:00
|
|
|
}
|
2018-04-14 01:02:01 +02:00
|
|
|
|
2018-02-28 00:03:28 +01:00
|
|
|
/// Read the request content type. If request does not contain
|
|
|
|
/// *Content-Type* header, empty str get returned.
|
|
|
|
fn content_type(&self) -> &str {
|
|
|
|
if let Some(content_type) = self.headers().get(header::CONTENT_TYPE) {
|
|
|
|
if let Ok(content_type) = content_type.to_str() {
|
2018-04-14 01:02:01 +02:00
|
|
|
return content_type.split(';').next().unwrap().trim();
|
2018-02-28 00:03:28 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
""
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Get content type encoding
|
|
|
|
///
|
|
|
|
/// UTF-8 is used by default, If request charset is not set.
|
|
|
|
fn encoding(&self) -> Result<EncodingRef, ContentTypeError> {
|
|
|
|
if let Some(mime_type) = self.mime_type()? {
|
|
|
|
if let Some(charset) = mime_type.get_param("charset") {
|
|
|
|
if let Some(enc) = encoding_from_whatwg_label(charset.as_str()) {
|
|
|
|
Ok(enc)
|
|
|
|
} else {
|
|
|
|
Err(ContentTypeError::UnknownEncoding)
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
Ok(UTF_8)
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
Ok(UTF_8)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Convert the request content type to a known mime type.
|
|
|
|
fn mime_type(&self) -> Result<Option<Mime>, ContentTypeError> {
|
|
|
|
if let Some(content_type) = self.headers().get(header::CONTENT_TYPE) {
|
|
|
|
if let Ok(content_type) = content_type.to_str() {
|
|
|
|
return match content_type.parse() {
|
|
|
|
Ok(mt) => Ok(Some(mt)),
|
|
|
|
Err(_) => Err(ContentTypeError::ParseError),
|
|
|
|
};
|
|
|
|
} else {
|
2018-04-14 01:02:01 +02:00
|
|
|
return Err(ContentTypeError::ParseError);
|
2018-02-28 00:03:28 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
Ok(None)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Check if request has chunked transfer encoding
|
|
|
|
fn chunked(&self) -> Result<bool, ParseError> {
|
|
|
|
if let Some(encodings) = self.headers().get(header::TRANSFER_ENCODING) {
|
|
|
|
if let Ok(s) = encodings.to_str() {
|
|
|
|
Ok(s.to_lowercase().contains("chunked"))
|
|
|
|
} else {
|
|
|
|
Err(ParseError::Header)
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
Ok(false)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Parses Range HTTP header string as per RFC 2616.
|
|
|
|
/// `size` is full size of response (file).
|
|
|
|
fn range(&self, size: u64) -> Result<Vec<HttpRange>, HttpRangeError> {
|
|
|
|
if let Some(range) = self.headers().get(header::RANGE) {
|
2018-05-17 21:20:20 +02:00
|
|
|
HttpRange::parse(unsafe { str::from_utf8_unchecked(range.as_bytes()) }, size)
|
|
|
|
.map_err(|e| e.into())
|
2018-02-28 00:03:28 +01:00
|
|
|
} else {
|
|
|
|
Ok(Vec::new())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Load http message body.
|
|
|
|
///
|
2018-04-14 01:02:01 +02:00
|
|
|
/// By default only 256Kb payload reads to a memory, then
|
|
|
|
/// `PayloadError::Overflow` get returned. Use `MessageBody::limit()`
|
|
|
|
/// method to change upper limit.
|
2018-02-28 00:03:28 +01:00
|
|
|
///
|
|
|
|
/// ## Server example
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// # extern crate bytes;
|
|
|
|
/// # extern crate actix_web;
|
|
|
|
/// # extern crate futures;
|
|
|
|
/// # #[macro_use] extern crate serde_derive;
|
2018-06-01 18:36:16 +02:00
|
|
|
/// use actix_web::{
|
|
|
|
/// AsyncResponder, FutureResponse, HttpMessage, HttpRequest, HttpResponse,
|
|
|
|
/// };
|
2018-02-28 00:03:28 +01:00
|
|
|
/// use bytes::Bytes;
|
|
|
|
/// use futures::future::Future;
|
|
|
|
///
|
2018-04-14 04:10:42 +02:00
|
|
|
/// fn index(mut req: HttpRequest) -> FutureResponse<HttpResponse> {
|
2018-02-28 00:03:28 +01:00
|
|
|
/// req.body() // <- get Body future
|
|
|
|
/// .limit(1024) // <- change max size of the body to a 1kb
|
|
|
|
/// .from_err()
|
|
|
|
/// .and_then(|bytes: Bytes| { // <- complete body
|
|
|
|
/// println!("==== BODY ==== {:?}", bytes);
|
2018-03-31 08:07:33 +02:00
|
|
|
/// Ok(HttpResponse::Ok().into())
|
2018-02-28 00:03:28 +01:00
|
|
|
/// }).responder()
|
|
|
|
/// }
|
|
|
|
/// # fn main() {}
|
|
|
|
/// ```
|
|
|
|
fn body(self) -> MessageBody<Self>
|
2018-04-14 01:02:01 +02:00
|
|
|
where
|
|
|
|
Self: Stream<Item = Bytes, Error = PayloadError> + Sized,
|
2018-02-28 00:03:28 +01:00
|
|
|
{
|
|
|
|
MessageBody::new(self)
|
|
|
|
}
|
|
|
|
|
2018-03-28 05:33:24 +02:00
|
|
|
/// Parse `application/x-www-form-urlencoded` encoded request's body.
|
2018-04-14 01:02:01 +02:00
|
|
|
/// Return `UrlEncoded` future. Form can be deserialized to any type that
|
|
|
|
/// implements `Deserialize` trait from *serde*.
|
2018-02-28 00:03:28 +01:00
|
|
|
///
|
|
|
|
/// Returns error:
|
|
|
|
///
|
|
|
|
/// * content type is not `application/x-www-form-urlencoded`
|
|
|
|
/// * content-length is greater than 256k
|
|
|
|
///
|
|
|
|
/// ## Server example
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// # extern crate actix_web;
|
|
|
|
/// # extern crate futures;
|
2018-03-28 05:33:24 +02:00
|
|
|
/// # use futures::Future;
|
2018-04-02 23:00:18 +02:00
|
|
|
/// # use std::collections::HashMap;
|
2018-06-01 18:36:16 +02:00
|
|
|
/// use actix_web::{FutureResponse, HttpMessage, HttpRequest, HttpResponse};
|
2018-02-28 00:03:28 +01:00
|
|
|
///
|
2018-03-28 05:33:24 +02:00
|
|
|
/// fn index(mut req: HttpRequest) -> FutureResponse<HttpResponse> {
|
2018-04-02 23:00:18 +02:00
|
|
|
/// Box::new(
|
|
|
|
/// req.urlencoded::<HashMap<String, String>>() // <- get UrlEncoded future
|
|
|
|
/// .from_err()
|
|
|
|
/// .and_then(|params| { // <- url encoded parameters
|
|
|
|
/// println!("==== BODY ==== {:?}", params);
|
|
|
|
/// Ok(HttpResponse::Ok().into())
|
2018-06-01 18:36:16 +02:00
|
|
|
/// }),
|
|
|
|
/// )
|
2018-02-28 00:03:28 +01:00
|
|
|
/// }
|
|
|
|
/// # fn main() {}
|
|
|
|
/// ```
|
2018-04-02 23:00:18 +02:00
|
|
|
fn urlencoded<T: DeserializeOwned>(self) -> UrlEncoded<Self, T>
|
2018-04-14 01:02:01 +02:00
|
|
|
where
|
|
|
|
Self: Stream<Item = Bytes, Error = PayloadError> + Sized,
|
2018-02-28 00:03:28 +01:00
|
|
|
{
|
|
|
|
UrlEncoded::new(self)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Parse `application/json` encoded body.
|
|
|
|
/// Return `JsonBody<T>` future. It resolves to a `T` value.
|
|
|
|
///
|
|
|
|
/// Returns error:
|
|
|
|
///
|
|
|
|
/// * content type is not `application/json`
|
|
|
|
/// * content length is greater than 256k
|
|
|
|
///
|
|
|
|
/// ## Server example
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// # extern crate actix_web;
|
|
|
|
/// # extern crate futures;
|
|
|
|
/// # #[macro_use] extern crate serde_derive;
|
|
|
|
/// use actix_web::*;
|
2018-06-01 18:36:16 +02:00
|
|
|
/// use futures::future::{ok, Future};
|
2018-02-28 00:03:28 +01:00
|
|
|
///
|
|
|
|
/// #[derive(Deserialize, Debug)]
|
|
|
|
/// struct MyObj {
|
|
|
|
/// name: String,
|
|
|
|
/// }
|
|
|
|
///
|
2018-06-01 18:36:16 +02:00
|
|
|
/// fn index(mut req: HttpRequest) -> Box<Future<Item = HttpResponse, Error = Error>> {
|
2018-02-28 00:03:28 +01:00
|
|
|
/// req.json() // <- get JsonBody future
|
|
|
|
/// .from_err()
|
|
|
|
/// .and_then(|val: MyObj| { // <- deserialized value
|
|
|
|
/// println!("==== BODY ==== {:?}", val);
|
2018-03-31 08:07:33 +02:00
|
|
|
/// Ok(HttpResponse::Ok().into())
|
2018-02-28 00:03:28 +01:00
|
|
|
/// }).responder()
|
|
|
|
/// }
|
|
|
|
/// # fn main() {}
|
|
|
|
/// ```
|
|
|
|
fn json<T: DeserializeOwned>(self) -> JsonBody<Self, T>
|
2018-04-14 01:02:01 +02:00
|
|
|
where
|
|
|
|
Self: Stream<Item = Bytes, Error = PayloadError> + Sized,
|
2018-02-28 00:03:28 +01:00
|
|
|
{
|
|
|
|
JsonBody::new(self)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Return stream to http payload processes as multipart.
|
|
|
|
///
|
|
|
|
/// Content-type: multipart/form-data;
|
|
|
|
///
|
|
|
|
/// ## Server example
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// # extern crate actix_web;
|
|
|
|
/// # extern crate env_logger;
|
|
|
|
/// # extern crate futures;
|
|
|
|
/// # use std::str;
|
|
|
|
/// # use actix_web::*;
|
2018-06-01 19:27:23 +02:00
|
|
|
/// # use actix_web::actix::fut::FinishStream;
|
2018-02-28 00:03:28 +01:00
|
|
|
/// # use futures::{Future, Stream};
|
|
|
|
/// # use futures::future::{ok, result, Either};
|
2018-06-01 18:36:16 +02:00
|
|
|
/// fn index(mut req: HttpRequest) -> Box<Future<Item = HttpResponse, Error = Error>> {
|
2018-02-28 00:03:28 +01:00
|
|
|
/// req.multipart().from_err() // <- get multipart stream for current request
|
|
|
|
/// .and_then(|item| match item { // <- iterate over multipart items
|
|
|
|
/// multipart::MultipartItem::Field(field) => {
|
|
|
|
/// // Field in turn is stream of *Bytes* object
|
|
|
|
/// Either::A(field.from_err()
|
|
|
|
/// .map(|c| println!("-- CHUNK: \n{:?}", str::from_utf8(&c)))
|
|
|
|
/// .finish())
|
|
|
|
/// },
|
|
|
|
/// multipart::MultipartItem::Nested(mp) => {
|
|
|
|
/// // Or item could be nested Multipart stream
|
|
|
|
/// Either::B(ok(()))
|
|
|
|
/// }
|
|
|
|
/// })
|
|
|
|
/// .finish() // <- Stream::finish() combinator from actix
|
2018-03-31 08:07:33 +02:00
|
|
|
/// .map(|_| HttpResponse::Ok().into())
|
2018-02-28 00:03:28 +01:00
|
|
|
/// .responder()
|
|
|
|
/// }
|
|
|
|
/// # fn main() {}
|
|
|
|
/// ```
|
|
|
|
fn multipart(self) -> Multipart<Self>
|
2018-04-14 01:02:01 +02:00
|
|
|
where
|
|
|
|
Self: Stream<Item = Bytes, Error = PayloadError> + Sized,
|
2018-02-28 00:03:28 +01:00
|
|
|
{
|
|
|
|
let boundary = Multipart::boundary(self.headers());
|
|
|
|
Multipart::new(boundary, self)
|
|
|
|
}
|
2018-06-13 19:43:03 +02:00
|
|
|
|
|
|
|
/// Return stream of lines.
|
|
|
|
fn readlines(self) -> Readlines<Self>
|
|
|
|
where
|
|
|
|
Self: Stream<Item = Bytes, Error = PayloadError> + Sized,
|
|
|
|
{
|
|
|
|
Readlines::new(self)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Stream to read request line by line.
|
|
|
|
pub struct Readlines<T>
|
|
|
|
where
|
|
|
|
T: HttpMessage + Stream<Item = Bytes, Error = PayloadError> + 'static,
|
|
|
|
{
|
|
|
|
req: T,
|
|
|
|
buff: Vec<u8>,
|
|
|
|
limit: usize,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T> Readlines<T>
|
|
|
|
where
|
|
|
|
T: HttpMessage + Stream<Item = Bytes, Error = PayloadError> + 'static,
|
|
|
|
{
|
|
|
|
/// Create a new stream to read request line by line.
|
|
|
|
fn new(req: T) -> Self {
|
|
|
|
Readlines {
|
|
|
|
req,
|
|
|
|
buff: Vec::with_capacity(256),
|
|
|
|
limit: 262_144,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Change max size of payload. By default max size is 256Kb
|
|
|
|
pub fn limit(mut self, limit: usize) -> Self {
|
|
|
|
self.limit = limit;
|
|
|
|
self
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T> Stream for Readlines<T>
|
|
|
|
where
|
|
|
|
T: HttpMessage + Stream<Item = Bytes, Error = PayloadError> + 'static,
|
|
|
|
{
|
|
|
|
type Item = String;
|
|
|
|
type Error = ReadlinesError;
|
|
|
|
|
|
|
|
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
|
|
|
|
match self.req.poll() {
|
|
|
|
Ok(Async::Ready(Some(bytes))) => {
|
|
|
|
for b in bytes.iter() {
|
|
|
|
if *b == '\n' as u8 {
|
|
|
|
self.buff.push(*b);
|
|
|
|
let line = str::from_utf8(&*self.buff)?.to_owned();
|
|
|
|
self.buff.clear();
|
|
|
|
return Ok(Async::Ready(Some(line)));
|
|
|
|
} else {
|
|
|
|
self.buff.push(*b);
|
|
|
|
}
|
|
|
|
if self.limit < self.buff.len() {
|
|
|
|
return Err(ReadlinesError::LimitOverflow);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Ok(Async::NotReady)
|
|
|
|
},
|
|
|
|
Ok(Async::NotReady) => Ok(Async::NotReady),
|
|
|
|
Ok(Async::Ready(None)) => {
|
|
|
|
if self.buff.len() == 0 {
|
|
|
|
return Ok(Async::Ready(None));
|
|
|
|
}
|
|
|
|
let line = str::from_utf8(&*self.buff)?.to_owned();
|
|
|
|
self.buff.clear();
|
|
|
|
return Ok(Async::Ready(Some(line)))
|
|
|
|
},
|
|
|
|
Err(e) => Err(ReadlinesError::from(e)),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub enum ReadlinesError {
|
|
|
|
EncodingError,
|
|
|
|
PayloadError(PayloadError),
|
|
|
|
LimitOverflow,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<PayloadError> for ReadlinesError {
|
|
|
|
fn from(err: PayloadError) -> Self {
|
|
|
|
ReadlinesError::PayloadError(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<str::Utf8Error> for ReadlinesError {
|
|
|
|
fn from(_: str::Utf8Error) -> Self {
|
|
|
|
ReadlinesError::EncodingError
|
|
|
|
}
|
2018-02-28 00:03:28 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Future that resolves to a complete http message body.
|
|
|
|
pub struct MessageBody<T> {
|
|
|
|
limit: usize,
|
|
|
|
req: Option<T>,
|
2018-04-14 01:02:01 +02:00
|
|
|
fut: Option<Box<Future<Item = Bytes, Error = PayloadError>>>,
|
2018-02-28 00:03:28 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
impl<T> MessageBody<T> {
|
|
|
|
/// Create `RequestBody` for request.
|
|
|
|
pub fn new(req: T) -> MessageBody<T> {
|
|
|
|
MessageBody {
|
|
|
|
limit: 262_144,
|
|
|
|
req: Some(req),
|
|
|
|
fut: None,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Change max size of payload. By default max size is 256Kb
|
|
|
|
pub fn limit(mut self, limit: usize) -> Self {
|
|
|
|
self.limit = limit;
|
|
|
|
self
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T> Future for MessageBody<T>
|
2018-04-14 01:02:01 +02:00
|
|
|
where
|
|
|
|
T: HttpMessage + Stream<Item = Bytes, Error = PayloadError> + 'static,
|
2018-02-28 00:03:28 +01:00
|
|
|
{
|
|
|
|
type Item = Bytes;
|
|
|
|
type Error = PayloadError;
|
|
|
|
|
|
|
|
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
|
|
|
if let Some(req) = self.req.take() {
|
|
|
|
if let Some(len) = req.headers().get(header::CONTENT_LENGTH) {
|
|
|
|
if let Ok(s) = len.to_str() {
|
|
|
|
if let Ok(len) = s.parse::<usize>() {
|
|
|
|
if len > self.limit {
|
|
|
|
return Err(PayloadError::Overflow);
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
return Err(PayloadError::UnknownLength);
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
return Err(PayloadError::UnknownLength);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// future
|
|
|
|
let limit = self.limit;
|
|
|
|
self.fut = Some(Box::new(
|
|
|
|
req.from_err()
|
|
|
|
.fold(BytesMut::new(), move |mut body, chunk| {
|
|
|
|
if (body.len() + chunk.len()) > limit {
|
|
|
|
Err(PayloadError::Overflow)
|
|
|
|
} else {
|
|
|
|
body.extend_from_slice(&chunk);
|
|
|
|
Ok(body)
|
|
|
|
}
|
|
|
|
})
|
2018-04-14 01:02:01 +02:00
|
|
|
.map(|body| body.freeze()),
|
2018-02-28 00:03:28 +01:00
|
|
|
));
|
|
|
|
}
|
|
|
|
|
2018-04-29 18:09:08 +02:00
|
|
|
self.fut
|
|
|
|
.as_mut()
|
|
|
|
.expect("UrlEncoded could not be used second time")
|
|
|
|
.poll()
|
2018-02-28 00:03:28 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Future that resolves to a parsed urlencoded values.
|
2018-04-02 23:00:18 +02:00
|
|
|
pub struct UrlEncoded<T, U> {
|
2018-02-28 00:03:28 +01:00
|
|
|
req: Option<T>,
|
|
|
|
limit: usize,
|
2018-04-14 01:02:01 +02:00
|
|
|
fut: Option<Box<Future<Item = U, Error = UrlencodedError>>>,
|
2018-02-28 00:03:28 +01:00
|
|
|
}
|
|
|
|
|
2018-04-02 23:00:18 +02:00
|
|
|
impl<T, U> UrlEncoded<T, U> {
|
2018-06-02 15:51:58 +02:00
|
|
|
/// Create a new future to URL encode a request
|
2018-04-02 23:00:18 +02:00
|
|
|
pub fn new(req: T) -> UrlEncoded<T, U> {
|
2018-02-28 00:03:28 +01:00
|
|
|
UrlEncoded {
|
|
|
|
req: Some(req),
|
|
|
|
limit: 262_144,
|
|
|
|
fut: None,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Change max size of payload. By default max size is 256Kb
|
|
|
|
pub fn limit(mut self, limit: usize) -> Self {
|
|
|
|
self.limit = limit;
|
|
|
|
self
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-04-02 23:00:18 +02:00
|
|
|
impl<T, U> Future for UrlEncoded<T, U>
|
2018-04-14 01:02:01 +02:00
|
|
|
where
|
|
|
|
T: HttpMessage + Stream<Item = Bytes, Error = PayloadError> + 'static,
|
|
|
|
U: DeserializeOwned + 'static,
|
2018-02-28 00:03:28 +01:00
|
|
|
{
|
2018-04-02 23:00:18 +02:00
|
|
|
type Item = U;
|
2018-02-28 00:03:28 +01:00
|
|
|
type Error = UrlencodedError;
|
|
|
|
|
|
|
|
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
|
|
|
if let Some(req) = self.req.take() {
|
2018-06-02 23:57:36 +02:00
|
|
|
if let Some(len) = req.headers().get(header::CONTENT_LENGTH) {
|
2018-02-28 00:03:28 +01:00
|
|
|
if let Ok(s) = len.to_str() {
|
|
|
|
if let Ok(len) = s.parse::<u64>() {
|
|
|
|
if len > 262_144 {
|
|
|
|
return Err(UrlencodedError::Overflow);
|
|
|
|
}
|
|
|
|
} else {
|
2018-04-14 01:02:01 +02:00
|
|
|
return Err(UrlencodedError::UnknownLength);
|
2018-02-28 00:03:28 +01:00
|
|
|
}
|
|
|
|
} else {
|
2018-04-14 01:02:01 +02:00
|
|
|
return Err(UrlencodedError::UnknownLength);
|
2018-02-28 00:03:28 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// check content type
|
|
|
|
if req.content_type().to_lowercase() != "application/x-www-form-urlencoded" {
|
2018-04-14 01:02:01 +02:00
|
|
|
return Err(UrlencodedError::ContentType);
|
2018-02-28 00:03:28 +01:00
|
|
|
}
|
2018-05-17 21:20:20 +02:00
|
|
|
let encoding = req.encoding().map_err(|_| UrlencodedError::ContentType)?;
|
2018-02-28 00:03:28 +01:00
|
|
|
|
|
|
|
// future
|
|
|
|
let limit = self.limit;
|
2018-05-17 21:20:20 +02:00
|
|
|
let fut = req
|
|
|
|
.from_err()
|
2018-02-28 00:03:28 +01:00
|
|
|
.fold(BytesMut::new(), move |mut body, chunk| {
|
|
|
|
if (body.len() + chunk.len()) > limit {
|
|
|
|
Err(UrlencodedError::Overflow)
|
|
|
|
} else {
|
|
|
|
body.extend_from_slice(&chunk);
|
|
|
|
Ok(body)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
.and_then(move |body| {
|
2018-04-02 23:00:18 +02:00
|
|
|
let enc: *const Encoding = encoding as *const Encoding;
|
|
|
|
if enc == UTF_8 {
|
|
|
|
serde_urlencoded::from_bytes::<U>(&body)
|
|
|
|
.map_err(|_| UrlencodedError::Parse)
|
|
|
|
} else {
|
2018-04-14 01:02:01 +02:00
|
|
|
let body = encoding
|
|
|
|
.decode(&body, DecoderTrap::Strict)
|
2018-04-02 23:00:18 +02:00
|
|
|
.map_err(|_| UrlencodedError::Parse)?;
|
|
|
|
serde_urlencoded::from_str::<U>(&body)
|
|
|
|
.map_err(|_| UrlencodedError::Parse)
|
2018-02-28 00:03:28 +01:00
|
|
|
}
|
|
|
|
});
|
|
|
|
self.fut = Some(Box::new(fut));
|
|
|
|
}
|
|
|
|
|
2018-04-29 18:09:08 +02:00
|
|
|
self.fut
|
|
|
|
.as_mut()
|
|
|
|
.expect("UrlEncoded could not be used second time")
|
|
|
|
.poll()
|
2018-02-28 00:03:28 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::*;
|
|
|
|
use encoding::all::ISO_8859_2;
|
2018-04-29 07:55:47 +02:00
|
|
|
use encoding::Encoding;
|
2018-02-28 00:03:28 +01:00
|
|
|
use futures::Async;
|
2018-04-14 01:02:01 +02:00
|
|
|
use http::{Method, Uri, Version};
|
2018-02-28 00:03:28 +01:00
|
|
|
use httprequest::HttpRequest;
|
2018-04-14 01:02:01 +02:00
|
|
|
use mime;
|
2018-02-28 00:03:28 +01:00
|
|
|
use std::str::FromStr;
|
|
|
|
use test::TestRequest;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_content_type() {
|
|
|
|
let req = TestRequest::with_header("content-type", "text/plain").finish();
|
|
|
|
assert_eq!(req.content_type(), "text/plain");
|
2018-04-14 01:02:01 +02:00
|
|
|
let req =
|
|
|
|
TestRequest::with_header("content-type", "application/json; charset=utf=8")
|
|
|
|
.finish();
|
2018-02-28 00:03:28 +01:00
|
|
|
assert_eq!(req.content_type(), "application/json");
|
|
|
|
let req = HttpRequest::default();
|
|
|
|
assert_eq!(req.content_type(), "");
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_mime_type() {
|
|
|
|
let req = TestRequest::with_header("content-type", "application/json").finish();
|
|
|
|
assert_eq!(req.mime_type().unwrap(), Some(mime::APPLICATION_JSON));
|
|
|
|
let req = HttpRequest::default();
|
|
|
|
assert_eq!(req.mime_type().unwrap(), None);
|
2018-04-14 01:02:01 +02:00
|
|
|
let req =
|
|
|
|
TestRequest::with_header("content-type", "application/json; charset=utf-8")
|
|
|
|
.finish();
|
2018-02-28 00:03:28 +01:00
|
|
|
let mt = req.mime_type().unwrap().unwrap();
|
|
|
|
assert_eq!(mt.get_param(mime::CHARSET), Some(mime::UTF_8));
|
|
|
|
assert_eq!(mt.type_(), mime::APPLICATION);
|
|
|
|
assert_eq!(mt.subtype(), mime::JSON);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_mime_type_error() {
|
|
|
|
let req = TestRequest::with_header(
|
2018-04-14 01:02:01 +02:00
|
|
|
"content-type",
|
|
|
|
"applicationadfadsfasdflknadsfklnadsfjson",
|
|
|
|
).finish();
|
2018-02-28 00:03:28 +01:00
|
|
|
assert_eq!(Err(ContentTypeError::ParseError), req.mime_type());
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_encoding() {
|
|
|
|
let req = HttpRequest::default();
|
|
|
|
assert_eq!(UTF_8.name(), req.encoding().unwrap().name());
|
|
|
|
|
2018-04-14 01:02:01 +02:00
|
|
|
let req = TestRequest::with_header("content-type", "application/json").finish();
|
2018-02-28 00:03:28 +01:00
|
|
|
assert_eq!(UTF_8.name(), req.encoding().unwrap().name());
|
|
|
|
|
|
|
|
let req = TestRequest::with_header(
|
2018-04-14 01:02:01 +02:00
|
|
|
"content-type",
|
|
|
|
"application/json; charset=ISO-8859-2",
|
|
|
|
).finish();
|
2018-02-28 00:03:28 +01:00
|
|
|
assert_eq!(ISO_8859_2.name(), req.encoding().unwrap().name());
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_encoding_error() {
|
2018-04-14 01:02:01 +02:00
|
|
|
let req = TestRequest::with_header("content-type", "applicatjson").finish();
|
2018-05-17 21:20:20 +02:00
|
|
|
assert_eq!(Some(ContentTypeError::ParseError), req.encoding().err());
|
2018-02-28 00:03:28 +01:00
|
|
|
|
|
|
|
let req = TestRequest::with_header(
|
2018-04-14 01:02:01 +02:00
|
|
|
"content-type",
|
|
|
|
"application/json; charset=kkkttktk",
|
|
|
|
).finish();
|
2018-04-29 18:09:08 +02:00
|
|
|
assert_eq!(
|
|
|
|
Some(ContentTypeError::UnknownEncoding),
|
|
|
|
req.encoding().err()
|
|
|
|
);
|
2018-02-28 00:03:28 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_no_request_range_header() {
|
|
|
|
let req = HttpRequest::default();
|
|
|
|
let ranges = req.range(100).unwrap();
|
|
|
|
assert!(ranges.is_empty());
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_request_range_header() {
|
|
|
|
let req = TestRequest::with_header(header::RANGE, "bytes=0-4").finish();
|
|
|
|
let ranges = req.range(100).unwrap();
|
|
|
|
assert_eq!(ranges.len(), 1);
|
|
|
|
assert_eq!(ranges[0].start, 0);
|
|
|
|
assert_eq!(ranges[0].length, 5);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_chunked() {
|
|
|
|
let req = HttpRequest::default();
|
|
|
|
assert!(!req.chunked().unwrap());
|
|
|
|
|
2018-04-14 01:02:01 +02:00
|
|
|
let req =
|
|
|
|
TestRequest::with_header(header::TRANSFER_ENCODING, "chunked").finish();
|
2018-02-28 00:03:28 +01:00
|
|
|
assert!(req.chunked().unwrap());
|
|
|
|
|
|
|
|
let mut headers = HeaderMap::new();
|
2018-04-14 01:02:01 +02:00
|
|
|
let s = unsafe {
|
|
|
|
str::from_utf8_unchecked(b"some va\xadscc\xacas0xsdasdlue".as_ref())
|
|
|
|
};
|
|
|
|
|
|
|
|
headers.insert(
|
|
|
|
header::TRANSFER_ENCODING,
|
|
|
|
header::HeaderValue::from_str(s).unwrap(),
|
|
|
|
);
|
2018-02-28 00:03:28 +01:00
|
|
|
let req = HttpRequest::new(
|
2018-04-14 01:02:01 +02:00
|
|
|
Method::GET,
|
|
|
|
Uri::from_str("/").unwrap(),
|
|
|
|
Version::HTTP_11,
|
|
|
|
headers,
|
|
|
|
None,
|
|
|
|
);
|
2018-02-28 00:03:28 +01:00
|
|
|
assert!(req.chunked().is_err());
|
|
|
|
}
|
|
|
|
|
|
|
|
impl PartialEq for UrlencodedError {
|
|
|
|
fn eq(&self, other: &UrlencodedError) -> bool {
|
|
|
|
match *self {
|
|
|
|
UrlencodedError::Chunked => match *other {
|
|
|
|
UrlencodedError::Chunked => true,
|
|
|
|
_ => false,
|
|
|
|
},
|
|
|
|
UrlencodedError::Overflow => match *other {
|
|
|
|
UrlencodedError::Overflow => true,
|
|
|
|
_ => false,
|
|
|
|
},
|
|
|
|
UrlencodedError::UnknownLength => match *other {
|
|
|
|
UrlencodedError::UnknownLength => true,
|
|
|
|
_ => false,
|
|
|
|
},
|
|
|
|
UrlencodedError::ContentType => match *other {
|
|
|
|
UrlencodedError::ContentType => true,
|
|
|
|
_ => false,
|
|
|
|
},
|
|
|
|
_ => false,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-04-02 23:00:18 +02:00
|
|
|
#[derive(Deserialize, Debug, PartialEq)]
|
|
|
|
struct Info {
|
|
|
|
hello: String,
|
|
|
|
}
|
|
|
|
|
2018-02-28 00:03:28 +01:00
|
|
|
#[test]
|
|
|
|
fn test_urlencoded_error() {
|
|
|
|
let req = TestRequest::with_header(
|
2018-04-14 01:02:01 +02:00
|
|
|
header::CONTENT_TYPE,
|
|
|
|
"application/x-www-form-urlencoded",
|
|
|
|
).header(header::CONTENT_LENGTH, "xxxx")
|
2018-02-28 00:03:28 +01:00
|
|
|
.finish();
|
2018-04-14 01:02:01 +02:00
|
|
|
assert_eq!(
|
|
|
|
req.urlencoded::<Info>().poll().err().unwrap(),
|
|
|
|
UrlencodedError::UnknownLength
|
|
|
|
);
|
2018-02-28 00:03:28 +01:00
|
|
|
|
|
|
|
let req = TestRequest::with_header(
|
2018-04-14 01:02:01 +02:00
|
|
|
header::CONTENT_TYPE,
|
|
|
|
"application/x-www-form-urlencoded",
|
|
|
|
).header(header::CONTENT_LENGTH, "1000000")
|
2018-02-28 00:03:28 +01:00
|
|
|
.finish();
|
2018-04-14 01:02:01 +02:00
|
|
|
assert_eq!(
|
|
|
|
req.urlencoded::<Info>().poll().err().unwrap(),
|
|
|
|
UrlencodedError::Overflow
|
|
|
|
);
|
2018-02-28 00:03:28 +01:00
|
|
|
|
2018-04-14 01:02:01 +02:00
|
|
|
let req = TestRequest::with_header(header::CONTENT_TYPE, "text/plain")
|
2018-02-28 00:03:28 +01:00
|
|
|
.header(header::CONTENT_LENGTH, "10")
|
|
|
|
.finish();
|
2018-04-14 01:02:01 +02:00
|
|
|
assert_eq!(
|
|
|
|
req.urlencoded::<Info>().poll().err().unwrap(),
|
|
|
|
UrlencodedError::ContentType
|
|
|
|
);
|
2018-02-28 00:03:28 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_urlencoded() {
|
|
|
|
let mut req = TestRequest::with_header(
|
2018-04-14 01:02:01 +02:00
|
|
|
header::CONTENT_TYPE,
|
|
|
|
"application/x-www-form-urlencoded",
|
|
|
|
).header(header::CONTENT_LENGTH, "11")
|
2018-02-28 00:03:28 +01:00
|
|
|
.finish();
|
2018-04-29 18:09:08 +02:00
|
|
|
req.payload_mut()
|
|
|
|
.unread_data(Bytes::from_static(b"hello=world"));
|
2018-02-28 00:03:28 +01:00
|
|
|
|
2018-04-02 23:00:18 +02:00
|
|
|
let result = req.urlencoded::<Info>().poll().ok().unwrap();
|
2018-04-14 01:02:01 +02:00
|
|
|
assert_eq!(
|
|
|
|
result,
|
|
|
|
Async::Ready(Info {
|
|
|
|
hello: "world".to_owned()
|
|
|
|
})
|
|
|
|
);
|
2018-02-28 00:03:28 +01:00
|
|
|
|
|
|
|
let mut req = TestRequest::with_header(
|
2018-04-14 01:02:01 +02:00
|
|
|
header::CONTENT_TYPE,
|
|
|
|
"application/x-www-form-urlencoded; charset=utf-8",
|
|
|
|
).header(header::CONTENT_LENGTH, "11")
|
2018-02-28 00:03:28 +01:00
|
|
|
.finish();
|
2018-04-29 18:09:08 +02:00
|
|
|
req.payload_mut()
|
|
|
|
.unread_data(Bytes::from_static(b"hello=world"));
|
2018-02-28 00:03:28 +01:00
|
|
|
|
|
|
|
let result = req.urlencoded().poll().ok().unwrap();
|
2018-04-14 01:02:01 +02:00
|
|
|
assert_eq!(
|
|
|
|
result,
|
|
|
|
Async::Ready(Info {
|
|
|
|
hello: "world".to_owned()
|
|
|
|
})
|
|
|
|
);
|
2018-04-02 23:00:18 +02:00
|
|
|
}
|
|
|
|
|
2018-02-28 00:03:28 +01:00
|
|
|
#[test]
|
|
|
|
fn test_message_body() {
|
|
|
|
let req = TestRequest::with_header(header::CONTENT_LENGTH, "xxxx").finish();
|
|
|
|
match req.body().poll().err().unwrap() {
|
|
|
|
PayloadError::UnknownLength => (),
|
2018-03-30 00:55:27 +02:00
|
|
|
_ => unreachable!("error"),
|
2018-02-28 00:03:28 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
let req = TestRequest::with_header(header::CONTENT_LENGTH, "1000000").finish();
|
|
|
|
match req.body().poll().err().unwrap() {
|
|
|
|
PayloadError::Overflow => (),
|
2018-03-30 00:55:27 +02:00
|
|
|
_ => unreachable!("error"),
|
2018-02-28 00:03:28 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
let mut req = HttpRequest::default();
|
2018-05-17 21:20:20 +02:00
|
|
|
req.payload_mut().unread_data(Bytes::from_static(b"test"));
|
2018-02-28 00:03:28 +01:00
|
|
|
match req.body().poll().ok().unwrap() {
|
|
|
|
Async::Ready(bytes) => assert_eq!(bytes, Bytes::from_static(b"test")),
|
2018-03-30 00:55:27 +02:00
|
|
|
_ => unreachable!("error"),
|
2018-02-28 00:03:28 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
let mut req = HttpRequest::default();
|
2018-04-29 18:09:08 +02:00
|
|
|
req.payload_mut()
|
|
|
|
.unread_data(Bytes::from_static(b"11111111111111"));
|
2018-02-28 00:03:28 +01:00
|
|
|
match req.body().limit(5).poll().err().unwrap() {
|
|
|
|
PayloadError::Overflow => (),
|
2018-03-30 00:55:27 +02:00
|
|
|
_ => unreachable!("error"),
|
2018-02-28 00:03:28 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|