2020-06-19 13:01:10 +00:00
|
|
|
use std::{io, mem};
|
2019-05-19 17:58:19 +00:00
|
|
|
use std::sync::Arc;
|
2020-06-19 13:01:10 +00:00
|
|
|
use std::collections::HashMap;
|
2019-05-19 17:58:19 +00:00
|
|
|
|
2020-06-22 11:54:34 +00:00
|
|
|
#[allow(unused_imports)]
|
|
|
|
use futures::future::FutureExt;
|
2020-06-14 15:57:56 +00:00
|
|
|
use futures::stream::StreamExt;
|
2020-06-22 11:54:34 +00:00
|
|
|
use futures::future::{Future, BoxFuture};
|
2019-12-11 00:34:23 +00:00
|
|
|
use tokio::sync::{mpsc, oneshot};
|
2020-06-28 20:23:34 +00:00
|
|
|
use ref_cast::RefCast;
|
2016-08-24 08:30:09 +00:00
|
|
|
|
2017-06-02 04:44:31 +00:00
|
|
|
use yansi::Paint;
|
2017-01-21 03:31:46 +00:00
|
|
|
use state::Container;
|
|
|
|
|
2019-06-13 01:48:02 +00:00
|
|
|
use crate::{logger, handler};
|
2020-06-07 06:22:04 +00:00
|
|
|
use crate::config::{Config, FullConfig, ConfigError, LoggedValue};
|
2019-06-13 01:48:02 +00:00
|
|
|
use crate::request::{Request, FormItems};
|
|
|
|
use crate::data::Data;
|
2020-07-30 06:07:22 +00:00
|
|
|
use crate::catcher::Catcher;
|
2019-06-13 01:48:02 +00:00
|
|
|
use crate::response::{Body, Response};
|
|
|
|
use crate::router::{Router, Route};
|
|
|
|
use crate::outcome::Outcome;
|
|
|
|
use crate::error::{LaunchError, LaunchErrorKind};
|
|
|
|
use crate::fairing::{Fairing, Fairings};
|
2020-04-14 12:28:36 +00:00
|
|
|
use crate::logger::PaintExt;
|
2020-06-28 21:01:06 +00:00
|
|
|
use crate::ext::AsyncReadExt;
|
2020-07-23 02:22:32 +00:00
|
|
|
use crate::shutdown::Shutdown;
|
2019-06-13 01:48:02 +00:00
|
|
|
|
|
|
|
use crate::http::{Method, Status, Header};
|
2019-09-14 15:10:00 +00:00
|
|
|
use crate::http::private::{Listener, Connection, Incoming};
|
2019-06-13 01:48:02 +00:00
|
|
|
use crate::http::hyper::{self, header};
|
|
|
|
use crate::http::uri::Origin;
|
2016-04-01 23:54:53 +00:00
|
|
|
|
2016-11-04 13:35:04 +00:00
|
|
|
/// The main `Rocket` type: used to mount routes and catchers and launch the
|
2016-10-21 09:56:57 +00:00
|
|
|
/// application.
|
2016-04-01 23:54:53 +00:00
|
|
|
pub struct Rocket {
|
2020-06-28 05:59:40 +00:00
|
|
|
pub(crate) config: Config,
|
2020-07-23 02:22:32 +00:00
|
|
|
pub(crate) managed_state: Container,
|
|
|
|
manifest: Vec<PreLaunchOp>,
|
2020-06-28 05:59:40 +00:00
|
|
|
router: Router,
|
2020-07-30 06:07:22 +00:00
|
|
|
default_catcher: Option<Catcher>,
|
2020-06-28 05:59:40 +00:00
|
|
|
catchers: HashMap<u16, Catcher>,
|
|
|
|
fairings: Fairings,
|
|
|
|
shutdown_receiver: Option<mpsc::Receiver<()>>,
|
2020-07-23 02:22:32 +00:00
|
|
|
pub(crate) shutdown_handle: Shutdown,
|
2020-06-14 15:57:51 +00:00
|
|
|
}
|
|
|
|
|
2020-06-28 05:59:40 +00:00
|
|
|
/// An operation that occurs prior to launching a Rocket instance.
|
|
|
|
enum PreLaunchOp {
|
2020-06-14 15:57:51 +00:00
|
|
|
Mount(Origin<'static>, Vec<Route>),
|
|
|
|
Register(Vec<Catcher>),
|
2020-06-28 05:59:40 +00:00
|
|
|
Manage(&'static str, Box<dyn FnOnce(&mut Container) + Send + Sync + 'static>),
|
2020-06-14 15:57:51 +00:00
|
|
|
Attach(Box<dyn Fairing>),
|
|
|
|
}
|
|
|
|
|
2020-06-28 05:59:40 +00:00
|
|
|
/// A frozen view into the contents of an instance of `Rocket`.
|
2020-06-14 15:57:51 +00:00
|
|
|
///
|
2020-06-28 05:59:40 +00:00
|
|
|
/// Obtained via [`Rocket::inspect()`].
|
2020-06-28 20:23:34 +00:00
|
|
|
#[derive(RefCast)]
|
2020-06-28 05:59:40 +00:00
|
|
|
#[repr(transparent)]
|
|
|
|
pub struct Cargo(Rocket);
|
|
|
|
|
2020-07-03 04:20:28 +00:00
|
|
|
// A token returned to force the execution of one method before another.
|
|
|
|
pub(crate) struct Token;
|
|
|
|
|
2020-06-28 05:59:40 +00:00
|
|
|
impl Rocket {
|
|
|
|
#[inline]
|
|
|
|
fn _mount(&mut self, base: Origin<'static>, routes: Vec<Route>) {
|
|
|
|
info!("{}{} {}{}",
|
|
|
|
Paint::emoji("🛰 "),
|
|
|
|
Paint::magenta("Mounting"),
|
|
|
|
Paint::blue(&base),
|
|
|
|
Paint::magenta(":"));
|
|
|
|
|
2020-07-29 23:38:24 +00:00
|
|
|
for route in routes {
|
|
|
|
let old_route = route.clone();
|
|
|
|
let route = route.map_base(|old| format!("{}{}", base, old))
|
|
|
|
.unwrap_or_else(|e| {
|
|
|
|
error_!("Route `{}` has a malformed URI.", old_route);
|
|
|
|
error_!("{}", e);
|
|
|
|
panic!("Invalid route URI.");
|
|
|
|
});
|
2020-06-28 05:59:40 +00:00
|
|
|
|
|
|
|
info_!("{}", route);
|
|
|
|
self.router.add(route);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn _register(&mut self, catchers: Vec<Catcher>) {
|
|
|
|
info!("{}{}", Paint::emoji("👾 "), Paint::magenta("Catchers:"));
|
|
|
|
|
2020-07-30 06:07:22 +00:00
|
|
|
for catcher in catchers {
|
|
|
|
info_!("{}", catcher);
|
2020-06-28 05:59:40 +00:00
|
|
|
|
2020-07-30 06:07:22 +00:00
|
|
|
let existing = match catcher.code {
|
|
|
|
Some(code) => self.catchers.insert(code, catcher),
|
|
|
|
None => self.default_catcher.replace(catcher)
|
|
|
|
};
|
|
|
|
|
|
|
|
if let Some(existing) = existing {
|
|
|
|
warn_!("Replacing existing '{}' catcher.", existing);
|
|
|
|
}
|
2020-06-28 05:59:40 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
async fn _attach(mut self, fairing: Box<dyn Fairing>) -> Self {
|
|
|
|
// Attach (and run attach-) fairings, which requires us to move `self`.
|
|
|
|
let mut fairings = mem::replace(&mut self.fairings, Fairings::new());
|
|
|
|
self = fairings.attach(fairing, self).await;
|
|
|
|
|
|
|
|
// Note that `self.fairings` may now be non-empty! Move them to the end.
|
|
|
|
fairings.append(self.fairings);
|
|
|
|
self.fairings = fairings;
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2020-06-28 21:01:06 +00:00
|
|
|
// Create a "dummy" instance of `Rocket` to use while mem-swapping `self`.
|
|
|
|
fn dummy() -> Rocket {
|
|
|
|
Rocket {
|
|
|
|
manifest: vec![],
|
|
|
|
config: Config::development(),
|
|
|
|
router: Router::new(),
|
2020-07-30 06:07:22 +00:00
|
|
|
default_catcher: None,
|
2020-06-28 21:01:06 +00:00
|
|
|
catchers: HashMap::new(),
|
|
|
|
managed_state: Container::new(),
|
|
|
|
fairings: Fairings::new(),
|
2020-07-22 23:10:02 +00:00
|
|
|
shutdown_handle: Shutdown(mpsc::channel(1).0),
|
2020-06-28 21:01:06 +00:00
|
|
|
shutdown_receiver: None,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-06-28 05:59:40 +00:00
|
|
|
// Instead of requiring the user to individually `await` each call to
|
|
|
|
// `attach()`, some operations are queued in `self.pending`. Functions that
|
|
|
|
// want to provide read access to any data from the Cargo, such as
|
|
|
|
// `inspect()`, need to apply those pending operations first.
|
|
|
|
//
|
|
|
|
// This function returns a future that executes those pending operations,
|
|
|
|
// requiring only a single `await` at the call site. After completion,
|
|
|
|
// `self.pending` will be empty and `self.manifest` will reflect all pending
|
|
|
|
// changes.
|
2020-07-03 04:20:28 +00:00
|
|
|
async fn actualize_manifest(&mut self) {
|
|
|
|
// Note: attach fairings may add more ops to the `manifest`! We
|
|
|
|
// process them as a stack to maintain proper ordering.
|
|
|
|
let mut manifest = mem::replace(&mut self.manifest, vec![]);
|
|
|
|
while !manifest.is_empty() {
|
|
|
|
trace_!("[MANIEST PROGRESS]: {:?}", manifest);
|
|
|
|
match manifest.remove(0) {
|
|
|
|
PreLaunchOp::Manage(_, callback) => callback(&mut self.managed_state),
|
|
|
|
PreLaunchOp::Mount(base, routes) => self._mount(base, routes),
|
|
|
|
PreLaunchOp::Register(catchers) => self._register(catchers),
|
|
|
|
PreLaunchOp::Attach(fairing) => {
|
|
|
|
let rocket = mem::replace(self, Rocket::dummy());
|
|
|
|
*self = rocket._attach(fairing).await;
|
|
|
|
self.manifest.append(&mut manifest);
|
|
|
|
manifest = mem::replace(&mut self.manifest, vec![]);
|
2020-06-28 05:59:40 +00:00
|
|
|
}
|
|
|
|
}
|
2020-07-03 04:20:28 +00:00
|
|
|
}
|
2020-06-28 05:59:40 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
pub(crate) async fn into_cargo(mut self) -> Cargo {
|
|
|
|
self.actualize_manifest().await;
|
|
|
|
Cargo(self)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn cargo(&self) -> &Cargo {
|
|
|
|
if !self.manifest.is_empty() {
|
|
|
|
panic!("internal error: immutable launch state with manifest");
|
|
|
|
}
|
|
|
|
|
2020-06-28 20:23:34 +00:00
|
|
|
Cargo::ref_cast(self)
|
2020-06-28 05:59:40 +00:00
|
|
|
}
|
2016-04-11 10:57:23 +00:00
|
|
|
}
|
|
|
|
|
2020-06-28 05:59:40 +00:00
|
|
|
// This function tries to hide all of the Hyper-ness from Rocket. It essentially
|
|
|
|
// converts Hyper types into Rocket types, then calls the `dispatch` function,
|
|
|
|
// which knows nothing about Hyper. Because responding depends on the
|
|
|
|
// `HyperResponse` type, this function does the actual response processing.
|
2020-07-03 04:20:28 +00:00
|
|
|
async fn hyper_service_fn(
|
2020-06-28 05:59:40 +00:00
|
|
|
rocket: Arc<Rocket>,
|
2019-08-20 01:13:49 +00:00
|
|
|
h_addr: std::net::SocketAddr,
|
|
|
|
hyp_req: hyper::Request<hyper::Body>,
|
2020-07-03 04:20:28 +00:00
|
|
|
) -> Result<hyper::Response<hyper::Body>, io::Error> {
|
2019-08-20 01:13:49 +00:00
|
|
|
// This future must return a hyper::Response, but that's not easy
|
|
|
|
// because the response body might borrow from the request. Instead,
|
|
|
|
// we do the body writing in another future that will send us
|
|
|
|
// the response metadata (and a body channel) beforehand.
|
2019-09-08 20:56:57 +00:00
|
|
|
let (tx, rx) = oneshot::channel();
|
2019-08-20 01:13:49 +00:00
|
|
|
|
2019-09-22 22:48:08 +00:00
|
|
|
tokio::spawn(async move {
|
2019-08-20 01:13:49 +00:00
|
|
|
// Get all of the information from Hyper.
|
|
|
|
let (h_parts, h_body) = hyp_req.into_parts();
|
|
|
|
|
|
|
|
// Convert the Hyper request into a Rocket request.
|
2019-12-15 19:01:10 +00:00
|
|
|
let req_res = Request::from_hyp(&rocket, h_parts.method, h_parts.headers, &h_parts.uri, h_addr);
|
2019-08-20 01:13:49 +00:00
|
|
|
let mut req = match req_res {
|
|
|
|
Ok(req) => req,
|
|
|
|
Err(e) => {
|
|
|
|
error!("Bad incoming request: {}", e);
|
|
|
|
// TODO: We don't have a request to pass in, so we just
|
|
|
|
// fabricate one. This is weird. We should let the user know
|
|
|
|
// that we failed to parse a request (by invoking some special
|
|
|
|
// handler) instead of doing this.
|
|
|
|
let dummy = Request::new(&rocket, Method::Get, Origin::dummy());
|
|
|
|
let r = rocket.handle_error(Status::BadRequest, &dummy).await;
|
|
|
|
return rocket.issue_response(r, tx).await;
|
|
|
|
}
|
|
|
|
};
|
2016-10-09 11:29:02 +00:00
|
|
|
|
2019-08-20 01:13:49 +00:00
|
|
|
// Retrieve the data from the hyper body.
|
2020-07-30 11:17:38 +00:00
|
|
|
let mut data = Data::from_hyp(h_body).await;
|
2016-10-16 07:03:08 +00:00
|
|
|
|
2019-08-20 01:13:49 +00:00
|
|
|
// Dispatch the request to get a response, then write that response out.
|
2020-07-30 11:17:38 +00:00
|
|
|
let token = rocket.preprocess_request(&mut req, &mut data).await;
|
2020-07-03 04:20:28 +00:00
|
|
|
let r = rocket.dispatch(token, &mut req, data).await;
|
2019-08-20 01:13:49 +00:00
|
|
|
rocket.issue_response(r, tx).await;
|
2019-09-22 22:48:08 +00:00
|
|
|
});
|
2017-04-13 07:18:31 +00:00
|
|
|
|
2020-07-03 04:20:28 +00:00
|
|
|
rx.await.map_err(|e| io::Error::new(io::ErrorKind::Other, e))
|
2017-04-13 07:18:31 +00:00
|
|
|
}
|
|
|
|
|
2020-06-28 05:59:40 +00:00
|
|
|
impl Rocket {
|
2019-06-30 16:45:17 +00:00
|
|
|
#[inline]
|
2019-12-18 05:55:37 +00:00
|
|
|
async fn issue_response(
|
2019-06-30 16:45:17 +00:00
|
|
|
&self,
|
2019-12-18 05:55:37 +00:00
|
|
|
response: Response<'_>,
|
2019-09-08 20:56:57 +00:00
|
|
|
tx: oneshot::Sender<hyper::Response<hyper::Body>>,
|
2019-12-18 05:55:37 +00:00
|
|
|
) {
|
2019-06-30 16:45:17 +00:00
|
|
|
let result = self.write_response(response, tx);
|
2019-12-18 05:55:37 +00:00
|
|
|
match result.await {
|
|
|
|
Ok(()) => {
|
|
|
|
info_!("{}", Paint::green("Response succeeded."));
|
|
|
|
}
|
|
|
|
Err(e) => {
|
|
|
|
error_!("Failed to write response: {:?}.", e);
|
2019-06-30 16:45:17 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2016-12-15 08:47:31 +00:00
|
|
|
|
2017-04-24 08:33:00 +00:00
|
|
|
#[inline]
|
2019-12-18 05:55:37 +00:00
|
|
|
async fn write_response(
|
2019-06-30 16:45:17 +00:00
|
|
|
&self,
|
2019-12-18 05:55:37 +00:00
|
|
|
mut response: Response<'_>,
|
2019-09-08 20:56:57 +00:00
|
|
|
tx: oneshot::Sender<hyper::Response<hyper::Body>>,
|
2019-12-18 05:55:37 +00:00
|
|
|
) -> io::Result<()> {
|
|
|
|
let mut hyp_res = hyper::Response::builder()
|
|
|
|
.status(response.status().code);
|
|
|
|
|
|
|
|
for header in response.headers().iter() {
|
|
|
|
let name = header.name.as_str();
|
|
|
|
let value = header.value.as_bytes();
|
|
|
|
hyp_res = hyp_res.header(name, value);
|
|
|
|
}
|
2019-06-30 16:45:17 +00:00
|
|
|
|
2019-12-18 05:55:37 +00:00
|
|
|
let send_response = move |hyp_res: hyper::ResponseBuilder, body| -> io::Result<()> {
|
2020-06-19 13:01:10 +00:00
|
|
|
let response = hyp_res.body(body)
|
|
|
|
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
|
|
|
|
|
|
|
|
tx.send(response).map_err(|_| {
|
|
|
|
let msg = "Client disconnected before the response was started";
|
|
|
|
io::Error::new(io::ErrorKind::BrokenPipe, msg)
|
|
|
|
})
|
2019-12-18 05:55:37 +00:00
|
|
|
};
|
2019-06-30 16:45:17 +00:00
|
|
|
|
2020-06-22 11:54:34 +00:00
|
|
|
match response.body_mut() {
|
2019-12-18 05:55:37 +00:00
|
|
|
None => {
|
|
|
|
hyp_res = hyp_res.header(header::CONTENT_LENGTH, "0");
|
|
|
|
send_response(hyp_res, hyper::Body::empty())?;
|
|
|
|
}
|
2020-01-24 22:34:17 +00:00
|
|
|
Some(body) => {
|
2020-06-19 13:01:10 +00:00
|
|
|
if let Some(s) = body.size().await {
|
|
|
|
hyp_res = hyp_res.header(header::CONTENT_LENGTH, s.to_string());
|
|
|
|
}
|
|
|
|
|
|
|
|
let chunk_size = match *body {
|
|
|
|
Body::Chunked(_, chunk_size) => chunk_size as usize,
|
|
|
|
Body::Sized(_, _) => crate::response::DEFAULT_CHUNK_SIZE,
|
2020-01-24 22:34:17 +00:00
|
|
|
};
|
2019-06-30 16:45:17 +00:00
|
|
|
|
2019-12-18 05:55:37 +00:00
|
|
|
let (mut sender, hyp_body) = hyper::Body::channel();
|
|
|
|
send_response(hyp_res, hyp_body)?;
|
2019-06-30 16:45:17 +00:00
|
|
|
|
2020-06-19 13:01:10 +00:00
|
|
|
let mut stream = body.as_reader().into_bytes_stream(chunk_size);
|
2019-12-18 05:55:37 +00:00
|
|
|
while let Some(next) = stream.next().await {
|
2020-06-19 13:01:10 +00:00
|
|
|
sender.send_data(next?).await
|
|
|
|
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
|
2019-06-30 16:45:17 +00:00
|
|
|
}
|
2019-12-18 05:55:37 +00:00
|
|
|
}
|
|
|
|
};
|
2019-06-30 16:45:17 +00:00
|
|
|
|
2019-12-18 05:55:37 +00:00
|
|
|
Ok(())
|
2016-12-15 08:47:31 +00:00
|
|
|
}
|
|
|
|
|
2017-01-13 15:50:51 +00:00
|
|
|
/// Preprocess the request for Rocket things. Currently, this means:
|
|
|
|
///
|
|
|
|
/// * Rewriting the method in the request if _method form field exists.
|
2020-07-03 04:20:28 +00:00
|
|
|
/// * Run the request fairings.
|
2017-01-13 15:50:51 +00:00
|
|
|
///
|
|
|
|
/// Keep this in-sync with derive_form when preprocessing form fields.
|
2020-07-03 04:20:28 +00:00
|
|
|
pub(crate) async fn preprocess_request(
|
|
|
|
&self,
|
|
|
|
req: &mut Request<'_>,
|
2020-07-30 11:17:38 +00:00
|
|
|
data: &mut Data
|
2020-07-03 04:20:28 +00:00
|
|
|
) -> Token {
|
2016-10-16 10:21:34 +00:00
|
|
|
// Check if this is a form and if the form contains the special _method
|
|
|
|
// field which we use to reinterpret the request's method.
|
|
|
|
let (min_len, max_len) = ("_method=get".len(), "_method=delete".len());
|
2020-07-30 11:17:38 +00:00
|
|
|
let peek_buffer = data.peek(max_len).await;
|
2017-02-01 11:12:24 +00:00
|
|
|
let is_form = req.content_type().map_or(false, |ct| ct.is_form());
|
2018-02-20 11:27:18 +00:00
|
|
|
|
2020-07-30 11:17:38 +00:00
|
|
|
if is_form && req.method() == Method::Post && peek_buffer.len() >= min_len {
|
|
|
|
if let Ok(form) = std::str::from_utf8(peek_buffer) {
|
2018-02-14 22:02:56 +00:00
|
|
|
let method: Option<Result<Method, _>> = FormItems::from(form)
|
2018-09-20 04:14:30 +00:00
|
|
|
.filter(|item| item.key.as_str() == "_method")
|
|
|
|
.map(|item| item.value.parse())
|
2018-02-14 22:02:56 +00:00
|
|
|
.next();
|
|
|
|
|
|
|
|
if let Some(Ok(method)) = method {
|
2020-07-03 04:20:28 +00:00
|
|
|
req._set_method(method);
|
2016-10-16 10:21:34 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-07-03 04:20:28 +00:00
|
|
|
|
|
|
|
// Run request fairings.
|
|
|
|
self.fairings.handle_request(req, data).await;
|
|
|
|
|
|
|
|
Token
|
2016-10-16 10:21:34 +00:00
|
|
|
}
|
|
|
|
|
2018-04-08 23:14:15 +00:00
|
|
|
/// Route the request and process the outcome to eventually get a response.
|
2019-06-30 16:45:17 +00:00
|
|
|
fn route_and_process<'s, 'r: 's>(
|
2018-02-04 10:07:28 +00:00
|
|
|
&'s self,
|
|
|
|
request: &'r Request<'s>,
|
|
|
|
data: Data
|
2019-06-30 16:45:17 +00:00
|
|
|
) -> impl Future<Output = Response<'r>> + Send + 's {
|
|
|
|
async move {
|
|
|
|
let mut response = match self.route(request, data).await {
|
|
|
|
Outcome::Success(response) => response,
|
|
|
|
Outcome::Forward(data) => {
|
|
|
|
// There was no matching route. Autohandle `HEAD` requests.
|
|
|
|
if request.method() == Method::Head {
|
|
|
|
info_!("Autohandling {} request.", Paint::default("HEAD").bold());
|
|
|
|
|
|
|
|
// Dispatch the request again with Method `GET`.
|
|
|
|
request._set_method(Method::Get);
|
|
|
|
|
|
|
|
// Return early so we don't set cookies twice.
|
2019-09-06 17:14:27 +00:00
|
|
|
let try_next: BoxFuture<'_, _> = Box::pin(self.route_and_process(request, data));
|
2019-06-30 16:45:17 +00:00
|
|
|
return try_next.await;
|
|
|
|
} else {
|
|
|
|
// No match was found and it can't be autohandled. 404.
|
|
|
|
self.handle_error(Status::NotFound, request).await
|
|
|
|
}
|
2016-12-16 13:17:16 +00:00
|
|
|
}
|
2019-06-30 16:45:17 +00:00
|
|
|
Outcome::Failure(status) => self.handle_error(status, request).await,
|
|
|
|
};
|
|
|
|
|
|
|
|
// Set the cookies. Note that error responses will only include
|
|
|
|
// cookies set by the error handler. See `handle_error` for more.
|
|
|
|
for cookie in request.cookies().delta() {
|
|
|
|
response.adjoin_header(cookie);
|
2016-12-16 13:17:16 +00:00
|
|
|
}
|
2020-01-24 05:07:11 +00:00
|
|
|
|
2019-06-30 16:45:17 +00:00
|
|
|
response
|
2018-04-08 23:14:15 +00:00
|
|
|
}
|
2016-12-16 13:17:16 +00:00
|
|
|
}
|
|
|
|
|
2016-11-04 13:35:04 +00:00
|
|
|
/// Tries to find a `Responder` for a given `request`. It does this by
|
|
|
|
/// routing the request and calling the handler for each matching route
|
2017-01-06 06:42:24 +00:00
|
|
|
/// until one of the handlers returns success or failure, or there are no
|
|
|
|
/// additional routes to try (forward). The corresponding outcome for each
|
|
|
|
/// condition is returned.
|
2017-05-27 02:48:50 +00:00
|
|
|
//
|
2017-05-30 01:10:07 +00:00
|
|
|
// TODO: We _should_ be able to take an `&mut` here and mutate the request
|
2017-05-27 02:48:50 +00:00
|
|
|
// at any pointer _before_ we pass it to a handler as long as we drop the
|
|
|
|
// outcome. That should be safe. Since no mutable borrow can be held
|
|
|
|
// (ensuring `handler` takes an immutable borrow), any caller to `route`
|
|
|
|
// should be able to supply an `&mut` and retain an `&` after the call.
|
2017-02-03 10:16:46 +00:00
|
|
|
#[inline]
|
2019-06-30 16:45:17 +00:00
|
|
|
pub(crate) fn route<'s, 'r: 's>(
|
2017-09-05 03:11:10 +00:00
|
|
|
&'s self,
|
|
|
|
request: &'r Request<'s>,
|
|
|
|
mut data: Data,
|
2019-06-30 16:45:17 +00:00
|
|
|
) -> impl Future<Output = handler::Outcome<'r>> + 's {
|
|
|
|
async move {
|
|
|
|
// Go through the list of matching routes until we fail or succeed.
|
|
|
|
let matches = self.router.route(request);
|
|
|
|
for route in matches {
|
|
|
|
// Retrieve and set the requests parameters.
|
|
|
|
info_!("Matched: {}", route);
|
|
|
|
request.set_route(route);
|
|
|
|
|
|
|
|
// Dispatch the request to the handler.
|
|
|
|
let outcome = route.handler.handle(request, data).await;
|
|
|
|
|
2020-07-03 04:20:28 +00:00
|
|
|
// Check if the request processing completed (Some) or if the
|
|
|
|
// request needs to be forwarded. If it does, continue the loop
|
|
|
|
// (None) to try again.
|
2019-06-30 16:45:17 +00:00
|
|
|
info_!("{} {}", Paint::default("Outcome:").bold(), outcome);
|
|
|
|
match outcome {
|
|
|
|
o@Outcome::Success(_) | o@Outcome::Failure(_) => return o,
|
|
|
|
Outcome::Forward(unused_data) => data = unused_data,
|
|
|
|
}
|
|
|
|
}
|
2016-08-27 04:34:28 +00:00
|
|
|
|
2019-06-30 16:45:17 +00:00
|
|
|
error_!("No matching routes for {}.", request);
|
|
|
|
Outcome::Forward(data)
|
|
|
|
}
|
2016-08-26 08:55:11 +00:00
|
|
|
}
|
2016-04-11 10:57:23 +00:00
|
|
|
|
2020-06-28 05:59:40 +00:00
|
|
|
#[inline]
|
2020-07-03 04:20:28 +00:00
|
|
|
pub(crate) async fn dispatch<'s, 'r: 's>(
|
2020-06-28 05:59:40 +00:00
|
|
|
&'s self,
|
2020-07-03 04:20:28 +00:00
|
|
|
_token: Token,
|
|
|
|
request: &'r Request<'s>,
|
2020-06-28 05:59:40 +00:00
|
|
|
data: Data
|
2020-07-03 04:20:28 +00:00
|
|
|
) -> Response<'r> {
|
|
|
|
info!("{}:", request);
|
2020-06-28 05:59:40 +00:00
|
|
|
|
2020-07-03 04:20:28 +00:00
|
|
|
// Remember if the request is `HEAD` for later body stripping.
|
|
|
|
let was_head_request = request.method() == Method::Head;
|
2020-06-28 05:59:40 +00:00
|
|
|
|
2020-07-03 04:20:28 +00:00
|
|
|
// Route the request and run the user's handlers.
|
|
|
|
let mut response = self.route_and_process(request, data).await;
|
2020-06-28 05:59:40 +00:00
|
|
|
|
2020-07-03 04:20:28 +00:00
|
|
|
// Add a default 'Server' header if it isn't already there.
|
|
|
|
// TODO: If removing Hyper, write out `Date` header too.
|
|
|
|
if !response.headers().contains("Server") {
|
|
|
|
response.set_header(Header::new("Server", "Rocket"));
|
|
|
|
}
|
2020-06-28 05:59:40 +00:00
|
|
|
|
2020-07-03 04:20:28 +00:00
|
|
|
// Run the response fairings.
|
|
|
|
self.fairings.handle_response(request, &mut response).await;
|
2020-06-28 05:59:40 +00:00
|
|
|
|
2020-07-03 04:20:28 +00:00
|
|
|
// Strip the body if this is a `HEAD` request.
|
|
|
|
if was_head_request {
|
|
|
|
response.strip_body();
|
2020-06-28 05:59:40 +00:00
|
|
|
}
|
2020-07-03 04:20:28 +00:00
|
|
|
|
|
|
|
response
|
2020-06-28 05:59:40 +00:00
|
|
|
}
|
|
|
|
|
2018-02-20 11:27:18 +00:00
|
|
|
// Finds the error catcher for the status `status` and executes it for the
|
2019-06-30 16:45:17 +00:00
|
|
|
// given request `req`. If a user has registered a catcher for `status`, the
|
|
|
|
// catcher is called. If the catcher fails to return a good response, the
|
|
|
|
// 500 catcher is executed. If there is no registered catcher for `status`,
|
|
|
|
// the default catcher is used.
|
|
|
|
pub(crate) fn handle_error<'s, 'r: 's>(
|
|
|
|
&'s self,
|
Overhaul URI types.
This is fairly large commit with several entangled logical changes.
The primary change in this commit is to completely overhaul how URI
handling in Rocket works. Prior to this commit, the `Uri` type acted as
an origin API. Its parser was minimal and lenient, allowing URIs that
were invalid according to RFC 7230. By contrast, the new `Uri` type
brings with it a strict RFC 7230 compliant parser. The `Uri` type now
represents any kind of valid URI, not simply `Origin` types. Three new
URI types were introduced:
* `Origin` - represents valid origin URIs
* `Absolute` - represents valid absolute URIs
* `Authority` - represents valid authority URIs
The `Origin` type replaces `Uri` in many cases:
* As fields and method inputs of `Route`
* The `&Uri` request guard is now `&Origin`
* The `uri!` macro produces an `Origin` instead of a `Uri`
The strict nature of URI parsing cascaded into the following changes:
* Several `Route` methods now `panic!` on invalid URIs
* The `Rocket::mount()` method is (correctly) stricter with URIs
* The `Redirect` constructors take a `TryInto<Uri>` type
* Dispatching of a `LocalRequest` correctly validates URIs
Overall, URIs are now properly and uniformly handled throughout Rocket's
codebase, resulting in a more reliable and correct system.
In addition to these URI changes, the following changes are also part of
this commit:
* The `LocalRequest::cloned_dispatch()` method was removed in favor of
chaining `.clone().dispatch()`.
* The entire Rocket codebase uses `crate` instead of `pub(crate)` as a
visibility modifier.
* Rocket uses the `crate_visibility_modifier` and `try_from` features.
A note on unsafety: this commit introduces many uses of `unsafe` in the
URI parser. All of these uses are a result of unsafely transforming byte
slices (`&[u8]` or similar) into strings (`&str`). The parser ensures
that these casts are safe, but of course, we must label their use
`unsafe`. The parser was written to be as generic and efficient as
possible and thus can parse directly from byte sources. Rocket, however,
does not make use of this fact and so would be able to remove all uses
of `unsafe` by parsing from an existing `&str`. This should be
considered in the future.
Fixes #443.
Resolves #263.
2018-07-29 01:26:15 +00:00
|
|
|
status: Status,
|
2019-06-30 16:45:17 +00:00
|
|
|
req: &'r Request<'s>
|
|
|
|
) -> impl Future<Output = Response<'r>> + 's {
|
|
|
|
async move {
|
|
|
|
warn_!("Responding with {} catcher.", Paint::red(&status));
|
|
|
|
|
|
|
|
// For now, we reset the delta state to prevent any modifications
|
|
|
|
// from earlier, unsuccessful paths from being reflected in error
|
|
|
|
// response. We may wish to relax this in the future.
|
|
|
|
req.cookies().reset_delta();
|
|
|
|
|
|
|
|
// Try to get the active catcher but fallback to user's 500 catcher.
|
2020-07-30 06:07:22 +00:00
|
|
|
let code = Paint::red(status.code);
|
|
|
|
let response = if let Some(catcher) = self.catchers.get(&status.code) {
|
|
|
|
catcher.handler.handle(status, req).await
|
|
|
|
} else if let Some(ref default) = self.default_catcher {
|
|
|
|
warn_!("No {} catcher found. Using default catcher.", code);
|
|
|
|
default.handler.handle(status, req).await
|
|
|
|
} else {
|
|
|
|
warn_!("No {} or default catcher found. Using Rocket default catcher.", code);
|
|
|
|
crate::catcher::default(status, req)
|
|
|
|
};
|
|
|
|
|
|
|
|
// Dispatch to the catcher. If it fails, use the Rocket default 500.
|
|
|
|
match response {
|
|
|
|
Ok(r) => r,
|
2019-06-30 16:45:17 +00:00
|
|
|
Err(err_status) => {
|
2020-07-30 06:07:22 +00:00
|
|
|
error_!("Catcher unexpectedly failed with {}.", err_status);
|
|
|
|
warn_!("Using Rocket's default 500 error catcher.");
|
|
|
|
let default = crate::catcher::default(Status::InternalServerError, req);
|
|
|
|
default.expect("Rocket has default 500 response")
|
2019-06-30 16:45:17 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2016-04-11 10:57:23 +00:00
|
|
|
}
|
2020-06-14 15:57:51 +00:00
|
|
|
|
|
|
|
// TODO.async: Solidify the Listener APIs and make this function public
|
|
|
|
async fn listen_on<L>(mut self, listener: L) -> Result<(), crate::error::Error>
|
2020-06-28 05:59:40 +00:00
|
|
|
where L: Listener + Send + Unpin + 'static,
|
|
|
|
<L as Listener>::Connection: Send + Unpin + 'static,
|
2020-06-14 15:57:51 +00:00
|
|
|
{
|
|
|
|
// Determine the address and port we actually binded to.
|
|
|
|
self.config.port = listener.local_addr().map(|a| a.port()).unwrap_or(0);
|
|
|
|
let proto = self.config.tls.as_ref().map_or("http://", |_| "https://");
|
|
|
|
let full_addr = format!("{}:{}", self.config.address, self.config.port);
|
|
|
|
|
|
|
|
// Freeze managed state for synchronization-free accesses later.
|
2020-06-28 05:59:40 +00:00
|
|
|
self.managed_state.freeze();
|
2020-06-14 15:57:51 +00:00
|
|
|
|
|
|
|
// Run the launch fairings.
|
2020-06-28 05:59:40 +00:00
|
|
|
self.fairings.pretty_print_counts();
|
|
|
|
self.fairings.handle_launch(self.cargo());
|
2020-06-14 15:57:51 +00:00
|
|
|
|
|
|
|
launch_info!("{}{} {}{}",
|
|
|
|
Paint::emoji("🚀 "),
|
|
|
|
Paint::default("Rocket has launched from").bold(),
|
|
|
|
Paint::default(proto).bold().underline(),
|
|
|
|
Paint::default(&full_addr).bold().underline());
|
|
|
|
|
|
|
|
// Restore the log level back to what it originally was.
|
|
|
|
logger::pop_max_level();
|
|
|
|
|
2020-06-28 05:59:40 +00:00
|
|
|
// Set the keep-alive.
|
|
|
|
// TODO.async: implement keep-alive in Listener
|
|
|
|
// let timeout = self.config.keep_alive.map(|s| Duration::from_secs(s as u64));
|
|
|
|
// listener.set_keepalive(timeout);
|
|
|
|
|
2020-06-14 15:57:51 +00:00
|
|
|
// We need to get this before moving `self` into an `Arc`.
|
|
|
|
let mut shutdown_receiver = self.shutdown_receiver
|
|
|
|
.take().expect("shutdown receiver has already been used");
|
|
|
|
|
|
|
|
let rocket = Arc::new(self);
|
|
|
|
let service = hyper::make_service_fn(move |connection: &<L as Listener>::Connection| {
|
|
|
|
let rocket = rocket.clone();
|
|
|
|
let remote_addr = connection.remote_addr().unwrap_or_else(|| ([0, 0, 0, 0], 0).into());
|
|
|
|
async move {
|
|
|
|
Ok::<_, std::convert::Infallible>(hyper::service_fn(move |req| {
|
|
|
|
hyper_service_fn(rocket.clone(), remote_addr, req)
|
|
|
|
}))
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
#[derive(Clone)]
|
|
|
|
struct TokioExecutor;
|
|
|
|
|
2020-07-09 05:05:54 +00:00
|
|
|
impl<Fut> hyper::Executor<Fut> for TokioExecutor
|
|
|
|
where Fut: Future + Send + 'static, Fut::Output: Send
|
|
|
|
{
|
2020-06-14 15:57:51 +00:00
|
|
|
fn execute(&self, fut: Fut) {
|
|
|
|
tokio::spawn(fut);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
hyper::Server::builder(Incoming::from_listener(listener))
|
|
|
|
.executor(TokioExecutor)
|
|
|
|
.serve(service)
|
|
|
|
.with_graceful_shutdown(async move { shutdown_receiver.recv().await; })
|
|
|
|
.await
|
|
|
|
.map_err(|e| crate::error::Error::Run(Box::new(e)))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-05-19 17:58:19 +00:00
|
|
|
impl Rocket {
|
2016-11-04 13:35:04 +00:00
|
|
|
/// Create a new `Rocket` application using the configuration information in
|
|
|
|
/// `Rocket.toml`. If the file does not exist or if there is an I/O error
|
2020-07-09 02:29:18 +00:00
|
|
|
/// reading the file, the defaults, overridden by any environment-based
|
|
|
|
/// paramparameters, are used. See the [`config`](crate::config)
|
|
|
|
/// documentation for more information on defaults.
|
2016-11-04 13:35:04 +00:00
|
|
|
///
|
2018-10-06 13:25:17 +00:00
|
|
|
/// This method is typically called through the
|
2019-06-13 01:48:02 +00:00
|
|
|
/// [`rocket::ignite()`](crate::ignite) alias.
|
2016-11-04 13:35:04 +00:00
|
|
|
///
|
|
|
|
/// # Panics
|
|
|
|
///
|
2020-06-07 06:22:04 +00:00
|
|
|
/// If there is an error reading configuration sources, this function prints
|
|
|
|
/// a nice error message and then exits the process.
|
2016-11-04 13:35:04 +00:00
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// # {
|
|
|
|
/// rocket::ignite()
|
|
|
|
/// # };
|
|
|
|
/// ```
|
|
|
|
pub fn ignite() -> Rocket {
|
2020-06-07 06:22:04 +00:00
|
|
|
Config::read()
|
|
|
|
.or_else(|e| match e {
|
|
|
|
ConfigError::IoError => {
|
|
|
|
warn!("Failed to read 'Rocket.toml'. Using defaults.");
|
2020-07-09 02:29:18 +00:00
|
|
|
Ok(FullConfig::env_default()?.take_active())
|
2020-06-07 06:22:04 +00:00
|
|
|
}
|
2020-07-09 02:29:18 +00:00
|
|
|
ConfigError::NotFound => Ok(FullConfig::env_default()?.take_active()),
|
2020-06-07 06:22:04 +00:00
|
|
|
_ => Err(e)
|
|
|
|
})
|
|
|
|
.map(Rocket::configured)
|
|
|
|
.unwrap_or_else(|e: ConfigError| {
|
|
|
|
logger::init(logger::LoggingLevel::Debug);
|
|
|
|
e.pretty_print();
|
|
|
|
std::process::exit(1)
|
|
|
|
})
|
2016-11-04 13:35:04 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Creates a new `Rocket` application using the supplied custom
|
2019-02-07 01:18:11 +00:00
|
|
|
/// configuration. The `Rocket.toml` file, if present, is ignored. Any
|
|
|
|
/// environment variables setting config parameters are ignored.
|
2016-11-04 13:35:04 +00:00
|
|
|
///
|
|
|
|
/// This method is typically called through the `rocket::custom` alias.
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// use rocket::config::{Config, Environment};
|
|
|
|
/// # use rocket::config::ConfigError;
|
|
|
|
///
|
2017-02-02 10:16:21 +00:00
|
|
|
/// # #[allow(dead_code)]
|
2016-11-04 13:35:04 +00:00
|
|
|
/// # fn try_config() -> Result<(), ConfigError> {
|
2017-01-12 02:31:37 +00:00
|
|
|
/// let config = Config::build(Environment::Staging)
|
|
|
|
/// .address("1.2.3.4")
|
|
|
|
/// .port(9234)
|
|
|
|
/// .finalize()?;
|
2016-11-04 13:35:04 +00:00
|
|
|
///
|
2017-02-02 10:16:21 +00:00
|
|
|
/// # #[allow(unused_variables)]
|
2018-07-03 20:47:17 +00:00
|
|
|
/// let app = rocket::custom(config);
|
2016-11-04 13:35:04 +00:00
|
|
|
/// # Ok(())
|
|
|
|
/// # }
|
|
|
|
/// ```
|
2017-05-19 10:29:08 +00:00
|
|
|
#[inline]
|
2018-07-03 20:47:17 +00:00
|
|
|
pub fn custom(config: Config) -> Rocket {
|
|
|
|
Rocket::configured(config)
|
2017-01-12 02:31:37 +00:00
|
|
|
}
|
|
|
|
|
2017-05-19 10:29:08 +00:00
|
|
|
#[inline]
|
2018-07-03 20:47:17 +00:00
|
|
|
fn configured(config: Config) -> Rocket {
|
|
|
|
if logger::try_init(config.log_level, false) {
|
|
|
|
// Temporary weaken log level for launch info.
|
2018-01-29 21:16:04 +00:00
|
|
|
logger::push_max_level(logger::LoggingLevel::Normal);
|
2017-01-12 02:31:37 +00:00
|
|
|
}
|
|
|
|
|
2020-04-14 12:28:36 +00:00
|
|
|
launch_info!("{}Configured for {}.", Paint::emoji("🔧 "), config.environment);
|
2018-11-19 10:11:38 +00:00
|
|
|
launch_info_!("address: {}", Paint::default(&config.address).bold());
|
|
|
|
launch_info_!("port: {}", Paint::default(&config.port).bold());
|
|
|
|
launch_info_!("log: {}", Paint::default(config.log_level).bold());
|
|
|
|
launch_info_!("workers: {}", Paint::default(config.workers).bold());
|
|
|
|
launch_info_!("secret key: {}", Paint::default(&config.secret_key).bold());
|
|
|
|
launch_info_!("limits: {}", Paint::default(&config.limits).bold());
|
2016-12-22 09:29:58 +00:00
|
|
|
|
2018-02-17 12:06:05 +00:00
|
|
|
match config.keep_alive {
|
2018-11-19 10:11:38 +00:00
|
|
|
Some(v) => launch_info_!("keep-alive: {}", Paint::default(format!("{}s", v)).bold()),
|
|
|
|
None => launch_info_!("keep-alive: {}", Paint::default("disabled").bold()),
|
2018-02-17 12:06:05 +00:00
|
|
|
}
|
|
|
|
|
2017-04-13 07:18:31 +00:00
|
|
|
let tls_configured = config.tls.is_some();
|
|
|
|
if tls_configured && cfg!(feature = "tls") {
|
2018-11-19 10:11:38 +00:00
|
|
|
launch_info_!("tls: {}", Paint::default("enabled").bold());
|
2017-06-09 06:33:16 +00:00
|
|
|
} else if tls_configured {
|
2018-11-19 10:11:38 +00:00
|
|
|
error_!("tls: {}", Paint::default("disabled").bold());
|
2017-06-09 06:33:16 +00:00
|
|
|
error_!("tls is configured, but the tls feature is disabled");
|
2017-04-13 07:18:31 +00:00
|
|
|
} else {
|
2018-11-19 10:11:38 +00:00
|
|
|
launch_info_!("tls: {}", Paint::default("disabled").bold());
|
2017-06-09 06:33:16 +00:00
|
|
|
}
|
|
|
|
|
2018-11-09 07:37:37 +00:00
|
|
|
if config.secret_key.is_generated() && config.environment.is_prod() {
|
|
|
|
warn!("environment is 'production', but no `secret_key` is configured");
|
2017-04-13 07:18:31 +00:00
|
|
|
}
|
|
|
|
|
2016-11-04 13:35:04 +00:00
|
|
|
for (name, value) in config.extras() {
|
2018-01-20 18:41:29 +00:00
|
|
|
launch_info_!("{} {}: {}",
|
2018-11-19 10:11:38 +00:00
|
|
|
Paint::yellow("[extra]"), name,
|
|
|
|
Paint::default(LoggedValue(value)).bold());
|
2016-11-04 13:35:04 +00:00
|
|
|
}
|
|
|
|
|
2020-06-28 05:59:40 +00:00
|
|
|
let managed_state = Container::new();
|
2019-08-25 02:19:11 +00:00
|
|
|
let (shutdown_sender, shutdown_receiver) = mpsc::channel(1);
|
|
|
|
|
2020-06-28 05:59:40 +00:00
|
|
|
Rocket {
|
2020-07-23 02:22:32 +00:00
|
|
|
config, managed_state,
|
|
|
|
shutdown_handle: Shutdown(shutdown_sender),
|
2020-06-28 05:59:40 +00:00
|
|
|
manifest: vec![],
|
2016-11-04 13:35:04 +00:00
|
|
|
router: Router::new(),
|
2020-07-30 06:07:22 +00:00
|
|
|
default_catcher: None,
|
|
|
|
catchers: HashMap::new(),
|
2017-09-05 03:11:10 +00:00
|
|
|
fairings: Fairings::new(),
|
2019-08-25 02:19:11 +00:00
|
|
|
shutdown_receiver: Some(shutdown_receiver),
|
2020-06-28 05:59:40 +00:00
|
|
|
}
|
2016-11-04 13:35:04 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Mounts all of the routes in the supplied vector at the given `base`
|
|
|
|
/// path. Mounting a route with path `path` at path `base` makes the route
|
|
|
|
/// available at `base/path`.
|
|
|
|
///
|
2017-05-19 10:29:08 +00:00
|
|
|
/// # Panics
|
|
|
|
///
|
Overhaul URI types.
This is fairly large commit with several entangled logical changes.
The primary change in this commit is to completely overhaul how URI
handling in Rocket works. Prior to this commit, the `Uri` type acted as
an origin API. Its parser was minimal and lenient, allowing URIs that
were invalid according to RFC 7230. By contrast, the new `Uri` type
brings with it a strict RFC 7230 compliant parser. The `Uri` type now
represents any kind of valid URI, not simply `Origin` types. Three new
URI types were introduced:
* `Origin` - represents valid origin URIs
* `Absolute` - represents valid absolute URIs
* `Authority` - represents valid authority URIs
The `Origin` type replaces `Uri` in many cases:
* As fields and method inputs of `Route`
* The `&Uri` request guard is now `&Origin`
* The `uri!` macro produces an `Origin` instead of a `Uri`
The strict nature of URI parsing cascaded into the following changes:
* Several `Route` methods now `panic!` on invalid URIs
* The `Rocket::mount()` method is (correctly) stricter with URIs
* The `Redirect` constructors take a `TryInto<Uri>` type
* Dispatching of a `LocalRequest` correctly validates URIs
Overall, URIs are now properly and uniformly handled throughout Rocket's
codebase, resulting in a more reliable and correct system.
In addition to these URI changes, the following changes are also part of
this commit:
* The `LocalRequest::cloned_dispatch()` method was removed in favor of
chaining `.clone().dispatch()`.
* The entire Rocket codebase uses `crate` instead of `pub(crate)` as a
visibility modifier.
* Rocket uses the `crate_visibility_modifier` and `try_from` features.
A note on unsafety: this commit introduces many uses of `unsafe` in the
URI parser. All of these uses are a result of unsafely transforming byte
slices (`&[u8]` or similar) into strings (`&str`). The parser ensures
that these casts are safe, but of course, we must label their use
`unsafe`. The parser was written to be as generic and efficient as
possible and thus can parse directly from byte sources. Rocket, however,
does not make use of this fact and so would be able to remove all uses
of `unsafe` by parsing from an existing `&str`. This should be
considered in the future.
Fixes #443.
Resolves #263.
2018-07-29 01:26:15 +00:00
|
|
|
/// Panics if the `base` mount point is not a valid static path: a valid
|
|
|
|
/// origin URI without dynamic parameters.
|
|
|
|
///
|
|
|
|
/// Panics if any route's URI is not a valid origin URI. This kind of panic
|
|
|
|
/// is guaranteed not to occur if the routes were generated using Rocket's
|
|
|
|
/// code generation.
|
2017-05-19 10:29:08 +00:00
|
|
|
///
|
2016-11-04 13:35:04 +00:00
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// Use the `routes!` macro to mount routes created using the code
|
|
|
|
/// generation facilities. Requests to the `/hello/world` URI will be
|
|
|
|
/// dispatched to the `hi` route.
|
|
|
|
///
|
2020-06-16 12:01:26 +00:00
|
|
|
/// ```rust,no_run
|
2018-06-28 15:55:15 +00:00
|
|
|
/// # #[macro_use] extern crate rocket;
|
2016-11-04 13:35:04 +00:00
|
|
|
/// #
|
|
|
|
/// #[get("/world")]
|
|
|
|
/// fn hi() -> &'static str {
|
|
|
|
/// "Hello!"
|
|
|
|
/// }
|
|
|
|
///
|
2020-07-22 23:10:02 +00:00
|
|
|
/// #[launch]
|
2020-06-16 12:01:26 +00:00
|
|
|
/// fn rocket() -> rocket::Rocket {
|
2016-11-04 13:35:04 +00:00
|
|
|
/// rocket::ignite().mount("/hello", routes![hi])
|
|
|
|
/// }
|
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// Manually create a route named `hi` at path `"/world"` mounted at base
|
|
|
|
/// `"/hello"`. Requests to the `/hello/world` URI will be dispatched to the
|
|
|
|
/// `hi` route.
|
|
|
|
///
|
|
|
|
/// ```rust
|
2016-12-15 08:47:31 +00:00
|
|
|
/// use rocket::{Request, Route, Data};
|
2019-08-07 00:08:00 +00:00
|
|
|
/// use rocket::handler::{HandlerFuture, Outcome};
|
2016-11-04 13:35:04 +00:00
|
|
|
/// use rocket::http::Method::*;
|
|
|
|
///
|
2019-08-07 00:08:00 +00:00
|
|
|
/// fn hi<'r>(req: &'r Request, _: Data) -> HandlerFuture<'r> {
|
2020-06-21 12:54:37 +00:00
|
|
|
/// Outcome::from(req, "Hello!").pin()
|
2016-11-04 13:35:04 +00:00
|
|
|
/// }
|
|
|
|
///
|
2020-06-14 15:57:55 +00:00
|
|
|
/// # let _ = async { // We don't actually want to launch the server in an example.
|
2016-11-04 13:35:04 +00:00
|
|
|
/// rocket::ignite().mount("/hello", vec![Route::new(Get, "/world", hi)])
|
2020-06-14 15:57:55 +00:00
|
|
|
/// # .launch().await;
|
|
|
|
/// # };
|
2016-11-04 13:35:04 +00:00
|
|
|
/// ```
|
2017-05-19 10:29:08 +00:00
|
|
|
#[inline]
|
2018-08-13 07:43:29 +00:00
|
|
|
pub fn mount<R: Into<Vec<Route>>>(mut self, base: &str, routes: R) -> Self {
|
2020-06-14 15:57:51 +00:00
|
|
|
let base_uri = Origin::parse_owned(base.to_string())
|
2018-07-30 01:24:25 +00:00
|
|
|
.unwrap_or_else(|e| {
|
2020-07-29 23:38:24 +00:00
|
|
|
error!("Invalid mount point URI: {}.", Paint::white(base));
|
2018-07-30 01:24:25 +00:00
|
|
|
panic!("Error: {}", e);
|
|
|
|
});
|
Overhaul URI types.
This is fairly large commit with several entangled logical changes.
The primary change in this commit is to completely overhaul how URI
handling in Rocket works. Prior to this commit, the `Uri` type acted as
an origin API. Its parser was minimal and lenient, allowing URIs that
were invalid according to RFC 7230. By contrast, the new `Uri` type
brings with it a strict RFC 7230 compliant parser. The `Uri` type now
represents any kind of valid URI, not simply `Origin` types. Three new
URI types were introduced:
* `Origin` - represents valid origin URIs
* `Absolute` - represents valid absolute URIs
* `Authority` - represents valid authority URIs
The `Origin` type replaces `Uri` in many cases:
* As fields and method inputs of `Route`
* The `&Uri` request guard is now `&Origin`
* The `uri!` macro produces an `Origin` instead of a `Uri`
The strict nature of URI parsing cascaded into the following changes:
* Several `Route` methods now `panic!` on invalid URIs
* The `Rocket::mount()` method is (correctly) stricter with URIs
* The `Redirect` constructors take a `TryInto<Uri>` type
* Dispatching of a `LocalRequest` correctly validates URIs
Overall, URIs are now properly and uniformly handled throughout Rocket's
codebase, resulting in a more reliable and correct system.
In addition to these URI changes, the following changes are also part of
this commit:
* The `LocalRequest::cloned_dispatch()` method was removed in favor of
chaining `.clone().dispatch()`.
* The entire Rocket codebase uses `crate` instead of `pub(crate)` as a
visibility modifier.
* Rocket uses the `crate_visibility_modifier` and `try_from` features.
A note on unsafety: this commit introduces many uses of `unsafe` in the
URI parser. All of these uses are a result of unsafely transforming byte
slices (`&[u8]` or similar) into strings (`&str`). The parser ensures
that these casts are safe, but of course, we must label their use
`unsafe`. The parser was written to be as generic and efficient as
possible and thus can parse directly from byte sources. Rocket, however,
does not make use of this fact and so would be able to remove all uses
of `unsafe` by parsing from an existing `&str`. This should be
considered in the future.
Fixes #443.
Resolves #263.
2018-07-29 01:26:15 +00:00
|
|
|
|
2018-07-30 01:24:25 +00:00
|
|
|
if base_uri.query().is_some() {
|
2020-07-29 23:38:24 +00:00
|
|
|
error!("Mount point '{}' contains query string.", base);
|
2018-07-30 01:24:25 +00:00
|
|
|
panic!("Invalid mount point.");
|
|
|
|
}
|
Overhaul URI types.
This is fairly large commit with several entangled logical changes.
The primary change in this commit is to completely overhaul how URI
handling in Rocket works. Prior to this commit, the `Uri` type acted as
an origin API. Its parser was minimal and lenient, allowing URIs that
were invalid according to RFC 7230. By contrast, the new `Uri` type
brings with it a strict RFC 7230 compliant parser. The `Uri` type now
represents any kind of valid URI, not simply `Origin` types. Three new
URI types were introduced:
* `Origin` - represents valid origin URIs
* `Absolute` - represents valid absolute URIs
* `Authority` - represents valid authority URIs
The `Origin` type replaces `Uri` in many cases:
* As fields and method inputs of `Route`
* The `&Uri` request guard is now `&Origin`
* The `uri!` macro produces an `Origin` instead of a `Uri`
The strict nature of URI parsing cascaded into the following changes:
* Several `Route` methods now `panic!` on invalid URIs
* The `Rocket::mount()` method is (correctly) stricter with URIs
* The `Redirect` constructors take a `TryInto<Uri>` type
* Dispatching of a `LocalRequest` correctly validates URIs
Overall, URIs are now properly and uniformly handled throughout Rocket's
codebase, resulting in a more reliable and correct system.
In addition to these URI changes, the following changes are also part of
this commit:
* The `LocalRequest::cloned_dispatch()` method was removed in favor of
chaining `.clone().dispatch()`.
* The entire Rocket codebase uses `crate` instead of `pub(crate)` as a
visibility modifier.
* Rocket uses the `crate_visibility_modifier` and `try_from` features.
A note on unsafety: this commit introduces many uses of `unsafe` in the
URI parser. All of these uses are a result of unsafely transforming byte
slices (`&[u8]` or similar) into strings (`&str`). The parser ensures
that these casts are safe, but of course, we must label their use
`unsafe`. The parser was written to be as generic and efficient as
possible and thus can parse directly from byte sources. Rocket, however,
does not make use of this fact and so would be able to remove all uses
of `unsafe` by parsing from an existing `&str`. This should be
considered in the future.
Fixes #443.
Resolves #263.
2018-07-29 01:26:15 +00:00
|
|
|
|
2020-06-28 05:59:40 +00:00
|
|
|
self.manifest.push(PreLaunchOp::Mount(base_uri, routes.into()));
|
2016-04-01 23:54:53 +00:00
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2016-11-04 13:35:04 +00:00
|
|
|
/// Registers all of the catchers in the supplied vector.
|
2016-11-05 18:35:21 +00:00
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
2020-06-16 12:01:26 +00:00
|
|
|
/// ```rust,no_run
|
2018-09-20 04:14:30 +00:00
|
|
|
/// # #[macro_use] extern crate rocket;
|
2018-09-17 03:52:07 +00:00
|
|
|
/// use rocket::Request;
|
2016-11-05 18:35:21 +00:00
|
|
|
///
|
2017-09-23 02:04:14 +00:00
|
|
|
/// #[catch(500)]
|
2016-11-05 18:35:21 +00:00
|
|
|
/// fn internal_error() -> &'static str {
|
|
|
|
/// "Whoops! Looks like we messed up."
|
|
|
|
/// }
|
|
|
|
///
|
2017-09-23 02:04:14 +00:00
|
|
|
/// #[catch(400)]
|
2016-11-05 18:35:21 +00:00
|
|
|
/// fn not_found(req: &Request) -> String {
|
|
|
|
/// format!("I couldn't find '{}'. Try something else?", req.uri())
|
|
|
|
/// }
|
|
|
|
///
|
2020-07-22 23:10:02 +00:00
|
|
|
/// #[launch]
|
2020-06-16 12:01:26 +00:00
|
|
|
/// fn rocket() -> rocket::Rocket {
|
|
|
|
/// rocket::ignite().register(catchers![internal_error, not_found])
|
2016-11-05 18:35:21 +00:00
|
|
|
/// }
|
|
|
|
/// ```
|
2017-05-19 10:29:08 +00:00
|
|
|
#[inline]
|
2018-09-16 08:47:51 +00:00
|
|
|
pub fn register(mut self, catchers: Vec<Catcher>) -> Self {
|
2020-06-28 05:59:40 +00:00
|
|
|
self.manifest.push(PreLaunchOp::Register(catchers));
|
2016-04-06 10:26:43 +00:00
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2017-01-21 03:31:46 +00:00
|
|
|
/// Add `state` to the state managed by this instance of Rocket.
|
|
|
|
///
|
2017-02-03 02:16:57 +00:00
|
|
|
/// This method can be called any number of times as long as each call
|
2017-02-06 18:40:43 +00:00
|
|
|
/// refers to a different `T`.
|
2017-02-03 02:16:57 +00:00
|
|
|
///
|
2017-01-21 03:31:46 +00:00
|
|
|
/// Managed state can be retrieved by any request handler via the
|
2019-06-13 01:48:02 +00:00
|
|
|
/// [`State`](crate::State) request guard. In particular, if a value of type `T`
|
2018-10-06 13:25:17 +00:00
|
|
|
/// is managed by Rocket, adding `State<T>` to the list of arguments in a
|
|
|
|
/// request handler instructs Rocket to retrieve the managed value.
|
2017-01-21 03:31:46 +00:00
|
|
|
///
|
|
|
|
/// # Panics
|
|
|
|
///
|
|
|
|
/// Panics if state of type `T` is already being managed.
|
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
2020-06-16 12:01:26 +00:00
|
|
|
/// ```rust,no_run
|
2018-06-28 15:55:15 +00:00
|
|
|
/// # #[macro_use] extern crate rocket;
|
2017-01-21 03:31:46 +00:00
|
|
|
/// use rocket::State;
|
|
|
|
///
|
|
|
|
/// struct MyValue(usize);
|
|
|
|
///
|
|
|
|
/// #[get("/")]
|
|
|
|
/// fn index(state: State<MyValue>) -> String {
|
|
|
|
/// format!("The stateful value is: {}", state.0)
|
|
|
|
/// }
|
|
|
|
///
|
2020-07-22 23:10:02 +00:00
|
|
|
/// #[launch]
|
2020-06-16 12:01:26 +00:00
|
|
|
/// fn rocket() -> rocket::Rocket {
|
2017-01-21 03:31:46 +00:00
|
|
|
/// rocket::ignite()
|
2017-02-02 10:16:21 +00:00
|
|
|
/// .mount("/", routes![index])
|
2017-01-21 03:31:46 +00:00
|
|
|
/// .manage(MyValue(10))
|
|
|
|
/// }
|
|
|
|
/// ```
|
2017-05-19 10:29:08 +00:00
|
|
|
#[inline]
|
2020-06-14 15:57:51 +00:00
|
|
|
pub fn manage<T: Send + Sync + 'static>(mut self, state: T) -> Self {
|
2020-06-28 05:59:40 +00:00
|
|
|
let type_name = std::any::type_name::<T>();
|
|
|
|
self.manifest.push(PreLaunchOp::Manage(type_name, Box::new(move |managed| {
|
|
|
|
if !managed.set::<T>(state) {
|
|
|
|
error!("State for type '{}' is already being managed!", type_name);
|
2020-06-14 15:57:51 +00:00
|
|
|
panic!("Aborting due to duplicately managed state.");
|
|
|
|
}
|
|
|
|
})));
|
2017-01-21 03:31:46 +00:00
|
|
|
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2018-07-03 01:18:41 +00:00
|
|
|
/// Attaches a fairing to this instance of Rocket. If the fairing is an
|
|
|
|
/// _attach_ fairing, it is run immediately. All other kinds of fairings
|
|
|
|
/// will be executed at their appropriate time.
|
2017-04-20 20:43:01 +00:00
|
|
|
///
|
2017-05-15 04:46:01 +00:00
|
|
|
/// # Example
|
2017-04-20 20:43:01 +00:00
|
|
|
///
|
2020-06-16 12:01:26 +00:00
|
|
|
/// ```rust,no_run
|
2018-09-20 04:14:30 +00:00
|
|
|
/// # #[macro_use] extern crate rocket;
|
2017-05-15 04:46:01 +00:00
|
|
|
/// use rocket::Rocket;
|
|
|
|
/// use rocket::fairing::AdHoc;
|
2017-04-20 20:43:01 +00:00
|
|
|
///
|
2020-07-22 23:10:02 +00:00
|
|
|
/// #[launch]
|
2020-06-16 12:01:26 +00:00
|
|
|
/// fn rocket() -> rocket::Rocket {
|
2017-04-20 20:43:01 +00:00
|
|
|
/// rocket::ignite()
|
2018-08-14 16:14:06 +00:00
|
|
|
/// .attach(AdHoc::on_launch("Launch Message", |_| {
|
|
|
|
/// println!("Rocket is launching!");
|
|
|
|
/// }))
|
2017-04-20 20:43:01 +00:00
|
|
|
/// }
|
|
|
|
/// ```
|
|
|
|
#[inline]
|
2017-05-15 04:46:01 +00:00
|
|
|
pub fn attach<F: Fairing>(mut self, fairing: F) -> Self {
|
2020-06-28 05:59:40 +00:00
|
|
|
self.manifest.push(PreLaunchOp::Attach(Box::new(fairing)));
|
2017-04-20 20:43:01 +00:00
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2020-06-28 05:59:40 +00:00
|
|
|
/// Access the current state of this `Rocket` instance.
|
|
|
|
///
|
|
|
|
/// The `Cargo` type provides methods such as [`Cargo::routes()`]
|
|
|
|
/// and [`Cargo::state()`]. This method is called to get a `Cargo`
|
|
|
|
/// instance.
|
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// # rocket::async_test(async {
|
|
|
|
/// let mut rocket = rocket::ignite();
|
|
|
|
/// let config = rocket.inspect().await.config();
|
|
|
|
/// # let _ = config;
|
|
|
|
/// # });
|
|
|
|
/// ```
|
|
|
|
pub async fn inspect(&mut self) -> &Cargo {
|
|
|
|
self.actualize_manifest().await;
|
|
|
|
self.cargo()
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns `Some` of the managed state value for the type `T` if it is
|
|
|
|
/// being managed by `self`. Otherwise, returns `None`.
|
|
|
|
///
|
|
|
|
/// This function is equivalent to `.inspect().await.state()` and is
|
|
|
|
/// provided as a convenience.
|
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// #[derive(PartialEq, Debug)]
|
|
|
|
/// struct MyState(&'static str);
|
|
|
|
///
|
|
|
|
/// # rocket::async_test(async {
|
|
|
|
/// let mut rocket = rocket::ignite().manage(MyState("hello!"));
|
|
|
|
/// assert_eq!(rocket.state::<MyState>().await, Some(&MyState("hello!")));
|
|
|
|
/// # });
|
|
|
|
/// ```
|
|
|
|
pub async fn state<T: Send + Sync + 'static>(&mut self) -> Option<&T> {
|
|
|
|
self.inspect().await.state()
|
2017-05-17 08:39:36 +00:00
|
|
|
}
|
|
|
|
|
2020-06-28 05:59:40 +00:00
|
|
|
/// Returns the active configuration.
|
|
|
|
///
|
|
|
|
/// This function is equivalent to `.inspect().await.config()` and is
|
|
|
|
/// provided as a convenience.
|
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// use rocket::Rocket;
|
|
|
|
/// use rocket::fairing::AdHoc;
|
|
|
|
///
|
|
|
|
/// # rocket::async_test(async {
|
|
|
|
/// let mut rocket = rocket::ignite();
|
|
|
|
/// println!("Rocket config: {:?}", rocket.config().await);
|
|
|
|
/// # });
|
|
|
|
/// ```
|
|
|
|
pub async fn config(&mut self) -> &Config {
|
|
|
|
self.inspect().await.config()
|
|
|
|
}
|
|
|
|
|
2020-07-22 23:10:02 +00:00
|
|
|
/// Returns a handle which can be used to gracefully terminate this instance
|
|
|
|
/// of Rocket. In routes, use the [`Shutdown`] request guard.
|
2020-06-28 05:59:40 +00:00
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// # use std::{thread, time::Duration};
|
|
|
|
/// #
|
|
|
|
/// # rocket::async_test(async {
|
|
|
|
/// let mut rocket = rocket::ignite();
|
2020-07-22 23:10:02 +00:00
|
|
|
/// let handle = rocket.inspect().await.shutdown();
|
2020-06-28 05:59:40 +00:00
|
|
|
///
|
|
|
|
/// # if false {
|
|
|
|
/// thread::spawn(move || {
|
|
|
|
/// thread::sleep(Duration::from_secs(10));
|
|
|
|
/// handle.shutdown();
|
|
|
|
/// });
|
|
|
|
///
|
|
|
|
/// // Shuts down after 10 seconds
|
|
|
|
/// let shutdown_result = rocket.launch().await;
|
|
|
|
/// assert!(shutdown_result.is_ok());
|
|
|
|
/// # }
|
|
|
|
/// # });
|
|
|
|
/// ```
|
|
|
|
#[inline(always)]
|
2020-07-22 23:10:02 +00:00
|
|
|
pub fn shutdown(&self) -> Shutdown {
|
2020-06-28 05:59:40 +00:00
|
|
|
self.shutdown_handle.clone()
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Perform "pre-launch" checks: verify that there are no routing colisions
|
|
|
|
/// and that there were no fairing failures.
|
|
|
|
pub(crate) async fn prelaunch_check(&mut self) -> Result<(), LaunchError> {
|
2020-06-14 15:57:53 +00:00
|
|
|
self.actualize_manifest().await;
|
2020-06-28 05:59:40 +00:00
|
|
|
if let Err(e) = self.router.collisions() {
|
|
|
|
return Err(LaunchError::new(LaunchErrorKind::Collision(e)));
|
|
|
|
}
|
|
|
|
|
|
|
|
if let Some(failures) = self.fairings.failures() {
|
|
|
|
return Err(LaunchError::new(LaunchErrorKind::FailedFairings(failures.to_vec())))
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(())
|
2019-09-14 15:10:00 +00:00
|
|
|
}
|
2019-05-19 17:58:19 +00:00
|
|
|
|
2020-06-14 15:57:53 +00:00
|
|
|
/// Returns a `Future` that drives the server, listening for and dispatching
|
2020-06-14 15:57:51 +00:00
|
|
|
/// requests to mounted routes and catchers. The `Future` completes when the
|
2020-07-22 23:10:02 +00:00
|
|
|
/// server is shut down via [`Shutdown`], encounters a fatal error, or if
|
|
|
|
/// the the `ctrlc` configuration option is set, when `Ctrl+C` is pressed.
|
2020-06-14 15:57:51 +00:00
|
|
|
///
|
|
|
|
/// # Error
|
2020-06-14 15:57:53 +00:00
|
|
|
///
|
2020-06-14 15:57:51 +00:00
|
|
|
/// If there is a problem starting the application, an [`Error`] is
|
2020-07-22 23:10:02 +00:00
|
|
|
/// returned. Note that a value of type `Error` panics if dropped without
|
|
|
|
/// first being inspected. See the [`Error`] documentation for more
|
|
|
|
/// information.
|
|
|
|
///
|
|
|
|
/// [`Error`]: crate::error::Error
|
2019-09-14 15:10:00 +00:00
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
|
|
|
/// ```rust
|
2020-06-14 15:57:55 +00:00
|
|
|
/// #[rocket::main]
|
2019-12-11 00:34:23 +00:00
|
|
|
/// async fn main() {
|
2019-09-14 15:10:00 +00:00
|
|
|
/// # if false {
|
2020-06-14 15:57:55 +00:00
|
|
|
/// let result = rocket::ignite().launch().await;
|
2019-09-14 15:10:00 +00:00
|
|
|
/// assert!(result.is_ok());
|
|
|
|
/// # }
|
2019-12-11 00:34:23 +00:00
|
|
|
/// }
|
2019-09-14 15:10:00 +00:00
|
|
|
/// ```
|
2020-06-28 05:59:40 +00:00
|
|
|
pub async fn launch(mut self) -> Result<(), crate::error::Error> {
|
2019-09-14 15:10:00 +00:00
|
|
|
use std::net::ToSocketAddrs;
|
2020-07-09 05:05:54 +00:00
|
|
|
use futures::future::Either;
|
2019-09-14 15:10:00 +00:00
|
|
|
use crate::error::Error::Launch;
|
|
|
|
|
2020-06-28 05:59:40 +00:00
|
|
|
self.prelaunch_check().await.map_err(crate::error::Error::Launch)?;
|
2020-06-14 15:57:51 +00:00
|
|
|
|
2020-06-28 05:59:40 +00:00
|
|
|
let full_addr = format!("{}:{}", self.config.address, self.config.port);
|
|
|
|
let addr = match full_addr.to_socket_addrs() {
|
|
|
|
Ok(mut addrs) => addrs.next().expect(">= 1 socket addr"),
|
|
|
|
Err(e) => return Err(Launch(e.into())),
|
2019-09-14 15:10:00 +00:00
|
|
|
};
|
|
|
|
|
2020-07-09 05:05:54 +00:00
|
|
|
// FIXME: Make `ctrlc` a known `Rocket` config option.
|
|
|
|
// If `ctrl-c` shutdown is enabled, we `select` on `the ctrl-c` signal
|
|
|
|
// and server. Otherwise, we only wait on the `server`, hence `pending`.
|
|
|
|
let shutdown_handle = self.shutdown_handle.clone();
|
|
|
|
let shutdown_signal = match self.config.get_bool("ctrlc") {
|
|
|
|
Ok(false) => futures::future::pending().boxed(),
|
|
|
|
_ => tokio::signal::ctrl_c().boxed(),
|
|
|
|
};
|
2019-09-14 15:10:00 +00:00
|
|
|
|
2019-12-11 00:34:23 +00:00
|
|
|
let server = {
|
2019-09-14 15:10:00 +00:00
|
|
|
macro_rules! listen_on {
|
2019-09-22 22:48:08 +00:00
|
|
|
($expr:expr) => {{
|
2019-09-14 15:10:00 +00:00
|
|
|
let listener = match $expr {
|
|
|
|
Ok(ok) => ok,
|
2020-07-09 05:05:54 +00:00
|
|
|
Err(err) => return Err(Launch(LaunchError::new(LaunchErrorKind::Bind(err))))
|
2019-09-14 15:10:00 +00:00
|
|
|
};
|
2020-06-28 05:59:40 +00:00
|
|
|
self.listen_on(listener)
|
2019-09-14 15:10:00 +00:00
|
|
|
}};
|
|
|
|
}
|
|
|
|
|
2020-07-09 05:05:54 +00:00
|
|
|
#[cfg(feature = "tls")] {
|
2020-06-28 05:59:40 +00:00
|
|
|
if let Some(tls) = self.config.tls.clone() {
|
2019-12-11 00:34:23 +00:00
|
|
|
listen_on!(crate::http::tls::bind_tls(addr, tls.certs, tls.key).await).boxed()
|
2019-09-14 15:10:00 +00:00
|
|
|
} else {
|
2019-12-11 00:34:23 +00:00
|
|
|
listen_on!(crate::http::private::bind_tcp(addr).await).boxed()
|
2019-09-14 15:10:00 +00:00
|
|
|
}
|
|
|
|
}
|
2020-07-09 05:05:54 +00:00
|
|
|
#[cfg(not(feature = "tls"))] {
|
|
|
|
listen_on!(crate::http::private::bind_tcp(addr).await).boxed()
|
2019-09-14 15:10:00 +00:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2020-07-09 05:05:54 +00:00
|
|
|
match futures::future::select(shutdown_signal, server).await {
|
|
|
|
Either::Left((Ok(()), server)) => {
|
|
|
|
// Ctrl-was pressed. Signal shutdown, wait for the server.
|
|
|
|
shutdown_handle.shutdown();
|
|
|
|
server.await
|
|
|
|
}
|
|
|
|
Either::Left((Err(err), server)) => {
|
|
|
|
// Error setting up ctrl-c signal. Let the user know.
|
|
|
|
warn!("Failed to enable `ctrl+c` graceful signal shutdown.");
|
|
|
|
info_!("Error: {}", err);
|
|
|
|
server.await
|
|
|
|
}
|
|
|
|
// Server shut down before Ctrl-C; return the result.
|
|
|
|
Either::Right((result, _)) => result,
|
2019-08-25 02:19:11 +00:00
|
|
|
}
|
2019-08-18 02:00:32 +00:00
|
|
|
}
|
2020-06-28 05:59:40 +00:00
|
|
|
}
|
2019-05-19 17:58:19 +00:00
|
|
|
|
2020-06-28 05:59:40 +00:00
|
|
|
impl std::fmt::Debug for PreLaunchOp {
|
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
|
|
use PreLaunchOp::*;
|
|
|
|
match self {
|
|
|
|
Mount(origin, routes) => f.debug_tuple("PreLaunchOp::Mount")
|
|
|
|
.field(&origin)
|
|
|
|
.field(&routes)
|
|
|
|
.finish(),
|
|
|
|
Register(catchers) => f.debug_tuple("PreLaunchOp::Register")
|
|
|
|
.field(&catchers)
|
|
|
|
.finish(),
|
|
|
|
Manage(name, _) => f.debug_tuple("PreLaunchOp::Manage")
|
|
|
|
.field(&name)
|
|
|
|
.finish(),
|
|
|
|
Attach(fairing) => f.debug_tuple("PreLaunchOp::Attach")
|
|
|
|
.field(&fairing.info())
|
|
|
|
.finish()
|
|
|
|
}
|
2020-06-14 15:57:51 +00:00
|
|
|
}
|
2020-06-28 05:59:40 +00:00
|
|
|
}
|
2020-06-14 15:57:51 +00:00
|
|
|
|
2020-06-28 05:59:40 +00:00
|
|
|
impl std::ops::Deref for Cargo {
|
|
|
|
type Target = Rocket;
|
2020-06-14 15:57:54 +00:00
|
|
|
|
2020-06-28 05:59:40 +00:00
|
|
|
fn deref(&self) -> &Self::Target {
|
|
|
|
&self.0
|
2020-06-14 15:57:54 +00:00
|
|
|
}
|
2020-06-14 15:57:51 +00:00
|
|
|
}
|
|
|
|
|
2020-06-28 05:59:40 +00:00
|
|
|
impl Cargo {
|
2017-06-12 22:08:34 +00:00
|
|
|
/// Returns an iterator over all of the routes mounted on this instance of
|
|
|
|
/// Rocket.
|
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
|
|
|
/// ```rust
|
2018-06-28 15:55:15 +00:00
|
|
|
/// # #[macro_use] extern crate rocket;
|
2017-06-12 22:08:34 +00:00
|
|
|
/// use rocket::Rocket;
|
|
|
|
/// use rocket::fairing::AdHoc;
|
|
|
|
///
|
|
|
|
/// #[get("/hello")]
|
|
|
|
/// fn hello() -> &'static str {
|
|
|
|
/// "Hello, world!"
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// fn main() {
|
2020-06-14 15:57:53 +00:00
|
|
|
/// # rocket::async_test(async {
|
2020-06-14 15:57:51 +00:00
|
|
|
/// let mut rocket = rocket::ignite()
|
2017-06-12 22:08:34 +00:00
|
|
|
/// .mount("/", routes![hello])
|
|
|
|
/// .mount("/hi", routes![hello]);
|
|
|
|
///
|
2020-06-14 15:57:53 +00:00
|
|
|
/// for route in rocket.inspect().await.routes() {
|
2017-06-12 22:08:34 +00:00
|
|
|
/// match route.base() {
|
|
|
|
/// "/" => assert_eq!(route.uri.path(), "/hello"),
|
|
|
|
/// "/hi" => assert_eq!(route.uri.path(), "/hi/hello"),
|
|
|
|
/// _ => unreachable!("only /hello, /hi/hello are expected")
|
|
|
|
/// }
|
|
|
|
/// }
|
|
|
|
///
|
2020-06-14 15:57:53 +00:00
|
|
|
/// assert_eq!(rocket.inspect().await.routes().count(), 2);
|
|
|
|
/// # });
|
2017-06-12 22:08:34 +00:00
|
|
|
/// }
|
|
|
|
/// ```
|
2017-04-05 08:19:33 +00:00
|
|
|
#[inline(always)]
|
2020-06-14 15:57:51 +00:00
|
|
|
pub fn routes(&self) -> impl Iterator<Item = &Route> + '_ {
|
2020-06-28 05:59:40 +00:00
|
|
|
self.0.router.routes()
|
2017-04-05 08:19:33 +00:00
|
|
|
}
|
2017-04-20 20:43:01 +00:00
|
|
|
|
2018-01-13 04:15:55 +00:00
|
|
|
/// Returns `Some` of the managed state value for the type `T` if it is
|
|
|
|
/// being managed by `self`. Otherwise, returns `None`.
|
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// #[derive(PartialEq, Debug)]
|
|
|
|
/// struct MyState(&'static str);
|
|
|
|
///
|
2020-06-14 15:57:53 +00:00
|
|
|
/// # rocket::async_test(async {
|
2020-06-14 15:57:51 +00:00
|
|
|
/// let mut rocket = rocket::ignite().manage(MyState("hello!"));
|
2020-06-22 11:54:34 +00:00
|
|
|
///
|
2020-06-28 05:59:40 +00:00
|
|
|
/// let cargo = rocket.inspect().await;
|
|
|
|
/// assert_eq!(cargo.state::<MyState>(), Some(&MyState("hello!")));
|
2020-06-14 15:57:53 +00:00
|
|
|
/// # });
|
2018-01-13 04:15:55 +00:00
|
|
|
/// ```
|
|
|
|
#[inline(always)]
|
|
|
|
pub fn state<T: Send + Sync + 'static>(&self) -> Option<&T> {
|
2020-06-28 05:59:40 +00:00
|
|
|
self.0.managed_state.try_get()
|
2018-01-13 04:15:55 +00:00
|
|
|
}
|
|
|
|
|
2017-06-12 22:08:34 +00:00
|
|
|
/// Returns the active configuration.
|
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
2020-06-16 12:01:26 +00:00
|
|
|
/// ```rust,no_run
|
2018-09-20 04:14:30 +00:00
|
|
|
/// # #[macro_use] extern crate rocket;
|
2017-06-12 22:08:34 +00:00
|
|
|
/// use rocket::Rocket;
|
|
|
|
/// use rocket::fairing::AdHoc;
|
|
|
|
///
|
2020-07-22 23:10:02 +00:00
|
|
|
/// #[launch]
|
2020-06-16 12:01:26 +00:00
|
|
|
/// fn rocket() -> rocket::Rocket {
|
2017-06-12 22:08:34 +00:00
|
|
|
/// rocket::ignite()
|
2020-06-28 05:59:40 +00:00
|
|
|
/// .attach(AdHoc::on_launch("Config Printer", |cargo| {
|
|
|
|
/// println!("Rocket launch config: {:?}", cargo.config());
|
2017-06-12 22:08:34 +00:00
|
|
|
/// }))
|
|
|
|
/// }
|
|
|
|
/// ```
|
2017-04-20 20:43:01 +00:00
|
|
|
#[inline(always)]
|
|
|
|
pub fn config(&self) -> &Config {
|
2020-06-28 05:59:40 +00:00
|
|
|
&self.0.config
|
2017-04-20 20:43:01 +00:00
|
|
|
}
|
2016-04-01 23:54:53 +00:00
|
|
|
}
|