rocket/request/request.rs
1use std::fmt;
2use std::ops::RangeFrom;
3use std::sync::Arc;
4use std::borrow::Cow;
5use std::future::Future;
6use std::net::{IpAddr, SocketAddr};
7
8use yansi::Paint;
9use state::{TypeMap, InitCell};
10use futures::future::BoxFuture;
11use parking_lot::Mutex;
12
13use crate::{Rocket, Route, Orbit};
14use crate::request::{FromParam, FromSegments, FromRequest, Outcome, AtomicMethod};
15use crate::form::{self, ValueField, FromForm};
16use crate::data::Limits;
17
18use crate::http::{hyper, Method, Header, HeaderMap};
19use crate::http::{ContentType, Accept, MediaType, CookieJar, Cookie};
20use crate::http::uncased::UncasedStr;
21use crate::http::private::Certificates;
22use crate::http::uri::{fmt::Path, Origin, Segments, Host, Authority};
23
24/// The type of an incoming web request.
25///
26/// This should be used sparingly in Rocket applications. In particular, it
27/// should likely only be used when writing [`FromRequest`] implementations. It
28/// contains all of the information for a given web request except for the body
29/// data. This includes the HTTP method, URI, cookies, headers, and more.
30pub struct Request<'r> {
31 method: AtomicMethod,
32 uri: Origin<'r>,
33 headers: HeaderMap<'r>,
34 pub(crate) connection: ConnectionMeta,
35 pub(crate) state: RequestState<'r>,
36}
37
38/// Information derived from an incoming connection, if any.
39#[derive(Clone)]
40pub(crate) struct ConnectionMeta {
41 pub remote: Option<SocketAddr>,
42 #[cfg_attr(not(feature = "mtls"), allow(dead_code))]
43 pub client_certificates: Option<Certificates>,
44}
45
46/// Information derived from the request.
47pub(crate) struct RequestState<'r> {
48 pub rocket: &'r Rocket<Orbit>,
49 pub route: Mutex<Option<&'r Route>>,
50 pub cookies: CookieJar<'r>,
51 pub accept: InitCell<Option<Accept>>,
52 pub content_type: InitCell<Option<ContentType>>,
53 pub cache: Arc<TypeMap![Send + Sync]>,
54 pub host: Option<Host<'r>>,
55}
56
57impl Request<'_> {
58 pub(crate) fn clone(&self) -> Self {
59 Request {
60 method: AtomicMethod::new(self.method()),
61 uri: self.uri.clone(),
62 headers: self.headers.clone(),
63 connection: self.connection.clone(),
64 state: self.state.clone(),
65 }
66 }
67}
68
69impl RequestState<'_> {
70 fn clone(&self) -> Self {
71 RequestState {
72 rocket: self.rocket,
73 route: Mutex::new(*self.route.lock()),
74 cookies: self.cookies.clone(),
75 accept: self.accept.clone(),
76 content_type: self.content_type.clone(),
77 cache: self.cache.clone(),
78 host: self.host.clone(),
79 }
80 }
81}
82
83impl<'r> Request<'r> {
84 /// Create a new `Request` with the given `method` and `uri`.
85 #[inline(always)]
86 pub(crate) fn new<'s: 'r>(
87 rocket: &'r Rocket<Orbit>,
88 method: Method,
89 uri: Origin<'s>
90 ) -> Request<'r> {
91 Request {
92 uri,
93 method: AtomicMethod::new(method),
94 headers: HeaderMap::new(),
95 connection: ConnectionMeta {
96 remote: None,
97 client_certificates: None,
98 },
99 state: RequestState {
100 rocket,
101 route: Mutex::new(None),
102 cookies: CookieJar::new(rocket.config()),
103 accept: InitCell::new(),
104 content_type: InitCell::new(),
105 cache: Arc::new(<TypeMap![Send + Sync]>::new()),
106 host: None,
107 }
108 }
109 }
110
111 /// Retrieve the method from `self`.
112 ///
113 /// # Example
114 ///
115 /// ```rust
116 /// use rocket::http::Method;
117 ///
118 /// # let c = rocket::local::blocking::Client::debug_with(vec![]).unwrap();
119 /// # let get = |uri| c.get(uri);
120 /// # let post = |uri| c.post(uri);
121 /// assert_eq!(get("/").method(), Method::Get);
122 /// assert_eq!(post("/").method(), Method::Post);
123 /// ```
124 #[inline(always)]
125 pub fn method(&self) -> Method {
126 self.method.load()
127 }
128
129 /// Set the method of `self` to `method`.
130 ///
131 /// # Example
132 ///
133 /// ```rust
134 /// use rocket::http::Method;
135 /// # let c = rocket::local::blocking::Client::debug_with(vec![]).unwrap();
136 /// # let mut req = c.get("/");
137 /// # let request = req.inner_mut();
138 ///
139 /// assert_eq!(request.method(), Method::Get);
140 ///
141 /// request.set_method(Method::Post);
142 /// assert_eq!(request.method(), Method::Post);
143 /// ```
144 #[inline(always)]
145 pub fn set_method(&mut self, method: Method) {
146 self._set_method(method);
147 }
148
149 /// Borrow the [`Origin`] URI from `self`.
150 ///
151 /// # Example
152 ///
153 /// ```rust
154 /// # let c = rocket::local::blocking::Client::debug_with(vec![]).unwrap();
155 /// # let get = |uri| c.get(uri);
156 /// assert_eq!(get("/hello/rocketeer").uri().path(), "/hello/rocketeer");
157 /// assert_eq!(get("/hello").uri().query(), None);
158 /// ```
159 #[inline(always)]
160 pub fn uri(&self) -> &Origin<'r> {
161 &self.uri
162 }
163
164 /// Set the URI in `self` to `uri`.
165 ///
166 /// # Example
167 ///
168 /// ```rust
169 /// use rocket::http::uri::Origin;
170 /// # let c = rocket::local::blocking::Client::debug_with(vec![]).unwrap();
171 /// # let mut req = c.get("/");
172 /// # let request = req.inner_mut();
173 ///
174 /// let uri = Origin::parse("/hello/Sergio?type=greeting").unwrap();
175 /// request.set_uri(uri);
176 /// assert_eq!(request.uri().path(), "/hello/Sergio");
177 /// assert_eq!(request.uri().query().unwrap(), "type=greeting");
178 ///
179 /// let new_uri = request.uri().map_path(|p| format!("/foo{}", p)).unwrap();
180 /// request.set_uri(new_uri);
181 /// assert_eq!(request.uri().path(), "/foo/hello/Sergio");
182 /// assert_eq!(request.uri().query().unwrap(), "type=greeting");
183 /// ```
184 #[inline(always)]
185 pub fn set_uri(&mut self, uri: Origin<'r>) {
186 self.uri = uri;
187 }
188
189 /// Returns the [`Host`] identified in the request, if any.
190 ///
191 /// If the request is made via HTTP/1.1 (or earlier), this method returns
192 /// the value in the `HOST` header without the deprecated `user_info`
193 /// component. Otherwise, this method returns the contents of the
194 /// `:authority` pseudo-header request field.
195 ///
196 /// Note that this method _only_ reflects the `HOST` header in the _initial_
197 /// request and not any changes made thereafter. To change the value
198 /// returned by this method, use [`Request::set_host()`].
199 ///
200 /// # ⚠️ DANGER ⚠️
201 ///
202 /// Using the user-controlled `host` to construct URLs is a security hazard!
203 /// _Never_ do so without first validating the host against a whitelist. For
204 /// this reason, Rocket disallows constructing host-prefixed URIs with
205 /// [`uri!`]. _Always_ use [`uri!`] to construct URIs.
206 ///
207 /// [`uri!`]: crate::uri!
208 ///
209 /// # Example
210 ///
211 /// Retrieve the raw host, unusable to construct safe URIs:
212 ///
213 /// ```rust
214 /// use rocket::http::uri::Host;
215 /// # use rocket::uri;
216 /// # let c = rocket::local::blocking::Client::debug_with(vec![]).unwrap();
217 /// # let mut req = c.get("/");
218 /// # let request = req.inner_mut();
219 ///
220 /// assert_eq!(request.host(), None);
221 ///
222 /// request.set_host(Host::from(uri!("rocket.rs")));
223 /// let host = request.host().unwrap();
224 /// assert_eq!(host.domain(), "rocket.rs");
225 /// assert_eq!(host.port(), None);
226 ///
227 /// request.set_host(Host::from(uri!("rocket.rs:2392")));
228 /// let host = request.host().unwrap();
229 /// assert_eq!(host.domain(), "rocket.rs");
230 /// assert_eq!(host.port(), Some(2392));
231 /// ```
232 ///
233 /// Retrieve the raw host, check it against a whitelist, and construct a
234 /// URI:
235 ///
236 /// ```rust
237 /// # #[macro_use] extern crate rocket;
238 /// # type Token = String;
239 /// # let c = rocket::local::blocking::Client::debug_with(vec![]).unwrap();
240 /// # let mut req = c.get("/");
241 /// # let request = req.inner_mut();
242 /// use rocket::http::uri::Host;
243 ///
244 /// // A sensitive URI we want to prefix with safe hosts.
245 /// #[get("/token?<secret>")]
246 /// fn token(secret: Token) { /* .. */ }
247 ///
248 /// // Whitelist of known hosts. In a real setting, you might retrieve this
249 /// // list from config at ignite-time using tools like `AdHoc::config()`.
250 /// const WHITELIST: [Host<'static>; 3] = [
251 /// Host::new(uri!("rocket.rs")),
252 /// Host::new(uri!("rocket.rs:443")),
253 /// Host::new(uri!("guide.rocket.rs:443")),
254 /// ];
255 ///
256 /// // A request with a host of "rocket.rs". Note the case-insensitivity.
257 /// request.set_host(Host::from(uri!("ROCKET.rs")));
258 /// let prefix = request.host().and_then(|h| h.to_absolute("https", &WHITELIST));
259 ///
260 /// // `rocket.rs` is in the whitelist, so we'll get back a `Some`.
261 /// assert!(prefix.is_some());
262 /// if let Some(prefix) = prefix {
263 /// // We can use this prefix to safely construct URIs.
264 /// let uri = uri!(prefix, token("some-secret-token"));
265 /// assert_eq!(uri, "https://ROCKET.rs/token?secret=some-secret-token");
266 /// }
267 ///
268 /// // A request with a host of "attacker-controlled.com".
269 /// request.set_host(Host::from(uri!("attacker-controlled.com")));
270 /// let prefix = request.host().and_then(|h| h.to_absolute("https", &WHITELIST));
271 ///
272 /// // `attacker-controlled.come` is _not_ on the whitelist.
273 /// assert!(prefix.is_none());
274 /// assert!(request.host().is_some());
275 /// ```
276 #[inline(always)]
277 pub fn host(&self) -> Option<&Host<'r>> {
278 self.state.host.as_ref()
279 }
280
281 /// Sets the host of `self` to `host`.
282 ///
283 /// # Example
284 ///
285 /// Set the host to `rocket.rs:443`.
286 ///
287 /// ```rust
288 /// use rocket::http::uri::Host;
289 /// # use rocket::uri;
290 /// # let c = rocket::local::blocking::Client::debug_with(vec![]).unwrap();
291 /// # let mut req = c.get("/");
292 /// # let request = req.inner_mut();
293 ///
294 /// assert_eq!(request.host(), None);
295 ///
296 /// request.set_host(Host::from(uri!("rocket.rs:443")));
297 /// let host = request.host().unwrap();
298 /// assert_eq!(host.domain(), "rocket.rs");
299 /// assert_eq!(host.port(), Some(443));
300 /// ```
301 #[inline(always)]
302 pub fn set_host(&mut self, host: Host<'r>) {
303 self.state.host = Some(host);
304 }
305
306 /// Returns the raw address of the remote connection that initiated this
307 /// request if the address is known. If the address is not known, `None` is
308 /// returned.
309 ///
310 /// Because it is common for proxies to forward connections for clients, the
311 /// remote address may contain information about the proxy instead of the
312 /// client. For this reason, proxies typically set a "X-Real-IP" header
313 /// [`ip_header`](crate::Config::ip_header) with the client's true IP. To
314 /// extract this IP from the request, use the [`real_ip()`] or
315 /// [`client_ip()`] methods.
316 ///
317 /// [`real_ip()`]: #method.real_ip
318 /// [`client_ip()`]: #method.client_ip
319 ///
320 /// # Example
321 ///
322 /// ```rust
323 /// use std::net::{SocketAddrV4, Ipv4Addr};
324 /// # let c = rocket::local::blocking::Client::debug_with(vec![]).unwrap();
325 /// # let mut req = c.get("/");
326 /// # let request = req.inner_mut();
327 ///
328 /// assert_eq!(request.remote(), None);
329 ///
330 /// let localhost = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 8000).into();
331 /// request.set_remote(localhost);
332 /// assert_eq!(request.remote(), Some(localhost));
333 /// ```
334 #[inline(always)]
335 pub fn remote(&self) -> Option<SocketAddr> {
336 self.connection.remote
337 }
338
339 /// Sets the remote address of `self` to `address`.
340 ///
341 /// # Example
342 ///
343 /// Set the remote address to be 127.0.0.1:8000:
344 ///
345 /// ```rust
346 /// use std::net::{SocketAddrV4, Ipv4Addr};
347 /// # let c = rocket::local::blocking::Client::debug_with(vec![]).unwrap();
348 /// # let mut req = c.get("/");
349 /// # let request = req.inner_mut();
350 ///
351 /// assert_eq!(request.remote(), None);
352 ///
353 /// let localhost = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 8000).into();
354 /// request.set_remote(localhost);
355 /// assert_eq!(request.remote(), Some(localhost));
356 /// ```
357 #[inline(always)]
358 pub fn set_remote(&mut self, address: SocketAddr) {
359 self.connection.remote = Some(address);
360 }
361
362 /// Returns the IP address of the configured
363 /// [`ip_header`](crate::Config::ip_header) of the request if such a header
364 /// is configured, exists and contains a valid IP address.
365 ///
366 /// The header's value is client-controlled unless a trusted proxy
367 /// overwrites it. See [`Config::ip_header`](crate::Config::ip_header).
368 ///
369 /// # Example
370 ///
371 /// ```rust
372 /// use std::net::Ipv4Addr;
373 /// use rocket::http::Header;
374 ///
375 /// # let c = rocket::local::blocking::Client::debug_with(vec![]).unwrap();
376 /// # let req = c.get("/");
377 /// assert_eq!(req.real_ip(), None);
378 ///
379 /// // `ip_header` defaults to `X-Real-IP`.
380 /// let req = req.header(Header::new("X-Real-IP", "127.0.0.1"));
381 /// assert_eq!(req.real_ip(), Some(Ipv4Addr::LOCALHOST.into()));
382 /// ```
383 pub fn real_ip(&self) -> Option<IpAddr> {
384 let ip_header = self.rocket().config.ip_header.as_ref()?.as_str();
385 self.headers()
386 .get_one(ip_header)
387 .and_then(|ip| {
388 ip.parse()
389 .map_err(|_| warn_!("'{}' header is malformed: {}", ip_header, ip))
390 .ok()
391 })
392 }
393
394 /// Attempts to return the client's IP address by first inspecting the
395 /// [`ip_header`](crate::Config::ip_header) and then using the remote
396 /// connection's IP address. Note that the built-in `IpAddr` request guard
397 /// can be used to retrieve the same information in a handler:
398 ///
399 /// ```rust
400 /// # use rocket::get;
401 /// use std::net::IpAddr;
402 ///
403 /// #[get("/")]
404 /// fn get_ip(client_ip: IpAddr) { /* ... */ }
405 ///
406 /// #[get("/")]
407 /// fn try_get_ip(client_ip: Option<IpAddr>) { /* ... */ }
408 /// ````
409 ///
410 /// If the `ip_header` exists and contains a valid IP address, that address
411 /// is returned. Otherwise, if the address of the remote connection is
412 /// known, that address is returned. Otherwise, `None` is returned.
413 ///
414 /// **Warning:** With the default configuration, any client can choose the
415 /// returned address by sending an `X-Real-IP` header. Do not rely on this
416 /// value for access control, rate limiting, or audit attribution unless
417 /// the application is only reachable through a proxy that overwrites the
418 /// header, or `ip_header` is disabled. See
419 /// [`Config::ip_header`](crate::Config::ip_header) for details. Use
420 /// [`Request::remote()`] to retrieve the connection's address directly.
421 ///
422 /// # Example
423 ///
424 /// ```rust
425 /// # use rocket::http::Header;
426 /// # use std::net::{SocketAddr, IpAddr, Ipv4Addr};
427 /// # let c = rocket::local::blocking::Client::debug_with(vec![]).unwrap();
428 /// # let mut req = c.get("/");
429 /// # let request = req.inner_mut();
430 ///
431 /// // starting without an "X-Real-IP" header or remote address
432 /// assert!(request.client_ip().is_none());
433 ///
434 /// // add a remote address; this is done by Rocket automatically
435 /// request.set_remote("127.0.0.1:8000".parse().unwrap());
436 /// assert_eq!(request.client_ip(), Some("127.0.0.1".parse().unwrap()));
437 ///
438 /// // now with an X-Real-IP header, the default value for `ip_header`.
439 /// request.add_header(Header::new("X-Real-IP", "8.8.8.8"));
440 /// assert_eq!(request.client_ip(), Some("8.8.8.8".parse().unwrap()));
441 /// ```
442 #[inline]
443 pub fn client_ip(&self) -> Option<IpAddr> {
444 self.real_ip().or_else(|| self.remote().map(|r| r.ip()))
445 }
446
447 /// Returns a wrapped borrow to the cookies in `self`.
448 ///
449 /// [`CookieJar`] implements internal mutability, so this method allows you
450 /// to get _and_ add/remove cookies in `self`.
451 ///
452 /// # Example
453 ///
454 /// Add a new cookie to a request's cookies:
455 ///
456 /// ```rust
457 /// use rocket::http::Cookie;
458 ///
459 /// # let c = rocket::local::blocking::Client::debug_with(vec![]).unwrap();
460 /// # let request = c.get("/");
461 /// # let req = request.inner();
462 /// req.cookies().add(("key", "val"));
463 /// req.cookies().add(("ans", format!("life: {}", 38 + 4)));
464 ///
465 /// assert_eq!(req.cookies().get_pending("key").unwrap().value(), "val");
466 /// assert_eq!(req.cookies().get_pending("ans").unwrap().value(), "life: 42");
467 /// ```
468 #[inline(always)]
469 pub fn cookies(&self) -> &CookieJar<'r> {
470 &self.state.cookies
471 }
472
473 /// Returns a [`HeaderMap`] of all of the headers in `self`.
474 ///
475 /// # Example
476 ///
477 /// ```rust
478 /// use rocket::http::{Accept, ContentType};
479 ///
480 /// # let c = rocket::local::blocking::Client::debug_with(vec![]).unwrap();
481 /// # let get = |uri| c.get(uri);
482 /// assert!(get("/").headers().is_empty());
483 ///
484 /// let req = get("/").header(Accept::HTML).header(ContentType::HTML);
485 /// assert_eq!(req.headers().len(), 2);
486 /// ```
487 #[inline(always)]
488 pub fn headers(&self) -> &HeaderMap<'r> {
489 &self.headers
490 }
491
492 /// Add `header` to `self`'s headers. The type of `header` can be any type
493 /// that implements the `Into<Header>` trait. This includes common types
494 /// such as [`ContentType`] and [`Accept`].
495 ///
496 /// # Example
497 ///
498 /// ```rust
499 /// use rocket::http::ContentType;
500 /// # let c = rocket::local::blocking::Client::debug_with(vec![]).unwrap();
501 /// # let mut req = c.get("/");
502 /// # let request = req.inner_mut();
503 ///
504 /// assert!(request.headers().is_empty());
505 ///
506 /// request.add_header(ContentType::HTML);
507 /// assert!(request.headers().contains("Content-Type"));
508 /// assert_eq!(request.headers().len(), 1);
509 /// ```
510 #[inline]
511 pub fn add_header<'h: 'r, H: Into<Header<'h>>>(&mut self, header: H) {
512 let header = header.into();
513 self.bust_header_cache(header.name(), false);
514 self.headers.add(header);
515 }
516
517 /// Replaces the value of the header with name `header.name` with
518 /// `header.value`. If no such header exists, `header` is added as a header
519 /// to `self`.
520 ///
521 /// # Example
522 ///
523 /// ```rust
524 /// use rocket::http::ContentType;
525 /// # let c = rocket::local::blocking::Client::debug_with(vec![]).unwrap();
526 /// # let mut req = c.get("/");
527 /// # let request = req.inner_mut();
528 ///
529 /// assert!(request.headers().is_empty());
530 ///
531 /// request.add_header(ContentType::Any);
532 /// assert_eq!(request.headers().get_one("Content-Type"), Some("*/*"));
533 /// assert_eq!(request.content_type(), Some(&ContentType::Any));
534 ///
535 /// request.replace_header(ContentType::PNG);
536 /// assert_eq!(request.headers().get_one("Content-Type"), Some("image/png"));
537 /// assert_eq!(request.content_type(), Some(&ContentType::PNG));
538 /// ```
539 #[inline]
540 pub fn replace_header<'h: 'r, H: Into<Header<'h>>>(&mut self, header: H) {
541 let header = header.into();
542 self.bust_header_cache(header.name(), true);
543 self.headers.replace(header);
544 }
545
546 /// Returns the Content-Type header of `self`. If the header is not present,
547 /// returns `None`.
548 ///
549 /// # Example
550 ///
551 /// ```rust
552 /// use rocket::http::ContentType;
553 ///
554 /// # let c = rocket::local::blocking::Client::debug_with(vec![]).unwrap();
555 /// # let get = |uri| c.get(uri);
556 /// assert_eq!(get("/").content_type(), None);
557 ///
558 /// let req = get("/").header(ContentType::JSON);
559 /// assert_eq!(req.content_type(), Some(&ContentType::JSON));
560 /// ```
561 #[inline]
562 pub fn content_type(&self) -> Option<&ContentType> {
563 self.state.content_type.get_or_init(|| {
564 self.headers().get_one("Content-Type").and_then(|v| v.parse().ok())
565 }).as_ref()
566 }
567
568 /// Returns the Accept header of `self`. If the header is not present,
569 /// returns `None`.
570 ///
571 /// # Example
572 ///
573 /// ```rust
574 /// use rocket::http::Accept;
575 ///
576 /// # let c = rocket::local::blocking::Client::debug_with(vec![]).unwrap();
577 /// # let get = |uri| c.get(uri);
578 /// assert_eq!(get("/").accept(), None);
579 /// assert_eq!(get("/").header(Accept::JSON).accept(), Some(&Accept::JSON));
580 /// ```
581 #[inline]
582 pub fn accept(&self) -> Option<&Accept> {
583 self.state.accept.get_or_init(|| {
584 self.headers().get_one("Accept").and_then(|v| v.parse().ok())
585 }).as_ref()
586 }
587
588 /// Returns the media type "format" of the request.
589 ///
590 /// The "format" of a request is either the Content-Type, if the request
591 /// methods indicates support for a payload, or the preferred media type in
592 /// the Accept header otherwise. If the method indicates no payload and no
593 /// Accept header is specified, a media type of `Any` is returned.
594 ///
595 /// The media type returned from this method is used to match against the
596 /// `format` route attribute.
597 ///
598 /// # Example
599 ///
600 /// ```rust
601 /// use rocket::http::{Accept, ContentType, MediaType};
602 /// # let c = rocket::local::blocking::Client::debug_with(vec![]).unwrap();
603 /// # let get = |uri| c.get(uri);
604 /// # let post = |uri| c.post(uri);
605 ///
606 /// // Non-payload-bearing: format is accept header.
607 /// let req = get("/").header(Accept::HTML);
608 /// assert_eq!(req.format(), Some(&MediaType::HTML));
609 ///
610 /// let req = get("/").header(ContentType::JSON).header(Accept::HTML);
611 /// assert_eq!(req.format(), Some(&MediaType::HTML));
612 ///
613 /// // Payload: format is content-type header.
614 /// let req = post("/").header(ContentType::HTML);
615 /// assert_eq!(req.format(), Some(&MediaType::HTML));
616 ///
617 /// let req = post("/").header(ContentType::JSON).header(Accept::HTML);
618 /// assert_eq!(req.format(), Some(&MediaType::JSON));
619 ///
620 /// // Non-payload-bearing method and no accept header: `Any`.
621 /// assert_eq!(get("/").format(), Some(&MediaType::Any));
622 /// ```
623 pub fn format(&self) -> Option<&MediaType> {
624 static ANY: MediaType = MediaType::Any;
625 if self.method().supports_payload() {
626 self.content_type().map(|ct| ct.media_type())
627 } else {
628 // FIXME: Should we be using `accept_first` or `preferred`? Or
629 // should we be checking neither and instead pass things through
630 // where the client accepts the thing at all?
631 self.accept()
632 .map(|accept| accept.preferred().media_type())
633 .or(Some(&ANY))
634 }
635 }
636
637 /// Returns the [`Rocket`] instance that is handling this request.
638 ///
639 /// # Example
640 ///
641 /// ```rust
642 /// # let c = rocket::local::blocking::Client::debug_with(vec![]).unwrap();
643 /// # let request = c.get("/");
644 /// # type Pool = usize;
645 /// // Retrieve the application config via `Rocket::config()`.
646 /// let config = request.rocket().config();
647 ///
648 /// // Retrieve managed state via `Rocket::state()`.
649 /// let state = request.rocket().state::<Pool>();
650 ///
651 /// // Get a list of all of the registered routes and catchers.
652 /// let routes = request.rocket().routes();
653 /// let catchers = request.rocket().catchers();
654 /// ```
655 #[inline(always)]
656 pub fn rocket(&self) -> &'r Rocket<Orbit> {
657 &self.state.rocket
658 }
659
660 /// Returns the configured application data limits.
661 ///
662 /// This is convenience function equivalent to:
663 ///
664 /// ```rust
665 /// # let c = rocket::local::blocking::Client::debug_with(vec![]).unwrap();
666 /// # let request = c.get("/");
667 /// &request.rocket().config().limits
668 /// # ;
669 /// ```
670 ///
671 /// # Example
672 ///
673 /// ```rust
674 /// use rocket::data::ToByteUnit;
675 /// # let c = rocket::local::blocking::Client::debug_with(vec![]).unwrap();
676 /// # let request = c.get("/");
677 ///
678 /// // This is the default `form` limit.
679 /// assert_eq!(request.limits().get("form"), Some(32.kibibytes()));
680 ///
681 /// // Retrieve the limit for files with extension `.pdf`; etails to 1MiB.
682 /// assert_eq!(request.limits().get("file/pdf"), Some(1.mebibytes()));
683 /// ```
684 #[inline(always)]
685 pub fn limits(&self) -> &'r Limits {
686 &self.rocket().config().limits
687 }
688
689 /// Get the presently matched route, if any.
690 ///
691 /// This method returns `Some` any time a handler or its guards are being
692 /// invoked. This method returns `None` _before_ routing has commenced; this
693 /// includes during request fairing callbacks.
694 ///
695 /// # Example
696 ///
697 /// ```rust
698 /// # let c = rocket::local::blocking::Client::debug_with(vec![]).unwrap();
699 /// # let request = c.get("/");
700 /// let route = request.route();
701 /// ```
702 #[inline(always)]
703 pub fn route(&self) -> Option<&'r Route> {
704 *self.state.route.lock()
705 }
706
707 /// Invokes the request guard implementation for `T`, returning its outcome.
708 ///
709 /// # Example
710 ///
711 /// Assuming a `User` request guard exists, invoke it:
712 ///
713 /// ```rust
714 /// # type User = rocket::http::Method;
715 /// # rocket::async_test(async move {
716 /// # let c = rocket::local::asynchronous::Client::debug_with(vec![]).await.unwrap();
717 /// # let request = c.get("/");
718 /// let outcome = request.guard::<User>().await;
719 /// # })
720 /// ```
721 #[inline(always)]
722 pub fn guard<'z, 'a, T>(&'a self) -> BoxFuture<'z, Outcome<T, T::Error>>
723 where T: FromRequest<'a> + 'z, 'a: 'z, 'r: 'z
724 {
725 T::from_request(self)
726 }
727
728 /// Retrieves the cached value for type `T` from the request-local cached
729 /// state of `self`. If no such value has previously been cached for this
730 /// request, `f` is called to produce the value which is subsequently
731 /// returned.
732 ///
733 /// Different values of the same type _cannot_ be cached without using a
734 /// proxy, wrapper type. To avoid the need to write these manually, or for
735 /// libraries wishing to store values of public types, use the
736 /// [`local_cache!`](crate::request::local_cache) or
737 /// [`local_cache_once!`](crate::request::local_cache_once) macros to
738 /// generate a locally anonymous wrapper type, store, and retrieve the
739 /// wrapped value from request-local cache.
740 ///
741 /// # Example
742 ///
743 /// ```rust
744 /// # let c = rocket::local::blocking::Client::debug_with(vec![]).unwrap();
745 /// # let request = c.get("/");
746 /// // The first store into local cache for a given type wins.
747 /// let value = request.local_cache(|| "hello");
748 /// assert_eq!(*request.local_cache(|| "hello"), "hello");
749 ///
750 /// // The following return the cached, previously stored value for the type.
751 /// assert_eq!(*request.local_cache(|| "goodbye"), "hello");
752 /// ```
753 #[inline]
754 pub fn local_cache<T, F>(&self, f: F) -> &T
755 where F: FnOnce() -> T,
756 T: Send + Sync + 'static
757 {
758 self.state.cache.try_get()
759 .unwrap_or_else(|| {
760 self.state.cache.set(f());
761 self.state.cache.get()
762 })
763 }
764
765 /// Retrieves the cached value for type `T` from the request-local cached
766 /// state of `self`. If no such value has previously been cached for this
767 /// request, `fut` is `await`ed to produce the value which is subsequently
768 /// returned.
769 ///
770 /// # Example
771 ///
772 /// ```rust
773 /// # use rocket::Request;
774 /// # type User = ();
775 /// async fn current_user<'r>(request: &Request<'r>) -> User {
776 /// // validate request for a given user, load from database, etc
777 /// }
778 ///
779 /// # rocket::async_test(async move {
780 /// # let c = rocket::local::asynchronous::Client::debug_with(vec![]).await.unwrap();
781 /// # let request = c.get("/");
782 /// let current_user = request.local_cache_async(async {
783 /// current_user(&request).await
784 /// }).await;
785 /// # })
786 /// ```
787 #[inline]
788 pub async fn local_cache_async<'a, T, F>(&'a self, fut: F) -> &'a T
789 where F: Future<Output = T>,
790 T: Send + Sync + 'static
791 {
792 match self.state.cache.try_get() {
793 Some(s) => s,
794 None => {
795 self.state.cache.set(fut.await);
796 self.state.cache.get()
797 }
798 }
799 }
800
801 /// Retrieves and parses into `T` the 0-indexed `n`th non-empty segment from
802 /// the _routed_ request, that is, the `n`th segment _after_ the mount
803 /// point. If the request has not been routed, then this is simply the `n`th
804 /// non-empty request URI segment.
805 ///
806 /// Returns `None` if `n` is greater than the number of non-empty segments.
807 /// Returns `Some(Err(T::Error))` if the parameter type `T` failed to be
808 /// parsed from the `n`th dynamic parameter.
809 ///
810 /// This method exists only to be used by manual routing. To retrieve
811 /// parameters from a request, use Rocket's code generation facilities.
812 ///
813 /// # Example
814 ///
815 /// ```rust
816 /// # let c = rocket::local::blocking::Client::debug_with(vec![]).unwrap();
817 /// # let get = |uri| c.get(uri);
818 /// assert_eq!(get("/a/b/c").param(0), Some(Ok("a")));
819 /// assert_eq!(get("/a/b/c").param(1), Some(Ok("b")));
820 /// assert_eq!(get("/a/b/c").param(2), Some(Ok("c")));
821 /// assert_eq!(get("/a/b/c").param::<&str>(3), None);
822 ///
823 /// assert_eq!(get("/1/b/3").param(0), Some(Ok(1)));
824 /// assert!(get("/1/b/3").param::<usize>(1).unwrap().is_err());
825 /// assert_eq!(get("/1/b/3").param(2), Some(Ok(3)));
826 ///
827 /// assert_eq!(get("/").param::<&str>(0), None);
828 /// ```
829 #[inline]
830 pub fn param<'a, T>(&'a self, n: usize) -> Option<Result<T, T::Error>>
831 where T: FromParam<'a>
832 {
833 self.routed_segment(n).map(T::from_param)
834 }
835
836 /// Retrieves and parses into `T` all of the path segments in the request
837 /// URI beginning and including the 0-indexed `n`th non-empty segment
838 /// _after_ the mount point.,that is, the `n`th segment _after_ the mount
839 /// point. If the request has not been routed, then this is simply the `n`th
840 /// non-empty request URI segment.
841 ///
842 /// `T` must implement [`FromSegments`], which is used to parse the
843 /// segments. If there are no non-empty segments, the `Segments` iterator
844 /// will be empty.
845 ///
846 /// This method exists only to be used by manual routing. To retrieve
847 /// segments from a request, use Rocket's code generation facilities.
848 ///
849 /// # Example
850 ///
851 /// ```rust
852 /// use std::path::PathBuf;
853 ///
854 /// # let c = rocket::local::blocking::Client::debug_with(vec![]).unwrap();
855 /// # let get = |uri| c.get(uri);
856 /// assert_eq!(get("/").segments(0..), Ok(PathBuf::new()));
857 /// assert_eq!(get("/").segments(2..), Ok(PathBuf::new()));
858 ///
859 /// // Empty segments are skipped.
860 /// assert_eq!(get("///").segments(2..), Ok(PathBuf::new()));
861 /// assert_eq!(get("/a/b/c").segments(0..), Ok(PathBuf::from("a/b/c")));
862 /// assert_eq!(get("/a/b/c").segments(1..), Ok(PathBuf::from("b/c")));
863 /// assert_eq!(get("/a/b/c").segments(2..), Ok(PathBuf::from("c")));
864 /// assert_eq!(get("/a/b/c").segments(3..), Ok(PathBuf::new()));
865 /// assert_eq!(get("/a/b/c").segments(4..), Ok(PathBuf::new()));
866 /// ```
867 #[inline]
868 pub fn segments<'a, T>(&'a self, n: RangeFrom<usize>) -> Result<T, T::Error>
869 where T: FromSegments<'a>
870 {
871 T::from_segments(self.routed_segments(n))
872 }
873
874 /// Retrieves and parses into `T` the query value with field name `name`.
875 /// `T` must implement [`FromForm`], which is used to parse the query's
876 /// value. Key matching is performed case-sensitively.
877 ///
878 /// # Warning
879 ///
880 /// This method exists _only_ to be used by manual routing and should
881 /// _never_ be used in a regular Rocket application. It is much more
882 /// expensive to use this method than to retrieve query parameters via
883 /// Rocket's codegen. To retrieve query values from a request, _always_
884 /// prefer to use Rocket's code generation facilities.
885 ///
886 /// # Error
887 ///
888 /// If a query segment with name `name` isn't present, returns `None`. If
889 /// parsing the value fails, returns `Some(Err(_))`.
890 ///
891 /// # Example
892 ///
893 /// ```rust
894 /// use rocket::form::FromForm;
895 ///
896 /// #[derive(Debug, PartialEq, FromForm)]
897 /// struct Dog<'r> {
898 /// name: &'r str,
899 /// age: usize
900 /// }
901 ///
902 /// # let c = rocket::local::blocking::Client::debug_with(vec![]).unwrap();
903 /// # let get = |uri| c.get(uri);
904 /// let req = get("/?a=apple&z=zebra&a=aardvark");
905 /// assert_eq!(req.query_value::<&str>("a").unwrap(), Ok("apple"));
906 /// assert_eq!(req.query_value::<&str>("z").unwrap(), Ok("zebra"));
907 /// assert_eq!(req.query_value::<&str>("b"), None);
908 ///
909 /// let a_seq = req.query_value::<Vec<&str>>("a");
910 /// assert_eq!(a_seq.unwrap().unwrap(), ["apple", "aardvark"]);
911 ///
912 /// let req = get("/?dog.name=Max+Fido&dog.age=3");
913 /// let dog = req.query_value::<Dog>("dog");
914 /// assert_eq!(dog.unwrap().unwrap(), Dog { name: "Max Fido", age: 3 });
915 /// ```
916 #[inline]
917 pub fn query_value<'a, T>(&'a self, name: &str) -> Option<form::Result<'a, T>>
918 where T: FromForm<'a>
919 {
920 if self.query_fields().find(|f| f.name == name).is_none() {
921 return None;
922 }
923
924 let mut ctxt = T::init(form::Options::Lenient);
925
926 self.query_fields()
927 .filter(|f| f.name == name)
928 .for_each(|f| T::push_value(&mut ctxt, f.shift()));
929
930 Some(T::finalize(ctxt))
931 }
932}
933
934// All of these methods only exist for internal, including codegen, purposes.
935// They _are not_ part of the stable API. Please, don't use these.
936#[doc(hidden)]
937impl<'r> Request<'r> {
938 /// Resets the cached value (if any) for the header with name `name`.
939 fn bust_header_cache(&mut self, name: &UncasedStr, replace: bool) {
940 if name == "Content-Type" {
941 if self.content_type().is_none() || replace {
942 self.state.content_type = InitCell::new();
943 }
944 } else if name == "Accept" {
945 if self.accept().is_none() || replace {
946 self.state.accept = InitCell::new();
947 }
948 }
949 }
950
951 /// Get the `n`th path segment, 0-indexed, after the mount point for the
952 /// currently matched route, as a string, if it exists. Used by codegen.
953 #[inline]
954 pub fn routed_segment(&self, n: usize) -> Option<&str> {
955 self.routed_segments(0..).get(n)
956 }
957
958 /// Get the segments beginning at the `n`th, 0-indexed, after the mount
959 /// point for the currently matched route, if they exist. Used by codegen.
960 #[inline]
961 pub fn routed_segments(&self, n: RangeFrom<usize>) -> Segments<'_, Path> {
962 let mount_segments = self.route()
963 .map(|r| r.uri.metadata.base_segs.len())
964 .unwrap_or(0);
965
966 self.uri().path().segments().skip(mount_segments + n.start)
967 }
968
969 // Retrieves the pre-parsed query items. Used by matching and codegen.
970 #[inline]
971 pub fn query_fields(&self) -> impl Iterator<Item = ValueField<'_>> {
972 self.uri().query()
973 .map(|q| q.segments().map(ValueField::from))
974 .into_iter()
975 .flatten()
976 }
977
978 /// Set `self`'s parameters given that the route used to reach this request
979 /// was `route`. Use during routing when attempting a given route.
980 #[inline(always)]
981 pub(crate) fn set_route(&self, route: &'r Route) {
982 *self.state.route.lock() = Some(route);
983 }
984
985 /// Set the method of `self`, even when `self` is a shared reference. Used
986 /// during routing to override methods for re-routing.
987 #[inline(always)]
988 pub(crate) fn _set_method(&self, method: Method) {
989 self.method.store(method)
990 }
991
992 pub(crate) fn cookies_mut(&mut self) -> &mut CookieJar<'r> {
993 &mut self.state.cookies
994 }
995
996 /// Convert from Hyper types into a Rocket Request.
997 pub(crate) fn from_hyp(
998 rocket: &'r Rocket<Orbit>,
999 hyper: &'r hyper::request::Parts,
1000 connection: Option<ConnectionMeta>,
1001 ) -> Result<Request<'r>, BadRequest<'r>> {
1002 // Keep track of parsing errors; emit a `BadRequest` if any exist.
1003 let mut errors = vec![];
1004
1005 // Ensure that the method is known. TODO: Allow made-up methods?
1006 let method = Method::from_hyp(&hyper.method)
1007 .unwrap_or_else(|| {
1008 errors.push(Kind::BadMethod(&hyper.method));
1009 Method::Get
1010 });
1011
1012 // TODO: Keep around not just the path/query, but the rest, if there?
1013 let uri = hyper.uri.path_and_query()
1014 .map(|uri| {
1015 // In debug, make sure we agree with Hyper about URI validity.
1016 // If we disagree, log a warning but continue anyway; if this is
1017 // a security issue with Hyper, there isn't much we can do.
1018 #[cfg(debug_assertions)]
1019 if Origin::parse(uri.as_str()).is_err() {
1020 warn!("Hyper/Rocket URI validity discord: {:?}", uri.as_str());
1021 info_!("Hyper believes the URI is valid while Rocket disagrees.");
1022 info_!("This is likely a Hyper bug with potential security implications.");
1023 warn_!("Please report this warning to Rocket's GitHub issue tracker.");
1024 }
1025
1026 Origin::new(uri.path(), uri.query().map(Cow::Borrowed))
1027 })
1028 .unwrap_or_else(|| {
1029 errors.push(Kind::InvalidUri(&hyper.uri));
1030 Origin::ROOT
1031 });
1032
1033 // Construct the request object; fill in metadata and headers next.
1034 let mut request = Request::new(rocket, method, uri);
1035
1036 // Set the passed in connection metadata.
1037 if let Some(connection) = connection {
1038 request.connection = connection;
1039 }
1040
1041 // Determine + set host. On HTTP < 2, use the `HOST` header. Otherwise,
1042 // use the `:authority` pseudo-header which hyper makes part of the URI.
1043 request.state.host = if hyper.version < hyper::Version::HTTP_2 {
1044 hyper.headers.get("host").and_then(|h| Host::parse_bytes(h.as_bytes()).ok())
1045 } else {
1046 hyper.uri.host().map(|h| Host::new(Authority::new(None, h, hyper.uri.port_u16())))
1047 };
1048
1049 // Set the request cookies, if they exist.
1050 for header in hyper.headers.get_all("Cookie") {
1051 let raw_str = match std::str::from_utf8(header.as_bytes()) {
1052 Ok(string) => string,
1053 Err(_) => continue
1054 };
1055
1056 for cookie_str in raw_str.split(';').map(|s| s.trim()) {
1057 if let Ok(cookie) = Cookie::parse_encoded(cookie_str) {
1058 request.state.cookies.add_original(cookie.into_owned());
1059 }
1060 }
1061 }
1062
1063 // Set the rest of the headers. This is rather unfortunate and slow.
1064 for (name, value) in hyper.headers.iter() {
1065 // FIXME: This is rather unfortunate. Header values needn't be UTF8.
1066 let value = match std::str::from_utf8(value.as_bytes()) {
1067 Ok(value) => value,
1068 Err(_) => {
1069 warn!("Header '{}' contains invalid UTF-8", name);
1070 warn_!("Rocket only supports UTF-8 header values. Dropping header.");
1071 continue;
1072 }
1073 };
1074
1075 request.add_header(Header::new(name.as_str(), value));
1076 }
1077
1078 if errors.is_empty() {
1079 Ok(request)
1080 } else {
1081 Err(BadRequest { request, errors })
1082 }
1083 }
1084}
1085
1086#[derive(Debug)]
1087pub(crate) struct BadRequest<'r> {
1088 pub request: Request<'r>,
1089 pub errors: Vec<Kind<'r>>,
1090}
1091
1092#[derive(Debug)]
1093pub(crate) enum Kind<'r> {
1094 InvalidUri(&'r hyper::Uri),
1095 BadMethod(&'r hyper::Method),
1096}
1097
1098impl fmt::Display for Kind<'_> {
1099 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1100 match self {
1101 Kind::InvalidUri(u) => write!(f, "invalid origin URI: {}", u),
1102 Kind::BadMethod(m) => write!(f, "invalid or unrecognized method: {}", m),
1103 }
1104 }
1105}
1106
1107impl fmt::Debug for Request<'_> {
1108 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1109 fmt.debug_struct("Request")
1110 .field("method", &self.method())
1111 .field("uri", &self.uri)
1112 .field("headers", &self.headers())
1113 .field("remote", &self.remote())
1114 .field("cookies", &self.cookies())
1115 .finish()
1116 }
1117}
1118
1119impl fmt::Display for Request<'_> {
1120 /// Pretty prints a Request. Primarily used by Rocket's logging.
1121 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1122 write!(f, "{} {}", self.method().green(), self.uri.blue())?;
1123
1124 // Print the requests media type when the route specifies a format.
1125 if let Some(mime) = self.format() {
1126 if !mime.is_any() {
1127 write!(f, " {}/{}", mime.top().yellow().linger(), mime.sub().resetting())?;
1128 }
1129 }
1130
1131 Ok(())
1132 }
1133}