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