1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
use self::future::ResponseFuture;
use crate::{
body::UnsyncBoxBody,
content_encoding::{encodings, SupportedEncodings},
set_status::SetStatus,
};
use bytes::Bytes;
use futures_util::FutureExt;
use http::{header, HeaderValue, Method, Request, Response, StatusCode};
use http_body_util::{BodyExt, Empty};
use percent_encoding::percent_decode;
use std::{
convert::Infallible,
io,
path::{Component, Path, PathBuf},
task::{Context, Poll},
};
use tower_service::Service;
pub(crate) mod future;
mod headers;
mod open_file;
#[cfg(test)]
mod tests;
// default capacity 64KiB
const DEFAULT_CAPACITY: usize = 65536;
/// Service that serves files from a given directory and all its sub directories.
///
/// The `Content-Type` will be guessed from the file extension.
///
/// An empty response with status `404 Not Found` will be returned if:
///
/// - The file doesn't exist
/// - Any segment of the path contains `..`
/// - Any segment of the path contains a backslash
/// - On unix, any segment of the path referenced as directory is actually an
/// existing file (`/file.html/something`)
/// - We don't have necessary permissions to read the file
///
/// # Example
///
/// ```
/// use tower_http::services::ServeDir;
///
/// // This will serve files in the "assets" directory and
/// // its subdirectories
/// let service = ServeDir::new("assets");
/// ```
#[derive(Clone, Debug)]
pub struct ServeDir<F = DefaultServeDirFallback> {
base: PathBuf,
buf_chunk_size: usize,
precompressed_variants: Option<PrecompressedVariants>,
// This is used to specialise implementation for
// single files
variant: ServeVariant,
fallback: Option<F>,
call_fallback_on_method_not_allowed: bool,
}
impl ServeDir<DefaultServeDirFallback> {
/// Create a new [`ServeDir`].
pub fn new<P>(path: P) -> Self
where
P: AsRef<Path>,
{
let mut base = PathBuf::from(".");
base.push(path.as_ref());
Self {
base,
buf_chunk_size: DEFAULT_CAPACITY,
precompressed_variants: None,
variant: ServeVariant::Directory {
append_index_html_on_directories: true,
},
fallback: None,
call_fallback_on_method_not_allowed: false,
}
}
pub(crate) fn new_single_file<P>(path: P, mime: HeaderValue) -> Self
where
P: AsRef<Path>,
{
Self {
base: path.as_ref().to_owned(),
buf_chunk_size: DEFAULT_CAPACITY,
precompressed_variants: None,
variant: ServeVariant::SingleFile { mime },
fallback: None,
call_fallback_on_method_not_allowed: false,
}
}
}
impl<F> ServeDir<F> {
/// If the requested path is a directory append `index.html`.
///
/// This is useful for static sites.
///
/// Defaults to `true`.
pub fn append_index_html_on_directories(mut self, append: bool) -> Self {
match &mut self.variant {
ServeVariant::Directory {
append_index_html_on_directories,
} => {
*append_index_html_on_directories = append;
self
}
ServeVariant::SingleFile { mime: _ } => self,
}
}
/// Set a specific read buffer chunk size.
///
/// The default capacity is 64kb.
pub fn with_buf_chunk_size(mut self, chunk_size: usize) -> Self {
self.buf_chunk_size = chunk_size;
self
}
/// Informs the service that it should also look for a precompressed gzip
/// version of _any_ file in the directory.
///
/// Assuming the `dir` directory is being served and `dir/foo.txt` is requested,
/// a client with an `Accept-Encoding` header that allows the gzip encoding
/// will receive the file `dir/foo.txt.gz` instead of `dir/foo.txt`.
/// If the precompressed file is not available, or the client doesn't support it,
/// the uncompressed version will be served instead.
/// Both the precompressed version and the uncompressed version are expected
/// to be present in the directory. Different precompressed variants can be combined.
pub fn precompressed_gzip(mut self) -> Self {
self.precompressed_variants
.get_or_insert(Default::default())
.gzip = true;
self
}
/// Informs the service that it should also look for a precompressed brotli
/// version of _any_ file in the directory.
///
/// Assuming the `dir` directory is being served and `dir/foo.txt` is requested,
/// a client with an `Accept-Encoding` header that allows the brotli encoding
/// will receive the file `dir/foo.txt.br` instead of `dir/foo.txt`.
/// If the precompressed file is not available, or the client doesn't support it,
/// the uncompressed version will be served instead.
/// Both the precompressed version and the uncompressed version are expected
/// to be present in the directory. Different precompressed variants can be combined.
pub fn precompressed_br(mut self) -> Self {
self.precompressed_variants
.get_or_insert(Default::default())
.br = true;
self
}
/// Informs the service that it should also look for a precompressed deflate
/// version of _any_ file in the directory.
///
/// Assuming the `dir` directory is being served and `dir/foo.txt` is requested,
/// a client with an `Accept-Encoding` header that allows the deflate encoding
/// will receive the file `dir/foo.txt.zz` instead of `dir/foo.txt`.
/// If the precompressed file is not available, or the client doesn't support it,
/// the uncompressed version will be served instead.
/// Both the precompressed version and the uncompressed version are expected
/// to be present in the directory. Different precompressed variants can be combined.
pub fn precompressed_deflate(mut self) -> Self {
self.precompressed_variants
.get_or_insert(Default::default())
.deflate = true;
self
}
/// Informs the service that it should also look for a precompressed zstd
/// version of _any_ file in the directory.
///
/// Assuming the `dir` directory is being served and `dir/foo.txt` is requested,
/// a client with an `Accept-Encoding` header that allows the zstd encoding
/// will receive the file `dir/foo.txt.zst` instead of `dir/foo.txt`.
/// If the precompressed file is not available, or the client doesn't support it,
/// the uncompressed version will be served instead.
/// Both the precompressed version and the uncompressed version are expected
/// to be present in the directory. Different precompressed variants can be combined.
pub fn precompressed_zstd(mut self) -> Self {
self.precompressed_variants
.get_or_insert(Default::default())
.zstd = true;
self
}
/// Set the fallback service.
///
/// This service will be called if there is no file at the path of the request.
///
/// The status code returned by the fallback will not be altered. Use
/// [`ServeDir::not_found_service`] to set a fallback and always respond with `404 Not Found`.
///
/// # Example
///
/// This can be used to respond with a different file:
///
/// ```rust
/// use tower_http::services::{ServeDir, ServeFile};
///
/// let service = ServeDir::new("assets")
/// // respond with `not_found.html` for missing files
/// .fallback(ServeFile::new("assets/not_found.html"));
/// ```
pub fn fallback<F2>(self, new_fallback: F2) -> ServeDir<F2> {
ServeDir {
base: self.base,
buf_chunk_size: self.buf_chunk_size,
precompressed_variants: self.precompressed_variants,
variant: self.variant,
fallback: Some(new_fallback),
call_fallback_on_method_not_allowed: self.call_fallback_on_method_not_allowed,
}
}
/// Set the fallback service and override the fallback's status code to `404 Not Found`.
///
/// This service will be called if there is no file at the path of the request.
///
/// # Example
///
/// This can be used to respond with a different file:
///
/// ```rust
/// use tower_http::services::{ServeDir, ServeFile};
///
/// let service = ServeDir::new("assets")
/// // respond with `404 Not Found` and the contents of `not_found.html` for missing files
/// .not_found_service(ServeFile::new("assets/not_found.html"));
/// ```
///
/// Setups like this are often found in single page applications.
pub fn not_found_service<F2>(self, new_fallback: F2) -> ServeDir<SetStatus<F2>> {
self.fallback(SetStatus::new(new_fallback, StatusCode::NOT_FOUND))
}
/// Customize whether or not to call the fallback for requests that aren't `GET` or `HEAD`.
///
/// Defaults to not calling the fallback and instead returning `405 Method Not Allowed`.
pub fn call_fallback_on_method_not_allowed(mut self, call_fallback: bool) -> Self {
self.call_fallback_on_method_not_allowed = call_fallback;
self
}
/// Call the service and get a future that contains any `std::io::Error` that might have
/// happened.
///
/// By default `<ServeDir as Service<_>>::call` will handle IO errors and convert them into
/// responses. It does that by converting [`std::io::ErrorKind::NotFound`] and
/// [`std::io::ErrorKind::PermissionDenied`] to `404 Not Found` and any other error to `500
/// Internal Server Error`. The error will also be logged with `tracing`.
///
/// If you want to manually control how the error response is generated you can make a new
/// service that wraps a `ServeDir` and calls `try_call` instead of `call`.
///
/// # Example
///
/// ```
/// use tower_http::services::ServeDir;
/// use std::{io, convert::Infallible};
/// use http::{Request, Response, StatusCode};
/// use http_body::Body as _;
/// use http_body_util::{Full, BodyExt, combinators::UnsyncBoxBody};
/// use bytes::Bytes;
/// use tower::{service_fn, ServiceExt, BoxError};
///
/// async fn serve_dir(
/// request: Request<Full<Bytes>>
/// ) -> Result<Response<UnsyncBoxBody<Bytes, BoxError>>, Infallible> {
/// let mut service = ServeDir::new("assets");
///
/// // You only need to worry about backpressure, and thus call `ServiceExt::ready`, if
/// // your adding a fallback to `ServeDir` that cares about backpressure.
/// //
/// // Its shown here for demonstration but you can do `service.try_call(request)`
/// // otherwise
/// let ready_service = match ServiceExt::<Request<Full<Bytes>>>::ready(&mut service).await {
/// Ok(ready_service) => ready_service,
/// Err(infallible) => match infallible {},
/// };
///
/// match ready_service.try_call(request).await {
/// Ok(response) => {
/// Ok(response.map(|body| body.map_err(Into::into).boxed_unsync()))
/// }
/// Err(err) => {
/// let body = Full::from("Something went wrong...")
/// .map_err(Into::into)
/// .boxed_unsync();
/// let response = Response::builder()
/// .status(StatusCode::INTERNAL_SERVER_ERROR)
/// .body(body)
/// .unwrap();
/// Ok(response)
/// }
/// }
/// }
/// ```
pub fn try_call<ReqBody, FResBody>(
&mut self,
req: Request<ReqBody>,
) -> ResponseFuture<ReqBody, F>
where
F: Service<Request<ReqBody>, Response = Response<FResBody>, Error = Infallible> + Clone,
F::Future: Send + 'static,
FResBody: http_body::Body<Data = Bytes> + Send + 'static,
FResBody::Error: Into<Box<dyn std::error::Error + Send + Sync>>,
{
if req.method() != Method::GET && req.method() != Method::HEAD {
if self.call_fallback_on_method_not_allowed {
if let Some(fallback) = &mut self.fallback {
return ResponseFuture {
inner: future::call_fallback(fallback, req),
};
}
} else {
return ResponseFuture::method_not_allowed();
}
}
// `ServeDir` doesn't care about the request body but the fallback might. So move out the
// body and pass it to the fallback, leaving an empty body in its place
//
// this is necessary because we cannot clone bodies
let (mut parts, body) = req.into_parts();
// same goes for extensions
let extensions = std::mem::take(&mut parts.extensions);
let req = Request::from_parts(parts, Empty::<Bytes>::new());
let fallback_and_request = self.fallback.as_mut().map(|fallback| {
let mut fallback_req = Request::new(body);
*fallback_req.method_mut() = req.method().clone();
*fallback_req.uri_mut() = req.uri().clone();
*fallback_req.headers_mut() = req.headers().clone();
*fallback_req.extensions_mut() = extensions;
// get the ready fallback and leave a non-ready clone in its place
let clone = fallback.clone();
let fallback = std::mem::replace(fallback, clone);
(fallback, fallback_req)
});
let path_to_file = match self
.variant
.build_and_validate_path(&self.base, req.uri().path())
{
Some(path_to_file) => path_to_file,
None => {
return ResponseFuture::invalid_path(fallback_and_request);
}
};
let buf_chunk_size = self.buf_chunk_size;
let range_header = req
.headers()
.get(header::RANGE)
.and_then(|value| value.to_str().ok())
.map(|s| s.to_owned());
let negotiated_encodings: Vec<_> = encodings(
req.headers(),
self.precompressed_variants.unwrap_or_default(),
)
.collect();
let variant = self.variant.clone();
let open_file_future = Box::pin(open_file::open_file(
variant,
path_to_file,
req,
negotiated_encodings,
range_header,
buf_chunk_size,
));
ResponseFuture::open_file_future(open_file_future, fallback_and_request)
}
}
impl<ReqBody, F, FResBody> Service<Request<ReqBody>> for ServeDir<F>
where
F: Service<Request<ReqBody>, Response = Response<FResBody>, Error = Infallible> + Clone,
F::Future: Send + 'static,
FResBody: http_body::Body<Data = Bytes> + Send + 'static,
FResBody::Error: Into<Box<dyn std::error::Error + Send + Sync>>,
{
type Response = Response<ResponseBody>;
type Error = Infallible;
type Future = InfallibleResponseFuture<ReqBody, F>;
#[inline]
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
if let Some(fallback) = &mut self.fallback {
fallback.poll_ready(cx)
} else {
Poll::Ready(Ok(()))
}
}
fn call(&mut self, req: Request<ReqBody>) -> Self::Future {
let future = self
.try_call(req)
.map(|result: Result<_, _>| -> Result<_, Infallible> {
let response = result.unwrap_or_else(|err| {
tracing::error!(error = %err, "Failed to read file");
let body = ResponseBody::new(UnsyncBoxBody::new(
Empty::new().map_err(|err| match err {}).boxed_unsync(),
));
Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.body(body)
.unwrap()
});
Ok(response)
} as _);
InfallibleResponseFuture::new(future)
}
}
opaque_future! {
/// Response future of [`ServeDir`].
pub type InfallibleResponseFuture<ReqBody, F> =
futures_util::future::Map<
ResponseFuture<ReqBody, F>,
fn(Result<Response<ResponseBody>, io::Error>) -> Result<Response<ResponseBody>, Infallible>,
>;
}
// Allow the ServeDir service to be used in the ServeFile service
// with almost no overhead
#[derive(Clone, Debug)]
enum ServeVariant {
Directory {
append_index_html_on_directories: bool,
},
SingleFile {
mime: HeaderValue,
},
}
impl ServeVariant {
fn build_and_validate_path(&self, base_path: &Path, requested_path: &str) -> Option<PathBuf> {
match self {
ServeVariant::Directory {
append_index_html_on_directories: _,
} => {
let path = requested_path.trim_start_matches('/');
let path_decoded = percent_decode(path.as_ref()).decode_utf8().ok()?;
let path_decoded = Path::new(&*path_decoded);
let mut path_to_file = base_path.to_path_buf();
for component in path_decoded.components() {
match component {
Component::Normal(comp) => {
// protect against paths like `/foo/c:/bar/baz` (#204)
if Path::new(&comp)
.components()
.all(|c| matches!(c, Component::Normal(_)))
{
path_to_file.push(comp)
} else {
return None;
}
}
Component::CurDir => {}
Component::Prefix(_) | Component::RootDir | Component::ParentDir => {
return None;
}
}
}
Some(path_to_file)
}
ServeVariant::SingleFile { mime: _ } => Some(base_path.to_path_buf()),
}
}
}
opaque_body! {
/// Response body for [`ServeDir`] and [`ServeFile`][super::ServeFile].
#[derive(Default)]
pub type ResponseBody = UnsyncBoxBody<Bytes, io::Error>;
}
/// The default fallback service used with [`ServeDir`].
#[derive(Debug, Clone, Copy)]
pub struct DefaultServeDirFallback(Infallible);
impl<ReqBody> Service<Request<ReqBody>> for DefaultServeDirFallback
where
ReqBody: Send + 'static,
{
type Response = Response<ResponseBody>;
type Error = Infallible;
type Future = InfallibleResponseFuture<ReqBody, Self>;
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
match self.0 {}
}
fn call(&mut self, _req: Request<ReqBody>) -> Self::Future {
match self.0 {}
}
}
#[derive(Clone, Copy, Debug, Default)]
struct PrecompressedVariants {
gzip: bool,
deflate: bool,
br: bool,
zstd: bool,
}
impl SupportedEncodings for PrecompressedVariants {
fn gzip(&self) -> bool {
self.gzip
}
fn deflate(&self) -> bool {
self.deflate
}
fn br(&self) -> bool {
self.br
}
fn zstd(&self) -> bool {
self.zstd
}
}