Skip to main content

rocket/
lifecycle.rs

1use futures::future::{FutureExt, Future};
2
3use crate::trace::Trace;
4use crate::util::Formatter;
5use crate::data::IoHandler;
6use crate::http::{Method, Status, Header};
7use crate::outcome::Outcome;
8use crate::form::Form;
9use crate::{route, catcher, Rocket, Orbit, Request, Response, Data};
10
11// A token returned to force the execution of one method before another.
12pub(crate) struct RequestToken;
13
14async fn catch_handle<Fut, T, F>(name: Option<&str>, run: F) -> Option<T>
15    where F: FnOnce() -> Fut, Fut: Future<Output = T>,
16{
17    macro_rules! panic_info {
18        ($name:expr, $e:expr) => {{
19            error!(handler = name.as_ref().map(display),
20                "handler panicked\n\
21                This is an application bug.\n\
22                A panic in Rust must be treated as an exceptional event.\n\
23                Panicking is not a suitable error handling mechanism.\n\
24                Unwinding, the result of a panic, is an expensive operation.\n\
25                Panics will degrade application performance.\n\
26                Instead of panicking, return `Option` and/or `Result`.\n\
27                Values of either type can be returned directly from handlers.\n\
28                A panic is treated as an internal server error.");
29
30            $e
31        }}
32    }
33
34    let run = std::panic::AssertUnwindSafe(run);
35    let fut = std::panic::catch_unwind(run)
36        .map_err(|e| panic_info!(name, e))
37        .ok()?;
38
39    std::panic::AssertUnwindSafe(fut)
40        .catch_unwind()
41        .await
42        .map_err(|e| panic_info!(name, e))
43        .ok()
44}
45
46impl Rocket<Orbit> {
47    /// Preprocess the request for Rocket things. Currently, this means:
48    ///
49    ///   * Rewriting the method in the request if _method form field exists.
50    ///   * Run the request fairings.
51    ///
52    /// This is the only place during lifecycle processing that `Request` is
53    /// mutable. Keep this in-sync with the `FromForm` derive.
54    pub(crate) async fn preprocess(
55        &self,
56        req: &mut Request<'_>,
57        data: &mut Data<'_>
58    ) -> RequestToken {
59        // Check if this is a form and if the form contains the special _method
60        // field which we use to reinterpret the request's method.
61        if req.method() == Method::Post && req.content_type().map_or(false, |v| v.is_form()) {
62            let peek_buffer = data.peek(32).await;
63            let method = std::str::from_utf8(peek_buffer).ok()
64                .and_then(|raw_form| Form::values(raw_form).next())
65                .filter(|field| field.name == "_method")
66                .and_then(|field| field.value.parse().ok());
67
68            if let Some(method) = method {
69                req.set_method(method);
70            }
71        }
72
73        // Run request fairings.
74        self.fairings.handle_request(req, data).await;
75
76        RequestToken
77    }
78
79    /// Dispatches the request to the router and processes the outcome to
80    /// produce a response. If the initial outcome is a *forward* and the
81    /// request was a HEAD request, the request is rewritten and rerouted as a
82    /// GET. This is automatic HEAD handling. A request that failed to parse
83    /// isn't routed; its outcome is a `400` error.
84    ///
85    /// After performing the above, if the outcome is a forward or error, the
86    /// appropriate error catcher is invoked to produce the response. Otherwise,
87    /// the successful response is used directly.
88    ///
89    /// Finally, new cookies in the cookie jar are added to the response,
90    /// Rocket-specific headers are written, and response fairings are run. Note
91    /// that error responses have special cookie handling. See `handle_error`.
92    pub(crate) async fn dispatch<'r, 's: 'r>(
93        &'s self,
94        _token: RequestToken,
95        request: &'r Request<'s>,
96        data: Data<'r>,
97        // io_stream: impl Future<Output = io::Result<IoStream>> + Send,
98    ) -> Response<'r> {
99        // Remember if the request is `HEAD` for later body stripping.
100        let was_head_request = request.method() == Method::Head;
101
102        // Route the request and run the user's handlers.
103        let outcome = match request.errors.is_empty() {
104            true => self.route(request, data).await,
105            false => Outcome::Error(Status::BadRequest),
106        };
107
108        let mut response = match outcome {
109            Outcome::Success(response) => response,
110            Outcome::Forward((data, _)) if request.method() == Method::Head => {
111                tracing::Span::current().record("autohandled", true);
112
113                // Dispatch the request again with Method `GET`.
114                request._set_method(Method::Get);
115                match self.route(request, data).await {
116                    Outcome::Success(response) => response,
117                    Outcome::Error(status) => self.dispatch_error(status, request).await,
118                    Outcome::Forward((_, status)) => self.dispatch_error(status, request).await,
119                }
120            }
121            Outcome::Forward((_, status)) => self.dispatch_error(status, request).await,
122            Outcome::Error(status) => self.dispatch_error(status, request).await,
123        };
124
125        // Set the cookies. Note that error responses will only include cookies
126        // set by the error handler. See `handle_error` for more.
127        let delta_jar = request.cookies().take_delta_jar();
128        for cookie in delta_jar.delta() {
129            response.adjoin_header(cookie);
130        }
131
132        // Add a default 'Server' header if it isn't already there.
133        // TODO: If removing Hyper, write out `Date` header too.
134        if let Some(ident) = request.rocket().config.ident.as_str() {
135            if !response.headers().contains("Server") {
136                response.set_header(Header::new("Server", ident));
137            }
138        }
139
140        // Run the response fairings.
141        self.fairings.handle_response(request, &mut response).await;
142
143        // Strip the body if this is a `HEAD` request or a 304 response.
144        if was_head_request || response.status() == Status::NotModified {
145            response.strip_body();
146        }
147
148        // A 204 response has no body and neither framing header. Otherwise,
149        // content-length must not be sent with transfer-encoding; without the
150        // latter, use the body's size, if known, to set content-length.
151        if response.status() == Status::NoContent {
152            response.remove_header("Content-Length");
153            response.remove_header("Transfer-Encoding");
154            *response.body_mut() = crate::response::Body::unsized_none();
155        } else if response.headers().contains("Transfer-Encoding") {
156            response.remove_header("Content-Length");
157        } else if let Some(size) = response.body_mut().size().await {
158            response.set_raw_header("Content-Length", size.to_string());
159        }
160
161        if let Some(alt_svc) = request.rocket().alt_svc.as_deref() {
162            response.set_raw_header("Alt-Svc", alt_svc);
163        }
164
165        // TODO: Should upgrades be handled here? We miss them on local clients.
166        response
167    }
168
169    pub(crate) fn extract_io_handler<'r>(
170        request: &'r Request<'_>,
171        response: &mut Response<'r>,
172        // io_stream: impl Future<Output = io::Result<IoStream>> + Send,
173    ) -> Option<(String, Box<dyn IoHandler + 'r>)> {
174        let upgrades = request.headers().get("upgrade");
175        let Ok(upgrade) = response.search_upgrades(upgrades) else {
176            info!(
177                upgrades = %Formatter(|f| f.debug_list()
178                    .entries(request.headers().get("upgrade"))
179                    .finish()),
180                "request wants upgrade but no i/o handler matched\n\
181                refusing to upgrade request"
182            );
183
184            return None;
185        };
186
187        if let Some((proto, io_handler)) = upgrade {
188            let proto = proto.to_string();
189            response.set_status(Status::SwitchingProtocols);
190            response.set_raw_header("Connection", "Upgrade");
191            response.set_raw_header("Upgrade", proto.clone());
192            return Some((proto, io_handler));
193        }
194
195        None
196    }
197
198    /// Calls the handler for each matching route until one of the handlers
199    /// returns success or error, or there are no additional routes to try, in
200    /// which case a `Forward` with the last forwarding state is returned.
201    #[inline]
202    #[tracing::instrument("routing", skip_all, fields(
203        method = %request.method(),
204        uri = %request.uri(),
205        format = request.format().map(display),
206    ))]
207    async fn route<'s, 'r: 's>(
208        &'s self,
209        request: &'r Request<'s>,
210        mut data: Data<'r>,
211    ) -> route::Outcome<'r> {
212        // Go through all matching routes until we fail or succeed or run out of
213        // routes to try, in which case we forward with the last status.
214        let mut status = Status::NotFound;
215        for (id, route) in self.router.route(request) {
216            // Retrieve and set the requests parameters.
217            route.trace_info();
218            request.set_route(id);
219
220            let name = route.name.as_deref();
221            let outcome = catch_handle(name, || route.handler.handle(request, data)).await
222                .unwrap_or(Outcome::Error(Status::InternalServerError));
223
224            // Check if the request processing completed (Some) or if the
225            // request needs to be forwarded. If it does, continue the loop
226            outcome.trace_info();
227            match outcome {
228                o@Outcome::Success(_) | o@Outcome::Error(_) => return o,
229                Outcome::Forward(forwarded) => (data, status) = forwarded,
230            }
231        }
232
233        Outcome::Forward((data, status))
234    }
235
236    // Invokes the catcher for `status`. Returns the response on success.
237    //
238    // Resets the cookie jar delta state to prevent any modifications from
239    // earlier unsuccessful paths from being reflected in the error response.
240    //
241    // On catcher error, the 500 error catcher is attempted. If _that_ errors,
242    // the (infallible) default 500 error cather is used.
243    #[tracing::instrument("catching", skip_all, fields(status = status.code, uri = %req.uri()))]
244    pub(crate) async fn dispatch_error<'r, 's: 'r>(
245        &'s self,
246        mut status: Status,
247        req: &'r Request<'s>
248    ) -> Response<'r> {
249        // We may wish to relax this in the future.
250        req.cookies().reset_delta();
251
252        loop {
253            // Dispatch to the `status` catcher.
254            match self.invoke_catcher(status, req).await {
255                Ok(r) => return r,
256                // If the catcher failed, try `500` catcher, unless this is it.
257                Err(e) if status.code != 500 => {
258                    warn!(status = e.map(|r| r.code), "catcher failed: trying 500 catcher");
259                    status = Status::InternalServerError;
260                }
261                // The 500 catcher failed. There's no recourse. Use default.
262                Err(e) => {
263                    error!(status = e.map(|r| r.code), "500 catcher failed");
264                    return catcher::default_handler(Status::InternalServerError, req);
265                }
266            }
267        }
268    }
269
270    /// Invokes the handler with `req` for catcher with status `status`.
271    ///
272    /// In order of preference, invoked handler is:
273    ///   * the user's registered handler for `status`
274    ///   * the user's registered `default` handler
275    ///   * Rocket's default handler for `status`
276    ///
277    /// Return `Ok(result)` if the handler succeeded. Returns `Ok(Some(Status))`
278    /// if the handler ran to completion but failed. Returns `Ok(None)` if the
279    /// handler panicked while executing.
280    async fn invoke_catcher<'s, 'r: 's>(
281        &'s self,
282        status: Status,
283        req: &'r Request<'s>
284    ) -> Result<Response<'r>, Option<Status>> {
285        if let Some(catcher) = self.router.catch(status, req) {
286            catcher.trace_info();
287            catch_handle(catcher.name.as_deref(), || catcher.handler.handle(status, req)).await
288                .map(|result| result.map_err(Some))
289                .unwrap_or_else(|| Err(None))
290        } else {
291            info!(name: "catcher", name = "rocket::default", "uri.base" = "/", code = status.code,
292                "no registered catcher: using Rocket default");
293            Ok(catcher::default_handler(status, req))
294        }
295    }
296}