2018-06-06 17:37:04 +00:00
|
|
|
use std::rc::Rc;
|
2017-05-27 02:48:50 +00:00
|
|
|
use std::cell::{Cell, RefCell};
|
2017-12-24 22:12:21 +00:00
|
|
|
use std::net::{IpAddr, SocketAddr};
|
2016-08-27 01:37:28 +00:00
|
|
|
use std::fmt;
|
2017-03-11 01:42:09 +00:00
|
|
|
use std::str;
|
2016-08-27 01:37:28 +00:00
|
|
|
|
2017-06-02 04:44:31 +00:00
|
|
|
use yansi::Paint;
|
2017-04-13 09:36:51 +00:00
|
|
|
use state::{Container, Storage};
|
2017-01-21 03:31:46 +00:00
|
|
|
|
2019-06-13 01:48:02 +00:00
|
|
|
use crate::request::{FromParam, FromSegments, FromRequest, Outcome};
|
|
|
|
use crate::request::{FromFormValue, FormItems, FormItem};
|
2016-03-15 03:43:52 +00:00
|
|
|
|
2019-06-13 01:48:02 +00:00
|
|
|
use crate::rocket::Rocket;
|
|
|
|
use crate::router::Route;
|
|
|
|
use crate::config::{Config, Limits};
|
|
|
|
use crate::http::{hyper, uri::{Origin, Segments}};
|
|
|
|
use crate::http::{Method, Header, HeaderMap, Cookies};
|
|
|
|
use crate::http::{RawStr, ContentType, Accept, MediaType};
|
|
|
|
use crate::http::private::{Indexed, SmallVec, CookieJar};
|
2016-08-26 08:55:11 +00:00
|
|
|
|
2018-09-20 04:14:30 +00:00
|
|
|
type Indices = (usize, usize);
|
2017-03-28 10:10:18 +00:00
|
|
|
|
2016-10-21 09:56:57 +00:00
|
|
|
/// The type of an incoming web request.
|
2016-10-01 03:22:06 +00:00
|
|
|
///
|
|
|
|
/// This should be used sparingly in Rocket applications. In particular, it
|
2018-10-06 13:25:17 +00:00
|
|
|
/// should likely only be used when writing [`FromRequest`] implementations. It
|
2016-12-21 09:30:45 +00:00
|
|
|
/// contains all of the information for a given web request except for the body
|
|
|
|
/// data. This includes the HTTP method, URI, cookies, headers, and more.
|
2017-06-06 20:41:04 +00:00
|
|
|
#[derive(Clone)]
|
2016-12-16 11:07:23 +00:00
|
|
|
pub struct Request<'r> {
|
2018-02-04 10:07:28 +00:00
|
|
|
method: Cell<Method>,
|
Overhaul URI types.
This is fairly large commit with several entangled logical changes.
The primary change in this commit is to completely overhaul how URI
handling in Rocket works. Prior to this commit, the `Uri` type acted as
an origin API. Its parser was minimal and lenient, allowing URIs that
were invalid according to RFC 7230. By contrast, the new `Uri` type
brings with it a strict RFC 7230 compliant parser. The `Uri` type now
represents any kind of valid URI, not simply `Origin` types. Three new
URI types were introduced:
* `Origin` - represents valid origin URIs
* `Absolute` - represents valid absolute URIs
* `Authority` - represents valid authority URIs
The `Origin` type replaces `Uri` in many cases:
* As fields and method inputs of `Route`
* The `&Uri` request guard is now `&Origin`
* The `uri!` macro produces an `Origin` instead of a `Uri`
The strict nature of URI parsing cascaded into the following changes:
* Several `Route` methods now `panic!` on invalid URIs
* The `Rocket::mount()` method is (correctly) stricter with URIs
* The `Redirect` constructors take a `TryInto<Uri>` type
* Dispatching of a `LocalRequest` correctly validates URIs
Overall, URIs are now properly and uniformly handled throughout Rocket's
codebase, resulting in a more reliable and correct system.
In addition to these URI changes, the following changes are also part of
this commit:
* The `LocalRequest::cloned_dispatch()` method was removed in favor of
chaining `.clone().dispatch()`.
* The entire Rocket codebase uses `crate` instead of `pub(crate)` as a
visibility modifier.
* Rocket uses the `crate_visibility_modifier` and `try_from` features.
A note on unsafety: this commit introduces many uses of `unsafe` in the
URI parser. All of these uses are a result of unsafely transforming byte
slices (`&[u8]` or similar) into strings (`&str`). The parser ensures
that these casts are safe, but of course, we must label their use
`unsafe`. The parser was written to be as generic and efficient as
possible and thus can parse directly from byte sources. Rocket, however,
does not make use of this fact and so would be able to remove all uses
of `unsafe` by parsing from an existing `&str`. This should be
considered in the future.
Fixes #443.
Resolves #263.
2018-07-29 01:26:15 +00:00
|
|
|
uri: Origin<'r>,
|
2016-12-16 11:07:23 +00:00
|
|
|
headers: HeaderMap<'r>,
|
2017-01-13 15:50:51 +00:00
|
|
|
remote: Option<SocketAddr>,
|
2018-09-20 04:14:30 +00:00
|
|
|
crate state: RequestState<'r>,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Clone)]
|
|
|
|
crate struct RequestState<'r> {
|
|
|
|
crate config: &'r Config,
|
|
|
|
crate managed: &'r Container,
|
|
|
|
crate path_segments: SmallVec<[Indices; 12]>,
|
|
|
|
crate query_items: Option<SmallVec<[IndexedFormItem; 6]>>,
|
|
|
|
crate route: Cell<Option<&'r Route>>,
|
|
|
|
crate cookies: RefCell<CookieJar>,
|
|
|
|
crate accept: Storage<Option<Accept>>,
|
|
|
|
crate content_type: Storage<Option<ContentType>>,
|
|
|
|
crate cache: Rc<Container>,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Clone)]
|
|
|
|
crate struct IndexedFormItem {
|
|
|
|
raw: Indices,
|
|
|
|
key: Indices,
|
|
|
|
value: Indices
|
2016-03-22 05:04:39 +00:00
|
|
|
}
|
|
|
|
|
2016-12-16 11:07:23 +00:00
|
|
|
impl<'r> Request<'r> {
|
Overhaul URI types.
This is fairly large commit with several entangled logical changes.
The primary change in this commit is to completely overhaul how URI
handling in Rocket works. Prior to this commit, the `Uri` type acted as
an origin API. Its parser was minimal and lenient, allowing URIs that
were invalid according to RFC 7230. By contrast, the new `Uri` type
brings with it a strict RFC 7230 compliant parser. The `Uri` type now
represents any kind of valid URI, not simply `Origin` types. Three new
URI types were introduced:
* `Origin` - represents valid origin URIs
* `Absolute` - represents valid absolute URIs
* `Authority` - represents valid authority URIs
The `Origin` type replaces `Uri` in many cases:
* As fields and method inputs of `Route`
* The `&Uri` request guard is now `&Origin`
* The `uri!` macro produces an `Origin` instead of a `Uri`
The strict nature of URI parsing cascaded into the following changes:
* Several `Route` methods now `panic!` on invalid URIs
* The `Rocket::mount()` method is (correctly) stricter with URIs
* The `Redirect` constructors take a `TryInto<Uri>` type
* Dispatching of a `LocalRequest` correctly validates URIs
Overall, URIs are now properly and uniformly handled throughout Rocket's
codebase, resulting in a more reliable and correct system.
In addition to these URI changes, the following changes are also part of
this commit:
* The `LocalRequest::cloned_dispatch()` method was removed in favor of
chaining `.clone().dispatch()`.
* The entire Rocket codebase uses `crate` instead of `pub(crate)` as a
visibility modifier.
* Rocket uses the `crate_visibility_modifier` and `try_from` features.
A note on unsafety: this commit introduces many uses of `unsafe` in the
URI parser. All of these uses are a result of unsafely transforming byte
slices (`&[u8]` or similar) into strings (`&str`). The parser ensures
that these casts are safe, but of course, we must label their use
`unsafe`. The parser was written to be as generic and efficient as
possible and thus can parse directly from byte sources. Rocket, however,
does not make use of this fact and so would be able to remove all uses
of `unsafe` by parsing from an existing `&str`. This should be
considered in the future.
Fixes #443.
Resolves #263.
2018-07-29 01:26:15 +00:00
|
|
|
/// Create a new `Request` with the given `method` and `uri`.
|
2017-03-28 10:10:18 +00:00
|
|
|
#[inline(always)]
|
Overhaul URI types.
This is fairly large commit with several entangled logical changes.
The primary change in this commit is to completely overhaul how URI
handling in Rocket works. Prior to this commit, the `Uri` type acted as
an origin API. Its parser was minimal and lenient, allowing URIs that
were invalid according to RFC 7230. By contrast, the new `Uri` type
brings with it a strict RFC 7230 compliant parser. The `Uri` type now
represents any kind of valid URI, not simply `Origin` types. Three new
URI types were introduced:
* `Origin` - represents valid origin URIs
* `Absolute` - represents valid absolute URIs
* `Authority` - represents valid authority URIs
The `Origin` type replaces `Uri` in many cases:
* As fields and method inputs of `Route`
* The `&Uri` request guard is now `&Origin`
* The `uri!` macro produces an `Origin` instead of a `Uri`
The strict nature of URI parsing cascaded into the following changes:
* Several `Route` methods now `panic!` on invalid URIs
* The `Rocket::mount()` method is (correctly) stricter with URIs
* The `Redirect` constructors take a `TryInto<Uri>` type
* Dispatching of a `LocalRequest` correctly validates URIs
Overall, URIs are now properly and uniformly handled throughout Rocket's
codebase, resulting in a more reliable and correct system.
In addition to these URI changes, the following changes are also part of
this commit:
* The `LocalRequest::cloned_dispatch()` method was removed in favor of
chaining `.clone().dispatch()`.
* The entire Rocket codebase uses `crate` instead of `pub(crate)` as a
visibility modifier.
* Rocket uses the `crate_visibility_modifier` and `try_from` features.
A note on unsafety: this commit introduces many uses of `unsafe` in the
URI parser. All of these uses are a result of unsafely transforming byte
slices (`&[u8]` or similar) into strings (`&str`). The parser ensures
that these casts are safe, but of course, we must label their use
`unsafe`. The parser was written to be as generic and efficient as
possible and thus can parse directly from byte sources. Rocket, however,
does not make use of this fact and so would be able to remove all uses
of `unsafe` by parsing from an existing `&str`. This should be
considered in the future.
Fixes #443.
Resolves #263.
2018-07-29 01:26:15 +00:00
|
|
|
crate fn new<'s: 'r>(
|
2018-04-08 23:14:15 +00:00
|
|
|
rocket: &'r Rocket,
|
|
|
|
method: Method,
|
Overhaul URI types.
This is fairly large commit with several entangled logical changes.
The primary change in this commit is to completely overhaul how URI
handling in Rocket works. Prior to this commit, the `Uri` type acted as
an origin API. Its parser was minimal and lenient, allowing URIs that
were invalid according to RFC 7230. By contrast, the new `Uri` type
brings with it a strict RFC 7230 compliant parser. The `Uri` type now
represents any kind of valid URI, not simply `Origin` types. Three new
URI types were introduced:
* `Origin` - represents valid origin URIs
* `Absolute` - represents valid absolute URIs
* `Authority` - represents valid authority URIs
The `Origin` type replaces `Uri` in many cases:
* As fields and method inputs of `Route`
* The `&Uri` request guard is now `&Origin`
* The `uri!` macro produces an `Origin` instead of a `Uri`
The strict nature of URI parsing cascaded into the following changes:
* Several `Route` methods now `panic!` on invalid URIs
* The `Rocket::mount()` method is (correctly) stricter with URIs
* The `Redirect` constructors take a `TryInto<Uri>` type
* Dispatching of a `LocalRequest` correctly validates URIs
Overall, URIs are now properly and uniformly handled throughout Rocket's
codebase, resulting in a more reliable and correct system.
In addition to these URI changes, the following changes are also part of
this commit:
* The `LocalRequest::cloned_dispatch()` method was removed in favor of
chaining `.clone().dispatch()`.
* The entire Rocket codebase uses `crate` instead of `pub(crate)` as a
visibility modifier.
* Rocket uses the `crate_visibility_modifier` and `try_from` features.
A note on unsafety: this commit introduces many uses of `unsafe` in the
URI parser. All of these uses are a result of unsafely transforming byte
slices (`&[u8]` or similar) into strings (`&str`). The parser ensures
that these casts are safe, but of course, we must label their use
`unsafe`. The parser was written to be as generic and efficient as
possible and thus can parse directly from byte sources. Rocket, however,
does not make use of this fact and so would be able to remove all uses
of `unsafe` by parsing from an existing `&str`. This should be
considered in the future.
Fixes #443.
Resolves #263.
2018-07-29 01:26:15 +00:00
|
|
|
uri: Origin<'s>
|
2018-04-08 23:14:15 +00:00
|
|
|
) -> Request<'r> {
|
2018-09-20 04:14:30 +00:00
|
|
|
let mut request = Request {
|
2018-02-04 10:07:28 +00:00
|
|
|
method: Cell::new(method),
|
Overhaul URI types.
This is fairly large commit with several entangled logical changes.
The primary change in this commit is to completely overhaul how URI
handling in Rocket works. Prior to this commit, the `Uri` type acted as
an origin API. Its parser was minimal and lenient, allowing URIs that
were invalid according to RFC 7230. By contrast, the new `Uri` type
brings with it a strict RFC 7230 compliant parser. The `Uri` type now
represents any kind of valid URI, not simply `Origin` types. Three new
URI types were introduced:
* `Origin` - represents valid origin URIs
* `Absolute` - represents valid absolute URIs
* `Authority` - represents valid authority URIs
The `Origin` type replaces `Uri` in many cases:
* As fields and method inputs of `Route`
* The `&Uri` request guard is now `&Origin`
* The `uri!` macro produces an `Origin` instead of a `Uri`
The strict nature of URI parsing cascaded into the following changes:
* Several `Route` methods now `panic!` on invalid URIs
* The `Rocket::mount()` method is (correctly) stricter with URIs
* The `Redirect` constructors take a `TryInto<Uri>` type
* Dispatching of a `LocalRequest` correctly validates URIs
Overall, URIs are now properly and uniformly handled throughout Rocket's
codebase, resulting in a more reliable and correct system.
In addition to these URI changes, the following changes are also part of
this commit:
* The `LocalRequest::cloned_dispatch()` method was removed in favor of
chaining `.clone().dispatch()`.
* The entire Rocket codebase uses `crate` instead of `pub(crate)` as a
visibility modifier.
* Rocket uses the `crate_visibility_modifier` and `try_from` features.
A note on unsafety: this commit introduces many uses of `unsafe` in the
URI parser. All of these uses are a result of unsafely transforming byte
slices (`&[u8]` or similar) into strings (`&str`). The parser ensures
that these casts are safe, but of course, we must label their use
`unsafe`. The parser was written to be as generic and efficient as
possible and thus can parse directly from byte sources. Rocket, however,
does not make use of this fact and so would be able to remove all uses
of `unsafe` by parsing from an existing `&str`. This should be
considered in the future.
Fixes #443.
Resolves #263.
2018-07-29 01:26:15 +00:00
|
|
|
uri: uri,
|
2016-12-16 11:07:23 +00:00
|
|
|
headers: HeaderMap::new(),
|
2017-01-13 15:50:51 +00:00
|
|
|
remote: None,
|
2017-05-20 02:38:56 +00:00
|
|
|
state: RequestState {
|
2018-09-20 04:14:30 +00:00
|
|
|
path_segments: SmallVec::new(),
|
|
|
|
query_items: None,
|
2017-06-06 20:41:04 +00:00
|
|
|
config: &rocket.config,
|
2017-12-27 04:27:47 +00:00
|
|
|
managed: &rocket.state,
|
2017-05-27 02:48:50 +00:00
|
|
|
route: Cell::new(None),
|
2017-03-28 10:10:18 +00:00
|
|
|
cookies: RefCell::new(CookieJar::new()),
|
2017-04-13 09:36:51 +00:00
|
|
|
accept: Storage::new(),
|
|
|
|
content_type: Storage::new(),
|
2018-06-06 17:37:04 +00:00
|
|
|
cache: Rc::new(Container::new()),
|
2017-03-28 10:10:18 +00:00
|
|
|
}
|
2018-09-20 04:14:30 +00:00
|
|
|
};
|
2016-12-16 11:07:23 +00:00
|
|
|
|
2018-09-20 04:14:30 +00:00
|
|
|
request.update_cached_uri_info();
|
|
|
|
request
|
2017-06-06 20:41:04 +00:00
|
|
|
}
|
|
|
|
|
2016-12-21 09:30:45 +00:00
|
|
|
/// Retrieve the method from `self`.
|
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
|
|
|
/// ```rust
|
2017-06-06 20:41:04 +00:00
|
|
|
/// # use rocket::Request;
|
2016-12-21 09:30:45 +00:00
|
|
|
/// use rocket::http::Method;
|
|
|
|
///
|
2017-06-06 20:41:04 +00:00
|
|
|
/// # Request::example(Method::Get, "/uri", |request| {
|
2017-06-25 04:00:50 +00:00
|
|
|
/// request.set_method(Method::Get);
|
2016-12-21 09:30:45 +00:00
|
|
|
/// assert_eq!(request.method(), Method::Get);
|
2017-06-06 20:41:04 +00:00
|
|
|
/// # });
|
2016-12-21 09:30:45 +00:00
|
|
|
/// ```
|
2016-12-16 11:07:23 +00:00
|
|
|
#[inline(always)]
|
|
|
|
pub fn method(&self) -> Method {
|
2018-02-04 10:07:28 +00:00
|
|
|
self.method.get()
|
2016-12-16 11:07:23 +00:00
|
|
|
}
|
|
|
|
|
2016-12-21 09:30:45 +00:00
|
|
|
/// Set the method of `self`.
|
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
|
|
|
/// ```rust
|
2017-06-06 20:41:04 +00:00
|
|
|
/// # use rocket::Request;
|
2016-12-21 09:30:45 +00:00
|
|
|
/// use rocket::http::Method;
|
|
|
|
///
|
2017-06-06 20:41:04 +00:00
|
|
|
/// # Request::example(Method::Get, "/uri", |request| {
|
2016-12-21 09:30:45 +00:00
|
|
|
/// assert_eq!(request.method(), Method::Get);
|
|
|
|
///
|
|
|
|
/// request.set_method(Method::Post);
|
|
|
|
/// assert_eq!(request.method(), Method::Post);
|
2017-06-06 20:41:04 +00:00
|
|
|
/// # });
|
2016-12-21 09:30:45 +00:00
|
|
|
/// ```
|
2016-12-16 11:07:23 +00:00
|
|
|
#[inline(always)]
|
|
|
|
pub fn set_method(&mut self, method: Method) {
|
2018-04-08 23:14:15 +00:00
|
|
|
self._set_method(method);
|
2016-12-16 11:07:23 +00:00
|
|
|
}
|
|
|
|
|
2018-10-06 13:25:17 +00:00
|
|
|
/// Borrow the [`Origin`] URI from `self`.
|
2016-12-21 09:30:45 +00:00
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
|
|
|
/// ```rust
|
2017-06-06 20:41:04 +00:00
|
|
|
/// # use rocket::Request;
|
|
|
|
/// # use rocket::http::Method;
|
|
|
|
/// # Request::example(Method::Get, "/uri", |request| {
|
Overhaul URI types.
This is fairly large commit with several entangled logical changes.
The primary change in this commit is to completely overhaul how URI
handling in Rocket works. Prior to this commit, the `Uri` type acted as
an origin API. Its parser was minimal and lenient, allowing URIs that
were invalid according to RFC 7230. By contrast, the new `Uri` type
brings with it a strict RFC 7230 compliant parser. The `Uri` type now
represents any kind of valid URI, not simply `Origin` types. Three new
URI types were introduced:
* `Origin` - represents valid origin URIs
* `Absolute` - represents valid absolute URIs
* `Authority` - represents valid authority URIs
The `Origin` type replaces `Uri` in many cases:
* As fields and method inputs of `Route`
* The `&Uri` request guard is now `&Origin`
* The `uri!` macro produces an `Origin` instead of a `Uri`
The strict nature of URI parsing cascaded into the following changes:
* Several `Route` methods now `panic!` on invalid URIs
* The `Rocket::mount()` method is (correctly) stricter with URIs
* The `Redirect` constructors take a `TryInto<Uri>` type
* Dispatching of a `LocalRequest` correctly validates URIs
Overall, URIs are now properly and uniformly handled throughout Rocket's
codebase, resulting in a more reliable and correct system.
In addition to these URI changes, the following changes are also part of
this commit:
* The `LocalRequest::cloned_dispatch()` method was removed in favor of
chaining `.clone().dispatch()`.
* The entire Rocket codebase uses `crate` instead of `pub(crate)` as a
visibility modifier.
* Rocket uses the `crate_visibility_modifier` and `try_from` features.
A note on unsafety: this commit introduces many uses of `unsafe` in the
URI parser. All of these uses are a result of unsafely transforming byte
slices (`&[u8]` or similar) into strings (`&str`). The parser ensures
that these casts are safe, but of course, we must label their use
`unsafe`. The parser was written to be as generic and efficient as
possible and thus can parse directly from byte sources. Rocket, however,
does not make use of this fact and so would be able to remove all uses
of `unsafe` by parsing from an existing `&str`. This should be
considered in the future.
Fixes #443.
Resolves #263.
2018-07-29 01:26:15 +00:00
|
|
|
/// assert_eq!(request.uri().path(), "/uri");
|
2017-06-06 20:41:04 +00:00
|
|
|
/// # });
|
2016-12-21 09:30:45 +00:00
|
|
|
/// ```
|
2016-12-16 11:07:23 +00:00
|
|
|
#[inline(always)]
|
2019-06-13 01:48:02 +00:00
|
|
|
pub fn uri(&self) -> &Origin<'_> {
|
2016-12-21 08:09:22 +00:00
|
|
|
&self.uri
|
2016-12-16 11:07:23 +00:00
|
|
|
}
|
|
|
|
|
Overhaul URI types.
This is fairly large commit with several entangled logical changes.
The primary change in this commit is to completely overhaul how URI
handling in Rocket works. Prior to this commit, the `Uri` type acted as
an origin API. Its parser was minimal and lenient, allowing URIs that
were invalid according to RFC 7230. By contrast, the new `Uri` type
brings with it a strict RFC 7230 compliant parser. The `Uri` type now
represents any kind of valid URI, not simply `Origin` types. Three new
URI types were introduced:
* `Origin` - represents valid origin URIs
* `Absolute` - represents valid absolute URIs
* `Authority` - represents valid authority URIs
The `Origin` type replaces `Uri` in many cases:
* As fields and method inputs of `Route`
* The `&Uri` request guard is now `&Origin`
* The `uri!` macro produces an `Origin` instead of a `Uri`
The strict nature of URI parsing cascaded into the following changes:
* Several `Route` methods now `panic!` on invalid URIs
* The `Rocket::mount()` method is (correctly) stricter with URIs
* The `Redirect` constructors take a `TryInto<Uri>` type
* Dispatching of a `LocalRequest` correctly validates URIs
Overall, URIs are now properly and uniformly handled throughout Rocket's
codebase, resulting in a more reliable and correct system.
In addition to these URI changes, the following changes are also part of
this commit:
* The `LocalRequest::cloned_dispatch()` method was removed in favor of
chaining `.clone().dispatch()`.
* The entire Rocket codebase uses `crate` instead of `pub(crate)` as a
visibility modifier.
* Rocket uses the `crate_visibility_modifier` and `try_from` features.
A note on unsafety: this commit introduces many uses of `unsafe` in the
URI parser. All of these uses are a result of unsafely transforming byte
slices (`&[u8]` or similar) into strings (`&str`). The parser ensures
that these casts are safe, but of course, we must label their use
`unsafe`. The parser was written to be as generic and efficient as
possible and thus can parse directly from byte sources. Rocket, however,
does not make use of this fact and so would be able to remove all uses
of `unsafe` by parsing from an existing `&str`. This should be
considered in the future.
Fixes #443.
Resolves #263.
2018-07-29 01:26:15 +00:00
|
|
|
/// Set the URI in `self` to `uri`.
|
2016-12-21 09:30:45 +00:00
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
|
|
|
/// ```rust
|
Overhaul URI types.
This is fairly large commit with several entangled logical changes.
The primary change in this commit is to completely overhaul how URI
handling in Rocket works. Prior to this commit, the `Uri` type acted as
an origin API. Its parser was minimal and lenient, allowing URIs that
were invalid according to RFC 7230. By contrast, the new `Uri` type
brings with it a strict RFC 7230 compliant parser. The `Uri` type now
represents any kind of valid URI, not simply `Origin` types. Three new
URI types were introduced:
* `Origin` - represents valid origin URIs
* `Absolute` - represents valid absolute URIs
* `Authority` - represents valid authority URIs
The `Origin` type replaces `Uri` in many cases:
* As fields and method inputs of `Route`
* The `&Uri` request guard is now `&Origin`
* The `uri!` macro produces an `Origin` instead of a `Uri`
The strict nature of URI parsing cascaded into the following changes:
* Several `Route` methods now `panic!` on invalid URIs
* The `Rocket::mount()` method is (correctly) stricter with URIs
* The `Redirect` constructors take a `TryInto<Uri>` type
* Dispatching of a `LocalRequest` correctly validates URIs
Overall, URIs are now properly and uniformly handled throughout Rocket's
codebase, resulting in a more reliable and correct system.
In addition to these URI changes, the following changes are also part of
this commit:
* The `LocalRequest::cloned_dispatch()` method was removed in favor of
chaining `.clone().dispatch()`.
* The entire Rocket codebase uses `crate` instead of `pub(crate)` as a
visibility modifier.
* Rocket uses the `crate_visibility_modifier` and `try_from` features.
A note on unsafety: this commit introduces many uses of `unsafe` in the
URI parser. All of these uses are a result of unsafely transforming byte
slices (`&[u8]` or similar) into strings (`&str`). The parser ensures
that these casts are safe, but of course, we must label their use
`unsafe`. The parser was written to be as generic and efficient as
possible and thus can parse directly from byte sources. Rocket, however,
does not make use of this fact and so would be able to remove all uses
of `unsafe` by parsing from an existing `&str`. This should be
considered in the future.
Fixes #443.
Resolves #263.
2018-07-29 01:26:15 +00:00
|
|
|
/// use rocket::http::uri::Origin;
|
|
|
|
///
|
2017-06-06 20:41:04 +00:00
|
|
|
/// # use rocket::Request;
|
|
|
|
/// # use rocket::http::Method;
|
|
|
|
/// # Request::example(Method::Get, "/uri", |mut request| {
|
Overhaul URI types.
This is fairly large commit with several entangled logical changes.
The primary change in this commit is to completely overhaul how URI
handling in Rocket works. Prior to this commit, the `Uri` type acted as
an origin API. Its parser was minimal and lenient, allowing URIs that
were invalid according to RFC 7230. By contrast, the new `Uri` type
brings with it a strict RFC 7230 compliant parser. The `Uri` type now
represents any kind of valid URI, not simply `Origin` types. Three new
URI types were introduced:
* `Origin` - represents valid origin URIs
* `Absolute` - represents valid absolute URIs
* `Authority` - represents valid authority URIs
The `Origin` type replaces `Uri` in many cases:
* As fields and method inputs of `Route`
* The `&Uri` request guard is now `&Origin`
* The `uri!` macro produces an `Origin` instead of a `Uri`
The strict nature of URI parsing cascaded into the following changes:
* Several `Route` methods now `panic!` on invalid URIs
* The `Rocket::mount()` method is (correctly) stricter with URIs
* The `Redirect` constructors take a `TryInto<Uri>` type
* Dispatching of a `LocalRequest` correctly validates URIs
Overall, URIs are now properly and uniformly handled throughout Rocket's
codebase, resulting in a more reliable and correct system.
In addition to these URI changes, the following changes are also part of
this commit:
* The `LocalRequest::cloned_dispatch()` method was removed in favor of
chaining `.clone().dispatch()`.
* The entire Rocket codebase uses `crate` instead of `pub(crate)` as a
visibility modifier.
* Rocket uses the `crate_visibility_modifier` and `try_from` features.
A note on unsafety: this commit introduces many uses of `unsafe` in the
URI parser. All of these uses are a result of unsafely transforming byte
slices (`&[u8]` or similar) into strings (`&str`). The parser ensures
that these casts are safe, but of course, we must label their use
`unsafe`. The parser was written to be as generic and efficient as
possible and thus can parse directly from byte sources. Rocket, however,
does not make use of this fact and so would be able to remove all uses
of `unsafe` by parsing from an existing `&str`. This should be
considered in the future.
Fixes #443.
Resolves #263.
2018-07-29 01:26:15 +00:00
|
|
|
/// let uri = Origin::parse("/hello/Sergio?type=greeting").unwrap();
|
|
|
|
/// request.set_uri(uri);
|
|
|
|
/// assert_eq!(request.uri().path(), "/hello/Sergio");
|
|
|
|
/// assert_eq!(request.uri().query(), Some("type=greeting"));
|
2017-06-06 20:41:04 +00:00
|
|
|
/// # });
|
2016-12-21 09:30:45 +00:00
|
|
|
/// ```
|
Overhaul URI types.
This is fairly large commit with several entangled logical changes.
The primary change in this commit is to completely overhaul how URI
handling in Rocket works. Prior to this commit, the `Uri` type acted as
an origin API. Its parser was minimal and lenient, allowing URIs that
were invalid according to RFC 7230. By contrast, the new `Uri` type
brings with it a strict RFC 7230 compliant parser. The `Uri` type now
represents any kind of valid URI, not simply `Origin` types. Three new
URI types were introduced:
* `Origin` - represents valid origin URIs
* `Absolute` - represents valid absolute URIs
* `Authority` - represents valid authority URIs
The `Origin` type replaces `Uri` in many cases:
* As fields and method inputs of `Route`
* The `&Uri` request guard is now `&Origin`
* The `uri!` macro produces an `Origin` instead of a `Uri`
The strict nature of URI parsing cascaded into the following changes:
* Several `Route` methods now `panic!` on invalid URIs
* The `Rocket::mount()` method is (correctly) stricter with URIs
* The `Redirect` constructors take a `TryInto<Uri>` type
* Dispatching of a `LocalRequest` correctly validates URIs
Overall, URIs are now properly and uniformly handled throughout Rocket's
codebase, resulting in a more reliable and correct system.
In addition to these URI changes, the following changes are also part of
this commit:
* The `LocalRequest::cloned_dispatch()` method was removed in favor of
chaining `.clone().dispatch()`.
* The entire Rocket codebase uses `crate` instead of `pub(crate)` as a
visibility modifier.
* Rocket uses the `crate_visibility_modifier` and `try_from` features.
A note on unsafety: this commit introduces many uses of `unsafe` in the
URI parser. All of these uses are a result of unsafely transforming byte
slices (`&[u8]` or similar) into strings (`&str`). The parser ensures
that these casts are safe, but of course, we must label their use
`unsafe`. The parser was written to be as generic and efficient as
possible and thus can parse directly from byte sources. Rocket, however,
does not make use of this fact and so would be able to remove all uses
of `unsafe` by parsing from an existing `&str`. This should be
considered in the future.
Fixes #443.
Resolves #263.
2018-07-29 01:26:15 +00:00
|
|
|
pub fn set_uri<'u: 'r>(&mut self, uri: Origin<'u>) {
|
|
|
|
self.uri = uri;
|
2018-09-20 04:14:30 +00:00
|
|
|
self.update_cached_uri_info();
|
2016-12-16 11:07:23 +00:00
|
|
|
}
|
|
|
|
|
2017-01-13 15:50:51 +00:00
|
|
|
/// Returns the address of the remote connection that initiated this
|
|
|
|
/// request if the address is known. If the address is not known, `None` is
|
|
|
|
/// returned.
|
|
|
|
///
|
2017-12-29 07:50:59 +00:00
|
|
|
/// Because it is common for proxies to forward connections for clients, the
|
|
|
|
/// remote address may contain information about the proxy instead of the
|
|
|
|
/// client. For this reason, proxies typically set the "X-Real-IP" header
|
|
|
|
/// with the client's true IP. To extract this IP from the request, use the
|
|
|
|
/// [`real_ip()`] or [`client_ip()`] methods.
|
|
|
|
///
|
|
|
|
/// [`real_ip()`]: #method.real_ip
|
|
|
|
/// [`client_ip()`]: #method.client_ip
|
|
|
|
///
|
2017-01-13 15:50:51 +00:00
|
|
|
/// # Example
|
|
|
|
///
|
|
|
|
/// ```rust
|
2017-06-06 20:41:04 +00:00
|
|
|
/// # use rocket::Request;
|
|
|
|
/// # use rocket::http::Method;
|
|
|
|
/// # Request::example(Method::Get, "/uri", |request| {
|
2017-01-13 15:50:51 +00:00
|
|
|
/// assert!(request.remote().is_none());
|
2017-06-06 20:41:04 +00:00
|
|
|
/// # });
|
2017-01-13 15:50:51 +00:00
|
|
|
/// ```
|
|
|
|
#[inline(always)]
|
|
|
|
pub fn remote(&self) -> Option<SocketAddr> {
|
|
|
|
self.remote
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Sets the remote address of `self` to `address`.
|
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
|
|
|
/// Set the remote address to be 127.0.0.1:8000:
|
|
|
|
///
|
|
|
|
/// ```rust
|
2017-06-06 20:41:04 +00:00
|
|
|
/// # use rocket::Request;
|
|
|
|
/// # use rocket::http::Method;
|
2017-01-13 15:50:51 +00:00
|
|
|
/// use std::net::{SocketAddr, IpAddr, Ipv4Addr};
|
|
|
|
///
|
2017-06-06 20:41:04 +00:00
|
|
|
/// # Request::example(Method::Get, "/uri", |mut request| {
|
2017-01-13 15:50:51 +00:00
|
|
|
/// let (ip, port) = (IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8000);
|
|
|
|
/// let localhost = SocketAddr::new(ip, port);
|
|
|
|
/// request.set_remote(localhost);
|
|
|
|
///
|
|
|
|
/// assert_eq!(request.remote(), Some(localhost));
|
2017-06-06 20:41:04 +00:00
|
|
|
/// # });
|
2017-01-13 15:50:51 +00:00
|
|
|
/// ```
|
|
|
|
#[inline(always)]
|
|
|
|
pub fn set_remote(&mut self, address: SocketAddr) {
|
|
|
|
self.remote = Some(address);
|
|
|
|
}
|
|
|
|
|
2017-12-29 07:50:59 +00:00
|
|
|
/// Returns the IP address in the "X-Real-IP" header of the request if such
|
|
|
|
/// a header exists and contains a valid IP address.
|
2017-12-24 22:12:21 +00:00
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// # use rocket::Request;
|
|
|
|
/// # use rocket::http::{Header, Method};
|
|
|
|
/// # use std::net::{SocketAddr, IpAddr, Ipv4Addr};
|
|
|
|
///
|
|
|
|
/// # Request::example(Method::Get, "/uri", |mut request| {
|
|
|
|
/// request.add_header(Header::new("X-Real-IP", "8.8.8.8"));
|
2017-12-29 07:50:59 +00:00
|
|
|
/// assert_eq!(request.real_ip(), Some("8.8.8.8".parse().unwrap()));
|
2017-12-24 22:12:21 +00:00
|
|
|
/// # });
|
|
|
|
/// ```
|
|
|
|
pub fn real_ip(&self) -> Option<IpAddr> {
|
|
|
|
self.headers()
|
|
|
|
.get_one("X-Real-IP")
|
|
|
|
.and_then(|ip| {
|
|
|
|
ip.parse()
|
|
|
|
.map_err(|_| warn_!("'X-Real-IP' header is malformed: {}", ip))
|
|
|
|
.ok()
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2017-12-29 07:50:59 +00:00
|
|
|
/// Attempts to return the client's IP address by first inspecting the
|
|
|
|
/// "X-Real-IP" header and then using the remote connection's IP address.
|
|
|
|
///
|
|
|
|
/// If the "X-Real-IP" header exists and contains a valid IP address, that
|
|
|
|
/// address is returned. Otherwise, if the address of the remote connection
|
|
|
|
/// is known, that address is returned. Otherwise, `None` is returned.
|
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// # use rocket::Request;
|
|
|
|
/// # use rocket::http::{Header, Method};
|
|
|
|
/// # use std::net::{SocketAddr, IpAddr, Ipv4Addr};
|
|
|
|
///
|
|
|
|
/// # Request::example(Method::Get, "/uri", |mut request| {
|
|
|
|
/// // starting without an "X-Real-IP" header or remote addresss
|
|
|
|
/// assert!(request.client_ip().is_none());
|
|
|
|
///
|
|
|
|
/// // add a remote address; this is done by Rocket automatically
|
|
|
|
/// request.set_remote("127.0.0.1:8000".parse().unwrap());
|
|
|
|
/// assert_eq!(request.client_ip(), Some("127.0.0.1".parse().unwrap()));
|
|
|
|
///
|
|
|
|
/// // now with an X-Real-IP header
|
|
|
|
/// request.add_header(Header::new("X-Real-IP", "8.8.8.8"));
|
|
|
|
/// assert_eq!(request.client_ip(), Some("8.8.8.8".parse().unwrap()));
|
|
|
|
/// # });
|
|
|
|
/// ```
|
|
|
|
#[inline]
|
|
|
|
pub fn client_ip(&self) -> Option<IpAddr> {
|
|
|
|
self.real_ip().or_else(|| self.remote().map(|r| r.ip()))
|
|
|
|
}
|
|
|
|
|
2018-09-20 04:14:30 +00:00
|
|
|
/// Returns a wrapped borrow to the cookies in `self`.
|
|
|
|
///
|
2018-10-06 13:25:17 +00:00
|
|
|
/// [`Cookies`] implements internal mutability, so this method allows you to
|
|
|
|
/// get _and_ add/remove cookies in `self`.
|
2018-09-20 04:14:30 +00:00
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
|
|
|
/// Add a new cookie to a request's cookies:
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// # use rocket::Request;
|
|
|
|
/// # use rocket::http::Method;
|
|
|
|
/// use rocket::http::Cookie;
|
|
|
|
///
|
|
|
|
/// # Request::example(Method::Get, "/uri", |mut request| {
|
|
|
|
/// request.cookies().add(Cookie::new("key", "val"));
|
|
|
|
/// request.cookies().add(Cookie::new("ans", format!("life: {}", 38 + 4)));
|
|
|
|
/// # });
|
|
|
|
/// ```
|
2019-06-13 01:48:02 +00:00
|
|
|
pub fn cookies(&self) -> Cookies<'_> {
|
2018-09-20 04:14:30 +00:00
|
|
|
// FIXME: Can we do better? This is disappointing.
|
|
|
|
match self.state.cookies.try_borrow_mut() {
|
|
|
|
Ok(jar) => Cookies::new(jar, self.state.config.secret_key()),
|
|
|
|
Err(_) => {
|
|
|
|
error_!("Multiple `Cookies` instances are active at once.");
|
|
|
|
info_!("An instance of `Cookies` must be dropped before another \
|
|
|
|
can be retrieved.");
|
|
|
|
warn_!("The retrieved `Cookies` instance will be empty.");
|
|
|
|
Cookies::empty()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-10-06 13:25:17 +00:00
|
|
|
/// Returns a [`HeaderMap`] of all of the headers in `self`.
|
2016-12-21 09:30:45 +00:00
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
|
|
|
/// ```rust
|
2017-06-06 20:41:04 +00:00
|
|
|
/// # use rocket::Request;
|
|
|
|
/// # use rocket::http::Method;
|
|
|
|
/// # Request::example(Method::Get, "/uri", |request| {
|
2016-12-21 09:30:45 +00:00
|
|
|
/// let header_map = request.headers();
|
|
|
|
/// assert!(header_map.is_empty());
|
2017-06-06 20:41:04 +00:00
|
|
|
/// # });
|
2016-12-21 09:30:45 +00:00
|
|
|
/// ```
|
|
|
|
#[inline(always)]
|
|
|
|
pub fn headers(&self) -> &HeaderMap<'r> {
|
|
|
|
&self.headers
|
|
|
|
}
|
|
|
|
|
2017-06-25 04:00:50 +00:00
|
|
|
/// Add `header` to `self`'s headers. The type of `header` can be any type
|
|
|
|
/// that implements the `Into<Header>` trait. This includes common types
|
2018-10-06 13:25:17 +00:00
|
|
|
/// such as [`ContentType`] and [`Accept`].
|
2016-12-21 09:30:45 +00:00
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
|
|
|
/// ```rust
|
2017-06-06 20:41:04 +00:00
|
|
|
/// # use rocket::Request;
|
|
|
|
/// # use rocket::http::Method;
|
|
|
|
/// use rocket::http::ContentType;
|
2016-12-21 09:30:45 +00:00
|
|
|
///
|
2017-06-06 20:41:04 +00:00
|
|
|
/// # Request::example(Method::Get, "/uri", |mut request| {
|
2016-12-21 09:30:45 +00:00
|
|
|
/// assert!(request.headers().is_empty());
|
|
|
|
///
|
2017-02-01 11:12:24 +00:00
|
|
|
/// request.add_header(ContentType::HTML);
|
2016-12-21 09:30:45 +00:00
|
|
|
/// assert!(request.headers().contains("Content-Type"));
|
|
|
|
/// assert_eq!(request.headers().len(), 1);
|
2017-06-06 20:41:04 +00:00
|
|
|
/// # });
|
2016-12-21 09:30:45 +00:00
|
|
|
/// ```
|
2016-12-16 11:07:23 +00:00
|
|
|
#[inline(always)]
|
2017-06-06 20:41:04 +00:00
|
|
|
pub fn add_header<'h: 'r, H: Into<Header<'h>>>(&mut self, header: H) {
|
2017-02-01 11:12:24 +00:00
|
|
|
self.headers.add(header.into());
|
2016-12-16 11:07:23 +00:00
|
|
|
}
|
|
|
|
|
2017-06-25 04:00:50 +00:00
|
|
|
/// Replaces the value of the header with name `header.name` with
|
|
|
|
/// `header.value`. If no such header exists, `header` is added as a header
|
|
|
|
/// to `self`.
|
2016-12-21 09:30:45 +00:00
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
|
|
|
/// ```rust
|
2017-06-06 20:41:04 +00:00
|
|
|
/// # use rocket::Request;
|
|
|
|
/// # use rocket::http::Method;
|
|
|
|
/// use rocket::http::ContentType;
|
2016-12-21 09:30:45 +00:00
|
|
|
///
|
2017-06-06 20:41:04 +00:00
|
|
|
/// # Request::example(Method::Get, "/uri", |mut request| {
|
2016-12-21 09:30:45 +00:00
|
|
|
/// assert!(request.headers().is_empty());
|
|
|
|
///
|
2017-04-13 09:36:51 +00:00
|
|
|
/// request.add_header(ContentType::Any);
|
|
|
|
/// assert_eq!(request.headers().get_one("Content-Type"), Some("*/*"));
|
2016-12-21 09:30:45 +00:00
|
|
|
///
|
2017-04-13 09:36:51 +00:00
|
|
|
/// request.replace_header(ContentType::PNG);
|
|
|
|
/// assert_eq!(request.headers().get_one("Content-Type"), Some("image/png"));
|
2017-06-06 20:41:04 +00:00
|
|
|
/// # });
|
2016-12-21 09:30:45 +00:00
|
|
|
/// ```
|
2016-12-16 11:07:23 +00:00
|
|
|
#[inline(always)]
|
2017-06-06 20:41:04 +00:00
|
|
|
pub fn replace_header<'h: 'r, H: Into<Header<'h>>>(&mut self, header: H) {
|
2017-02-01 11:12:24 +00:00
|
|
|
self.headers.replace(header.into());
|
2016-12-16 11:07:23 +00:00
|
|
|
}
|
|
|
|
|
2017-04-14 21:35:22 +00:00
|
|
|
/// Returns the Content-Type header of `self`. If the header is not present,
|
|
|
|
/// returns `None`. The Content-Type header is cached after the first call
|
|
|
|
/// to this function. As a result, subsequent calls will always return the
|
|
|
|
/// same value.
|
2016-12-21 09:30:45 +00:00
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
|
|
|
/// ```rust
|
2017-06-06 20:41:04 +00:00
|
|
|
/// # use rocket::Request;
|
|
|
|
/// # use rocket::http::Method;
|
|
|
|
/// use rocket::http::ContentType;
|
2017-04-13 09:36:51 +00:00
|
|
|
///
|
2017-06-06 20:41:04 +00:00
|
|
|
/// # Request::example(Method::Get, "/uri", |mut request| {
|
2017-04-13 09:36:51 +00:00
|
|
|
/// request.add_header(ContentType::JSON);
|
|
|
|
/// assert_eq!(request.content_type(), Some(&ContentType::JSON));
|
2017-06-25 04:00:50 +00:00
|
|
|
///
|
|
|
|
/// // The header is cached; it cannot be replaced after first access.
|
|
|
|
/// request.replace_header(ContentType::HTML);
|
|
|
|
/// assert_eq!(request.content_type(), Some(&ContentType::JSON));
|
2017-06-06 20:41:04 +00:00
|
|
|
/// # });
|
2016-12-21 09:30:45 +00:00
|
|
|
/// ```
|
2016-12-16 11:07:23 +00:00
|
|
|
#[inline(always)]
|
2017-04-13 09:36:51 +00:00
|
|
|
pub fn content_type(&self) -> Option<&ContentType> {
|
2017-05-20 02:38:56 +00:00
|
|
|
self.state.content_type.get_or_set(|| {
|
2017-04-13 09:36:51 +00:00
|
|
|
self.headers().get_one("Content-Type").and_then(|v| v.parse().ok())
|
|
|
|
}).as_ref()
|
2017-03-28 10:10:18 +00:00
|
|
|
}
|
|
|
|
|
2017-06-25 04:00:50 +00:00
|
|
|
/// Returns the Accept header of `self`. If the header is not present,
|
|
|
|
/// returns `None`. The Accept header is cached after the first call to this
|
|
|
|
/// function. As a result, subsequent calls will always return the same
|
|
|
|
/// value.
|
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// # use rocket::Request;
|
|
|
|
/// # use rocket::http::Method;
|
|
|
|
/// use rocket::http::Accept;
|
|
|
|
///
|
|
|
|
/// # Request::example(Method::Get, "/uri", |mut request| {
|
|
|
|
/// request.add_header(Accept::JSON);
|
|
|
|
/// assert_eq!(request.accept(), Some(&Accept::JSON));
|
|
|
|
///
|
|
|
|
/// // The header is cached; it cannot be replaced after first access.
|
|
|
|
/// request.replace_header(Accept::HTML);
|
|
|
|
/// assert_eq!(request.accept(), Some(&Accept::JSON));
|
|
|
|
/// # });
|
|
|
|
/// ```
|
2017-03-28 10:10:18 +00:00
|
|
|
#[inline(always)]
|
2017-04-13 09:36:51 +00:00
|
|
|
pub fn accept(&self) -> Option<&Accept> {
|
2017-05-20 02:38:56 +00:00
|
|
|
self.state.accept.get_or_set(|| {
|
2017-04-13 09:36:51 +00:00
|
|
|
self.headers().get_one("Accept").and_then(|v| v.parse().ok())
|
|
|
|
}).as_ref()
|
2017-03-28 10:10:18 +00:00
|
|
|
}
|
|
|
|
|
2018-10-05 04:44:42 +00:00
|
|
|
/// Returns the media type "format" of the request.
|
2017-06-25 04:00:50 +00:00
|
|
|
///
|
|
|
|
/// The "format" of a request is either the Content-Type, if the request
|
|
|
|
/// methods indicates support for a payload, or the preferred media type in
|
2018-10-05 04:44:42 +00:00
|
|
|
/// the Accept header otherwise. If the method indicates no payload and no
|
|
|
|
/// Accept header is specified, a media type of `Any` is returned.
|
2017-06-25 04:00:50 +00:00
|
|
|
///
|
|
|
|
/// The media type returned from this method is used to match against the
|
|
|
|
/// `format` route attribute.
|
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// # use rocket::Request;
|
|
|
|
/// use rocket::http::{Method, Accept, ContentType, MediaType};
|
|
|
|
///
|
|
|
|
/// # Request::example(Method::Get, "/uri", |mut request| {
|
|
|
|
/// request.add_header(ContentType::JSON);
|
|
|
|
/// request.add_header(Accept::HTML);
|
|
|
|
///
|
|
|
|
/// request.set_method(Method::Get);
|
|
|
|
/// assert_eq!(request.format(), Some(&MediaType::HTML));
|
|
|
|
///
|
|
|
|
/// request.set_method(Method::Post);
|
|
|
|
/// assert_eq!(request.format(), Some(&MediaType::JSON));
|
|
|
|
/// # });
|
|
|
|
/// ```
|
2017-04-13 09:36:51 +00:00
|
|
|
pub fn format(&self) -> Option<&MediaType> {
|
2018-10-05 04:44:42 +00:00
|
|
|
static ANY: MediaType = MediaType::Any;
|
2018-02-04 10:07:28 +00:00
|
|
|
if self.method().supports_payload() {
|
2017-04-13 09:36:51 +00:00
|
|
|
self.content_type().map(|ct| ct.media_type())
|
2017-03-29 11:08:53 +00:00
|
|
|
} else {
|
|
|
|
// FIXME: Should we be using `accept_first` or `preferred`? Or
|
|
|
|
// should we be checking neither and instead pass things through
|
|
|
|
// where the client accepts the thing at all?
|
2018-10-05 04:44:42 +00:00
|
|
|
self.accept()
|
|
|
|
.map(|accept| accept.preferred().media_type())
|
|
|
|
.or(Some(&ANY))
|
2017-03-29 11:08:53 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-06-25 04:00:50 +00:00
|
|
|
/// Returns the configured application receive limits.
|
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// # use rocket::Request;
|
|
|
|
/// # use rocket::http::Method;
|
|
|
|
/// # Request::example(Method::Get, "/uri", |mut request| {
|
|
|
|
/// let json_limit = request.limits().get("json");
|
|
|
|
/// # });
|
|
|
|
/// ```
|
2017-05-27 02:48:50 +00:00
|
|
|
pub fn limits(&self) -> &'r Limits {
|
2017-06-06 20:41:04 +00:00
|
|
|
&self.state.config.limits
|
2017-05-27 02:48:50 +00:00
|
|
|
}
|
|
|
|
|
2017-06-25 04:00:50 +00:00
|
|
|
/// Get the presently matched route, if any.
|
|
|
|
///
|
|
|
|
/// This method returns `Some` any time a handler or its guards are being
|
|
|
|
/// invoked. This method returns `None` _before_ routing has commenced; this
|
|
|
|
/// includes during request fairing callbacks.
|
|
|
|
///
|
|
|
|
/// # Example
|
2017-05-27 02:48:50 +00:00
|
|
|
///
|
2017-06-25 04:00:50 +00:00
|
|
|
/// ```rust
|
|
|
|
/// # use rocket::Request;
|
|
|
|
/// # use rocket::http::Method;
|
|
|
|
/// # Request::example(Method::Get, "/uri", |mut request| {
|
|
|
|
/// let route = request.route();
|
|
|
|
/// # });
|
|
|
|
/// ```
|
2017-05-27 02:48:50 +00:00
|
|
|
pub fn route(&self) -> Option<&'r Route> {
|
|
|
|
self.state.route.get()
|
|
|
|
}
|
|
|
|
|
2018-07-12 03:44:09 +00:00
|
|
|
/// Invokes the request guard implementation for `T`, returning its outcome.
|
2017-06-25 04:00:50 +00:00
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
2017-08-13 10:13:20 +00:00
|
|
|
/// Assuming a `User` request guard exists, invoke it:
|
2017-06-25 04:00:50 +00:00
|
|
|
///
|
2018-10-06 13:25:17 +00:00
|
|
|
/// ```rust
|
|
|
|
/// # use rocket::Request;
|
|
|
|
/// # use rocket::http::Method;
|
|
|
|
/// # type User = Method;
|
|
|
|
/// # Request::example(Method::Get, "/uri", |request| {
|
2017-08-13 10:13:20 +00:00
|
|
|
/// let outcome = request.guard::<User>();
|
2018-10-06 13:25:17 +00:00
|
|
|
/// # });
|
2017-06-25 04:00:50 +00:00
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// Retrieve managed state inside of a guard implementation:
|
|
|
|
///
|
2018-10-06 13:25:17 +00:00
|
|
|
/// ```rust
|
|
|
|
/// # use rocket::Request;
|
|
|
|
/// # use rocket::http::Method;
|
2017-06-25 04:00:50 +00:00
|
|
|
/// use rocket::State;
|
|
|
|
///
|
2018-10-06 13:25:17 +00:00
|
|
|
/// # type Pool = usize;
|
|
|
|
/// # Request::example(Method::Get, "/uri", |request| {
|
|
|
|
/// let pool = request.guard::<State<Pool>>();
|
|
|
|
/// # });
|
2017-06-25 04:00:50 +00:00
|
|
|
/// ```
|
|
|
|
#[inline(always)]
|
|
|
|
pub fn guard<'a, T: FromRequest<'a, 'r>>(&'a self) -> Outcome<T, T::Error> {
|
|
|
|
T::from_request(self)
|
|
|
|
}
|
|
|
|
|
2018-08-13 07:45:18 +00:00
|
|
|
/// Retrieves the cached value for type `T` from the request-local cached
|
|
|
|
/// state of `self`. If no such value has previously been cached for this
|
|
|
|
/// request, `f` is called to produce the value which is subsequently
|
|
|
|
/// returned.
|
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// # use rocket::http::Method;
|
|
|
|
/// # use rocket::Request;
|
2018-10-06 13:25:17 +00:00
|
|
|
/// # type User = ();
|
2018-08-13 07:45:18 +00:00
|
|
|
/// fn current_user(request: &Request) -> User {
|
|
|
|
/// // Validate request for a given user, load from database, etc.
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// # Request::example(Method::Get, "/uri", |request| {
|
|
|
|
/// let user = request.local_cache(|| current_user(request));
|
|
|
|
/// # });
|
|
|
|
/// ```
|
|
|
|
pub fn local_cache<T, F>(&self, f: F) -> &T
|
|
|
|
where F: FnOnce() -> T,
|
|
|
|
T: Send + Sync + 'static
|
|
|
|
{
|
|
|
|
self.state.cache.try_get()
|
|
|
|
.unwrap_or_else(|| {
|
|
|
|
self.state.cache.set(f());
|
|
|
|
self.state.cache.get()
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2018-09-20 04:14:30 +00:00
|
|
|
/// Retrieves and parses into `T` the 0-indexed `n`th segment from the
|
|
|
|
/// request. Returns `None` if `n` is greater than the number of segments.
|
2018-09-16 10:07:50 +00:00
|
|
|
/// Returns `Some(Err(T::Error))` if the parameter type `T` failed to be
|
|
|
|
/// parsed from the `n`th dynamic parameter.
|
2016-10-01 03:22:06 +00:00
|
|
|
///
|
2016-12-21 09:30:45 +00:00
|
|
|
/// This method exists only to be used by manual routing. To retrieve
|
|
|
|
/// parameters from a request, use Rocket's code generation facilities.
|
|
|
|
///
|
2016-10-01 03:22:06 +00:00
|
|
|
/// # Example
|
|
|
|
///
|
2016-12-21 09:30:45 +00:00
|
|
|
/// ```rust
|
2018-09-20 04:14:30 +00:00
|
|
|
/// # use rocket::{Request, http::Method};
|
|
|
|
/// use rocket::http::{RawStr, uri::Origin};
|
2016-10-01 03:22:06 +00:00
|
|
|
///
|
2018-09-20 04:14:30 +00:00
|
|
|
/// # Request::example(Method::Get, "/", |req| {
|
|
|
|
/// fn string<'s>(req: &'s mut Request, uri: &'static str, n: usize) -> &'s RawStr {
|
|
|
|
/// req.set_uri(Origin::parse(uri).unwrap());
|
2018-09-16 10:07:50 +00:00
|
|
|
///
|
2018-09-20 04:14:30 +00:00
|
|
|
/// req.get_param(n)
|
|
|
|
/// .and_then(|r| r.ok())
|
|
|
|
/// .unwrap_or("unnamed".into())
|
2016-10-01 03:22:06 +00:00
|
|
|
/// }
|
2018-09-20 04:14:30 +00:00
|
|
|
///
|
|
|
|
/// assert_eq!(string(req, "/", 0).as_str(), "unnamed");
|
|
|
|
/// assert_eq!(string(req, "/a/b/this_one", 0).as_str(), "a");
|
|
|
|
/// assert_eq!(string(req, "/a/b/this_one", 1).as_str(), "b");
|
|
|
|
/// assert_eq!(string(req, "/a/b/this_one", 2).as_str(), "this_one");
|
|
|
|
/// assert_eq!(string(req, "/a/b/this_one", 3).as_str(), "unnamed");
|
|
|
|
/// assert_eq!(string(req, "/a/b/c/d/e/f/g/h", 7).as_str(), "h");
|
|
|
|
/// # });
|
2016-10-01 03:22:06 +00:00
|
|
|
/// ```
|
2018-09-20 04:14:30 +00:00
|
|
|
#[inline]
|
2018-09-16 10:07:50 +00:00
|
|
|
pub fn get_param<'a, T>(&'a self, n: usize) -> Option<Result<T, T::Error>>
|
|
|
|
where T: FromParam<'a>
|
|
|
|
{
|
2018-09-20 04:14:30 +00:00
|
|
|
Some(T::from_param(self.raw_segment_str(n)?))
|
2016-09-12 01:57:04 +00:00
|
|
|
}
|
|
|
|
|
2016-10-01 03:22:06 +00:00
|
|
|
/// Retrieves and parses into `T` all of the path segments in the request
|
2018-09-20 04:14:30 +00:00
|
|
|
/// URI beginning and including the 0-indexed `n`th non-empty segment. `T`
|
2018-10-06 13:25:17 +00:00
|
|
|
/// must implement [`FromSegments`], which is used to parse the segments.
|
2016-12-31 05:51:23 +00:00
|
|
|
///
|
|
|
|
/// This method exists only to be used by manual routing. To retrieve
|
|
|
|
/// segments from a request, use Rocket's code generation facilities.
|
2016-12-21 09:30:45 +00:00
|
|
|
///
|
|
|
|
/// # Error
|
|
|
|
///
|
2018-09-20 04:14:30 +00:00
|
|
|
/// If there are fewer than `n` non-empty segments, returns `None`. If
|
|
|
|
/// parsing the segments failed, returns `Some(Err(T:Error))`.
|
2016-12-21 09:30:45 +00:00
|
|
|
///
|
|
|
|
/// # Example
|
2016-10-01 03:22:06 +00:00
|
|
|
///
|
2018-09-20 04:14:30 +00:00
|
|
|
/// ```rust
|
|
|
|
/// # use rocket::{Request, http::Method};
|
|
|
|
/// use std::path::PathBuf;
|
|
|
|
///
|
|
|
|
/// use rocket::http::uri::Origin;
|
|
|
|
///
|
|
|
|
/// # Request::example(Method::Get, "/", |req| {
|
|
|
|
/// fn path<'s>(req: &'s mut Request, uri: &'static str, n: usize) -> PathBuf {
|
|
|
|
/// req.set_uri(Origin::parse(uri).unwrap());
|
|
|
|
///
|
|
|
|
/// req.get_segments(n)
|
|
|
|
/// .and_then(|r| r.ok())
|
|
|
|
/// .unwrap_or_else(|| "whoops".into())
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// assert_eq!(path(req, "/", 0), PathBuf::from("whoops"));
|
|
|
|
/// assert_eq!(path(req, "/a/", 0), PathBuf::from("a"));
|
|
|
|
/// assert_eq!(path(req, "/a/b/c", 0), PathBuf::from("a/b/c"));
|
|
|
|
/// assert_eq!(path(req, "/a/b/c", 1), PathBuf::from("b/c"));
|
|
|
|
/// assert_eq!(path(req, "/a/b/c", 2), PathBuf::from("c"));
|
|
|
|
/// assert_eq!(path(req, "/a/b/c", 6), PathBuf::from("whoops"));
|
|
|
|
/// # });
|
|
|
|
/// ```
|
|
|
|
#[inline]
|
2018-09-16 10:07:50 +00:00
|
|
|
pub fn get_segments<'a, T>(&'a self, n: usize) -> Option<Result<T, T::Error>>
|
|
|
|
where T: FromSegments<'a>
|
|
|
|
{
|
2018-09-20 04:14:30 +00:00
|
|
|
Some(T::from_segments(self.raw_segments(n)?))
|
2016-10-31 17:51:19 +00:00
|
|
|
}
|
|
|
|
|
2018-09-20 04:14:30 +00:00
|
|
|
/// Retrieves and parses into `T` the query value with key `key`. `T` must
|
|
|
|
/// implement [`FromFormValue`], which is used to parse the query's value.
|
|
|
|
/// Key matching is performed case-sensitively. If there are multiple pairs
|
|
|
|
/// with key `key`, the _last_ one is returned.
|
|
|
|
///
|
|
|
|
/// This method exists only to be used by manual routing. To retrieve
|
|
|
|
/// query values from a request, use Rocket's code generation facilities.
|
|
|
|
///
|
|
|
|
/// # Error
|
|
|
|
///
|
|
|
|
/// If a query segment with key `key` isn't present, returns `None`. If
|
|
|
|
/// parsing the value fails, returns `Some(Err(T:Error))`.
|
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// # use rocket::{Request, http::Method};
|
|
|
|
/// use std::path::PathBuf;
|
|
|
|
/// use rocket::http::{RawStr, uri::Origin};
|
|
|
|
///
|
|
|
|
/// # Request::example(Method::Get, "/", |req| {
|
|
|
|
/// fn value<'s>(req: &'s mut Request, uri: &'static str, key: &str) -> &'s RawStr {
|
|
|
|
/// req.set_uri(Origin::parse(uri).unwrap());
|
|
|
|
///
|
|
|
|
/// req.get_query_value(key)
|
|
|
|
/// .and_then(|r| r.ok())
|
|
|
|
/// .unwrap_or("n/a".into())
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// assert_eq!(value(req, "/?a=apple&z=zebra", "a").as_str(), "apple");
|
|
|
|
/// assert_eq!(value(req, "/?a=apple&z=zebra", "z").as_str(), "zebra");
|
|
|
|
/// assert_eq!(value(req, "/?a=apple&z=zebra", "A").as_str(), "n/a");
|
|
|
|
/// assert_eq!(value(req, "/?a=apple&z=zebra&a=argon", "a").as_str(), "argon");
|
|
|
|
/// assert_eq!(value(req, "/?a=1&a=2&a=3&b=4", "a").as_str(), "3");
|
|
|
|
/// assert_eq!(value(req, "/?a=apple&z=zebra", "apple").as_str(), "n/a");
|
|
|
|
/// # });
|
|
|
|
/// ```
|
|
|
|
#[inline]
|
|
|
|
pub fn get_query_value<'a, T>(&'a self, key: &str) -> Option<Result<T, T::Error>>
|
|
|
|
where T: FromFormValue<'a>
|
|
|
|
{
|
|
|
|
self.raw_query_items()?
|
|
|
|
.rev()
|
|
|
|
.find(|item| item.key.as_str() == key)
|
|
|
|
.map(|item| T::from_form_value(item.value))
|
|
|
|
}
|
|
|
|
}
|
2016-12-31 05:51:23 +00:00
|
|
|
|
2018-09-20 04:14:30 +00:00
|
|
|
// All of these methods only exist for internal, including codegen, purposes.
|
|
|
|
// They _are not_ part of the stable API.
|
|
|
|
#[doc(hidden)]
|
|
|
|
impl<'r> Request<'r> {
|
|
|
|
// Only used by doc-tests! Needs to be `pub` because doc-test are external.
|
2019-06-13 01:48:02 +00:00
|
|
|
pub fn example<F: Fn(&mut Request<'_>)>(method: Method, uri: &str, f: F) {
|
2018-11-12 10:17:55 +00:00
|
|
|
let rocket = Rocket::custom(Config::development());
|
2018-09-20 04:14:30 +00:00
|
|
|
let uri = Origin::parse(uri).expect("invalid URI in example");
|
|
|
|
let mut request = Request::new(&rocket, method, uri);
|
|
|
|
f(&mut request);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Updates the cached `path_segments` and `query_items` in `self.state`.
|
|
|
|
// MUST be called whenever a new URI is set or updated.
|
|
|
|
#[inline]
|
|
|
|
fn update_cached_uri_info(&mut self) {
|
|
|
|
let path_segments = Segments(self.uri.path())
|
|
|
|
.map(|s| indices(s, self.uri.path()))
|
|
|
|
.collect();
|
2016-12-31 05:51:23 +00:00
|
|
|
|
2018-09-20 04:14:30 +00:00
|
|
|
let query_items = self.uri.query()
|
|
|
|
.map(|query_str| FormItems::from(query_str)
|
|
|
|
.map(|item| IndexedFormItem::from(query_str, item))
|
|
|
|
.collect()
|
|
|
|
);
|
|
|
|
|
|
|
|
self.state.path_segments = path_segments;
|
|
|
|
self.state.query_items = query_items;
|
2016-09-08 07:02:17 +00:00
|
|
|
}
|
|
|
|
|
2018-09-20 04:14:30 +00:00
|
|
|
/// Get the `n`th path segment, 0-indexed, after the mount point for the
|
|
|
|
/// currently matched route, as a string, if it exists. Used by codegen.
|
2017-05-19 10:29:08 +00:00
|
|
|
#[inline]
|
2018-09-20 04:14:30 +00:00
|
|
|
pub fn raw_segment_str(&self, n: usize) -> Option<&RawStr> {
|
|
|
|
self.routed_path_segment(n)
|
|
|
|
.map(|(i, j)| self.uri.path()[i..j].into())
|
2017-05-19 10:29:08 +00:00
|
|
|
}
|
|
|
|
|
2018-09-20 04:14:30 +00:00
|
|
|
/// Get the segments beginning at the `n`th, 0-indexed, after the mount
|
|
|
|
/// point for the currently matched route, if they exist. Used by codegen.
|
|
|
|
#[inline]
|
2019-06-13 01:48:02 +00:00
|
|
|
pub fn raw_segments(&self, n: usize) -> Option<Segments<'_>> {
|
2018-09-20 04:14:30 +00:00
|
|
|
self.routed_path_segment(n)
|
|
|
|
.map(|(i, _)| Segments(&self.uri.path()[i..]) )
|
2018-02-04 10:07:28 +00:00
|
|
|
}
|
|
|
|
|
2018-09-20 04:14:30 +00:00
|
|
|
// Returns an iterator over the raw segments of the path URI. Does not take
|
|
|
|
// into account the current route. This is used during routing.
|
2017-05-19 10:29:08 +00:00
|
|
|
#[inline]
|
2018-09-20 04:14:30 +00:00
|
|
|
crate fn raw_path_segments(&self) -> impl Iterator<Item = &RawStr> {
|
|
|
|
let path = self.uri.path();
|
|
|
|
self.state.path_segments.iter().cloned()
|
|
|
|
.map(move |(i, j)| path[i..j].into())
|
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn routed_path_segment(&self, n: usize) -> Option<(usize, usize)> {
|
|
|
|
let mount_segments = self.route()
|
|
|
|
.map(|r| r.base.segment_count())
|
|
|
|
.unwrap_or(0);
|
|
|
|
|
|
|
|
self.state.path_segments.get(mount_segments + n).map(|(i, j)| (*i, *j))
|
2017-05-19 10:29:08 +00:00
|
|
|
}
|
|
|
|
|
2018-09-20 04:14:30 +00:00
|
|
|
// Retrieves the pre-parsed query items. Used by matching and codegen.
|
|
|
|
#[inline]
|
|
|
|
pub fn raw_query_items(
|
|
|
|
&self
|
2019-06-13 01:48:02 +00:00
|
|
|
) -> Option<impl Iterator<Item = FormItem<'_>> + DoubleEndedIterator + Clone> {
|
2018-09-20 04:14:30 +00:00
|
|
|
let query = self.uri.query()?;
|
|
|
|
self.state.query_items.as_ref().map(move |items| {
|
|
|
|
items.iter().map(move |item| item.convert(query))
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Set `self`'s parameters given that the route used to reach this request
|
|
|
|
/// was `route`. Use during routing when attempting a given route.
|
2017-05-19 10:29:08 +00:00
|
|
|
#[inline(always)]
|
2018-09-20 04:14:30 +00:00
|
|
|
crate fn set_route(&self, route: &'r Route) {
|
|
|
|
self.state.route.set(Some(route));
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Set the method of `self`, even when `self` is a shared reference. Used
|
|
|
|
/// during routing to override methods for re-routing.
|
|
|
|
#[inline(always)]
|
|
|
|
crate fn _set_method(&self, method: Method) {
|
|
|
|
self.method.set(method);
|
2017-03-08 11:28:12 +00:00
|
|
|
}
|
|
|
|
|
2016-12-21 09:30:45 +00:00
|
|
|
/// Convert from Hyper types into a Rocket Request.
|
Overhaul URI types.
This is fairly large commit with several entangled logical changes.
The primary change in this commit is to completely overhaul how URI
handling in Rocket works. Prior to this commit, the `Uri` type acted as
an origin API. Its parser was minimal and lenient, allowing URIs that
were invalid according to RFC 7230. By contrast, the new `Uri` type
brings with it a strict RFC 7230 compliant parser. The `Uri` type now
represents any kind of valid URI, not simply `Origin` types. Three new
URI types were introduced:
* `Origin` - represents valid origin URIs
* `Absolute` - represents valid absolute URIs
* `Authority` - represents valid authority URIs
The `Origin` type replaces `Uri` in many cases:
* As fields and method inputs of `Route`
* The `&Uri` request guard is now `&Origin`
* The `uri!` macro produces an `Origin` instead of a `Uri`
The strict nature of URI parsing cascaded into the following changes:
* Several `Route` methods now `panic!` on invalid URIs
* The `Rocket::mount()` method is (correctly) stricter with URIs
* The `Redirect` constructors take a `TryInto<Uri>` type
* Dispatching of a `LocalRequest` correctly validates URIs
Overall, URIs are now properly and uniformly handled throughout Rocket's
codebase, resulting in a more reliable and correct system.
In addition to these URI changes, the following changes are also part of
this commit:
* The `LocalRequest::cloned_dispatch()` method was removed in favor of
chaining `.clone().dispatch()`.
* The entire Rocket codebase uses `crate` instead of `pub(crate)` as a
visibility modifier.
* Rocket uses the `crate_visibility_modifier` and `try_from` features.
A note on unsafety: this commit introduces many uses of `unsafe` in the
URI parser. All of these uses are a result of unsafely transforming byte
slices (`&[u8]` or similar) into strings (`&str`). The parser ensures
that these casts are safe, but of course, we must label their use
`unsafe`. The parser was written to be as generic and efficient as
possible and thus can parse directly from byte sources. Rocket, however,
does not make use of this fact and so would be able to remove all uses
of `unsafe` by parsing from an existing `&str`. This should be
considered in the future.
Fixes #443.
Resolves #263.
2018-07-29 01:26:15 +00:00
|
|
|
crate fn from_hyp(
|
|
|
|
rocket: &'r Rocket,
|
|
|
|
h_method: hyper::Method,
|
|
|
|
h_headers: hyper::header::Headers,
|
|
|
|
h_uri: hyper::RequestUri,
|
|
|
|
h_addr: SocketAddr,
|
|
|
|
) -> Result<Request<'r>, String> {
|
2016-12-16 11:07:23 +00:00
|
|
|
// Get a copy of the URI for later use.
|
2016-08-26 08:55:11 +00:00
|
|
|
let uri = match h_uri {
|
2016-12-21 08:09:22 +00:00
|
|
|
hyper::RequestUri::AbsolutePath(s) => s,
|
2016-09-30 22:20:11 +00:00
|
|
|
_ => return Err(format!("Bad URI: {}", h_uri)),
|
2016-08-27 01:37:28 +00:00
|
|
|
};
|
|
|
|
|
2016-12-16 11:07:23 +00:00
|
|
|
// Ensure that the method is known. TODO: Allow made-up methods?
|
2016-08-27 01:37:28 +00:00
|
|
|
let method = match Method::from_hyp(&h_method) {
|
2016-10-09 04:37:28 +00:00
|
|
|
Some(method) => method,
|
2016-12-16 11:07:23 +00:00
|
|
|
None => return Err(format!("Invalid method: {}", h_method))
|
2016-08-26 08:55:11 +00:00
|
|
|
};
|
|
|
|
|
Overhaul URI types.
This is fairly large commit with several entangled logical changes.
The primary change in this commit is to completely overhaul how URI
handling in Rocket works. Prior to this commit, the `Uri` type acted as
an origin API. Its parser was minimal and lenient, allowing URIs that
were invalid according to RFC 7230. By contrast, the new `Uri` type
brings with it a strict RFC 7230 compliant parser. The `Uri` type now
represents any kind of valid URI, not simply `Origin` types. Three new
URI types were introduced:
* `Origin` - represents valid origin URIs
* `Absolute` - represents valid absolute URIs
* `Authority` - represents valid authority URIs
The `Origin` type replaces `Uri` in many cases:
* As fields and method inputs of `Route`
* The `&Uri` request guard is now `&Origin`
* The `uri!` macro produces an `Origin` instead of a `Uri`
The strict nature of URI parsing cascaded into the following changes:
* Several `Route` methods now `panic!` on invalid URIs
* The `Rocket::mount()` method is (correctly) stricter with URIs
* The `Redirect` constructors take a `TryInto<Uri>` type
* Dispatching of a `LocalRequest` correctly validates URIs
Overall, URIs are now properly and uniformly handled throughout Rocket's
codebase, resulting in a more reliable and correct system.
In addition to these URI changes, the following changes are also part of
this commit:
* The `LocalRequest::cloned_dispatch()` method was removed in favor of
chaining `.clone().dispatch()`.
* The entire Rocket codebase uses `crate` instead of `pub(crate)` as a
visibility modifier.
* Rocket uses the `crate_visibility_modifier` and `try_from` features.
A note on unsafety: this commit introduces many uses of `unsafe` in the
URI parser. All of these uses are a result of unsafely transforming byte
slices (`&[u8]` or similar) into strings (`&str`). The parser ensures
that these casts are safe, but of course, we must label their use
`unsafe`. The parser was written to be as generic and efficient as
possible and thus can parse directly from byte sources. Rocket, however,
does not make use of this fact and so would be able to remove all uses
of `unsafe` by parsing from an existing `&str`. This should be
considered in the future.
Fixes #443.
Resolves #263.
2018-07-29 01:26:15 +00:00
|
|
|
// We need to re-parse the URI since we don't trust Hyper... :(
|
|
|
|
let uri = Origin::parse_owned(uri).map_err(|e| e.to_string())?;
|
|
|
|
|
2016-12-16 11:07:23 +00:00
|
|
|
// Construct the request object.
|
2017-06-06 20:41:04 +00:00
|
|
|
let mut request = Request::new(rocket, method, uri);
|
2017-03-28 10:10:18 +00:00
|
|
|
request.set_remote(h_addr);
|
2016-09-12 01:57:04 +00:00
|
|
|
|
2017-03-08 11:28:12 +00:00
|
|
|
// Set the request cookies, if they exist.
|
2017-01-27 07:08:15 +00:00
|
|
|
if let Some(cookie_headers) = h_headers.get_raw("Cookie") {
|
2017-03-08 11:28:12 +00:00
|
|
|
let mut cookie_jar = CookieJar::new();
|
2017-01-27 07:08:15 +00:00
|
|
|
for header in cookie_headers {
|
2019-06-13 01:48:02 +00:00
|
|
|
let raw_str = match std::str::from_utf8(header) {
|
2017-01-27 07:08:15 +00:00
|
|
|
Ok(string) => string,
|
|
|
|
Err(_) => continue
|
|
|
|
};
|
|
|
|
|
2018-07-18 16:45:20 +00:00
|
|
|
for cookie_str in raw_str.split(';').map(|s| s.trim()) {
|
2017-06-06 20:41:04 +00:00
|
|
|
if let Some(cookie) = Cookies::parse_cookie(cookie_str) {
|
2017-03-08 11:28:12 +00:00
|
|
|
cookie_jar.add_original(cookie);
|
|
|
|
}
|
2017-01-27 07:08:15 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-09-20 04:14:30 +00:00
|
|
|
request.state.cookies = RefCell::new(cookie_jar);
|
2016-12-16 00:34:19 +00:00
|
|
|
}
|
|
|
|
|
2016-12-16 11:07:23 +00:00
|
|
|
// Set the rest of the headers.
|
|
|
|
for hyp in h_headers.iter() {
|
2017-03-11 01:42:09 +00:00
|
|
|
if let Some(header_values) = h_headers.get_raw(hyp.name()) {
|
|
|
|
for value in header_values {
|
2017-03-16 02:20:20 +00:00
|
|
|
// This is not totally correct since values needn't be UTF8.
|
|
|
|
let value_str = String::from_utf8_lossy(value).into_owned();
|
|
|
|
let header = Header::new(hyp.name().to_string(), value_str);
|
2017-03-11 01:42:09 +00:00
|
|
|
request.add_header(header);
|
|
|
|
}
|
|
|
|
}
|
2016-12-16 11:07:23 +00:00
|
|
|
}
|
2016-08-27 01:37:28 +00:00
|
|
|
|
|
|
|
Ok(request)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-06-13 01:48:02 +00:00
|
|
|
impl fmt::Debug for Request<'_> {
|
|
|
|
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
|
2017-06-06 20:41:04 +00:00
|
|
|
fmt.debug_struct("Request")
|
|
|
|
.field("method", &self.method)
|
|
|
|
.field("uri", &self.uri)
|
|
|
|
.field("headers", &self.headers())
|
|
|
|
.field("remote", &self.remote())
|
|
|
|
.finish()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-06-13 01:48:02 +00:00
|
|
|
impl fmt::Display for Request<'_> {
|
2016-10-01 03:22:06 +00:00
|
|
|
/// Pretty prints a Request. This is primarily used by Rocket's logging
|
|
|
|
/// infrastructure.
|
2019-06-13 01:48:02 +00:00
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
2018-02-04 10:07:28 +00:00
|
|
|
write!(f, "{} {}", Paint::green(self.method()), Paint::blue(&self.uri))?;
|
2017-07-11 11:35:05 +00:00
|
|
|
|
|
|
|
// Print the requests media type when the route specifies a format.
|
|
|
|
if let Some(media_type) = self.format() {
|
|
|
|
if !media_type.is_any() {
|
|
|
|
write!(f, " {}", Paint::yellow(media_type))?;
|
2017-02-01 11:12:24 +00:00
|
|
|
}
|
2016-10-13 02:08:19 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
Ok(())
|
2016-03-15 03:43:52 +00:00
|
|
|
}
|
|
|
|
}
|
2018-09-20 04:14:30 +00:00
|
|
|
|
|
|
|
impl IndexedFormItem {
|
|
|
|
#[inline(always)]
|
2019-06-13 01:48:02 +00:00
|
|
|
fn from(s: &str, i: FormItem<'_>) -> Self {
|
2018-09-20 04:14:30 +00:00
|
|
|
let (r, k, v) = (indices(i.raw, s), indices(i.key, s), indices(i.value, s));
|
|
|
|
IndexedFormItem { raw: r, key: k, value: v }
|
|
|
|
}
|
|
|
|
|
|
|
|
#[inline(always)]
|
|
|
|
fn convert<'s>(&self, source: &'s str) -> FormItem<'s> {
|
|
|
|
FormItem {
|
|
|
|
raw: source[self.raw.0..self.raw.1].into(),
|
|
|
|
key: source[self.key.0..self.key.1].into(),
|
|
|
|
value: source[self.value.0..self.value.1].into(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn indices(needle: &str, haystack: &str) -> (usize, usize) {
|
|
|
|
Indexed::checked_from(needle, haystack)
|
|
|
|
.expect("segments inside of path/query")
|
|
|
|
.indices()
|
|
|
|
}
|