Vendor asic-rs 0.8.1 (280 crates, offline builds) + wxWidgets 3.3.3 (pristine + patch queue); UI spec + ADR-0003; M1 on asic-rs
This commit is contained in:
+79
@@ -0,0 +1,79 @@
|
||||
//! File system related services.
|
||||
|
||||
use bytes::Bytes;
|
||||
use futures_core::Stream;
|
||||
use http_body::{Body, Frame};
|
||||
use pin_project_lite::pin_project;
|
||||
use std::{
|
||||
io,
|
||||
pin::Pin,
|
||||
task::{Context, Poll},
|
||||
};
|
||||
use tokio::io::{AsyncRead, AsyncReadExt, Take};
|
||||
use tokio_util::io::ReaderStream;
|
||||
|
||||
mod serve_dir;
|
||||
mod serve_file;
|
||||
|
||||
pub use self::{
|
||||
serve_dir::{
|
||||
future::ResponseFuture as ServeFileSystemResponseFuture,
|
||||
DefaultServeDirFallback,
|
||||
// The response body and future are used for both ServeDir and ServeFile
|
||||
ResponseBody as ServeFileSystemResponseBody,
|
||||
ServeDir,
|
||||
},
|
||||
serve_file::ServeFile,
|
||||
};
|
||||
|
||||
pin_project! {
|
||||
// NOTE: This could potentially be upstreamed to `http-body`.
|
||||
/// Adapter that turns an [`impl AsyncRead`][tokio::io::AsyncRead] to an [`impl Body`][http_body::Body].
|
||||
#[derive(Debug)]
|
||||
pub struct AsyncReadBody<T> {
|
||||
#[pin]
|
||||
reader: ReaderStream<T>,
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> AsyncReadBody<T>
|
||||
where
|
||||
T: AsyncRead,
|
||||
{
|
||||
/// Create a new [`AsyncReadBody`] wrapping the given reader,
|
||||
/// with a specific read buffer capacity
|
||||
pub fn with_capacity(read: T, capacity: usize) -> Self {
|
||||
Self {
|
||||
reader: ReaderStream::with_capacity(read, capacity),
|
||||
}
|
||||
}
|
||||
|
||||
fn with_capacity_limited(
|
||||
read: T,
|
||||
capacity: usize,
|
||||
max_read_bytes: u64,
|
||||
) -> AsyncReadBody<Take<T>> {
|
||||
AsyncReadBody {
|
||||
reader: ReaderStream::with_capacity(read.take(max_read_bytes), capacity),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Body for AsyncReadBody<T>
|
||||
where
|
||||
T: AsyncRead,
|
||||
{
|
||||
type Data = Bytes;
|
||||
type Error = io::Error;
|
||||
|
||||
fn poll_frame(
|
||||
self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
|
||||
match std::task::ready!(self.project().reader.poll_next(cx)) {
|
||||
Some(Ok(chunk)) => Poll::Ready(Some(Ok(Frame::data(chunk)))),
|
||||
Some(Err(err)) => Poll::Ready(Some(Err(err))),
|
||||
None => Poll::Ready(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
use super::{
|
||||
open_file::{FileOpened, FileRequestExtent, OpenFileOutput},
|
||||
DefaultServeDirFallback, ResponseBody,
|
||||
};
|
||||
use crate::{
|
||||
body::UnsyncBoxBody, content_encoding::Encoding, services::fs::AsyncReadBody, BoxError,
|
||||
};
|
||||
use bytes::Bytes;
|
||||
use futures_core::future::BoxFuture;
|
||||
use futures_util::future::{FutureExt, TryFutureExt};
|
||||
use http::{
|
||||
header::{self, ALLOW},
|
||||
HeaderValue, Request, Response, StatusCode,
|
||||
};
|
||||
use http_body_util::{BodyExt, Empty, Full};
|
||||
use pin_project_lite::pin_project;
|
||||
use std::{
|
||||
convert::Infallible,
|
||||
future::Future,
|
||||
io,
|
||||
pin::Pin,
|
||||
task::{ready, Context, Poll},
|
||||
};
|
||||
use tower_service::Service;
|
||||
|
||||
pin_project! {
|
||||
/// Response future of [`ServeDir::try_call()`][`super::ServeDir::try_call()`].
|
||||
pub struct ResponseFuture<ReqBody, F = DefaultServeDirFallback> {
|
||||
#[pin]
|
||||
pub(super) inner: ResponseFutureInner<ReqBody, F>,
|
||||
}
|
||||
}
|
||||
|
||||
impl<ReqBody, F> ResponseFuture<ReqBody, F> {
|
||||
pub(super) fn open_file_future(
|
||||
future: BoxFuture<'static, io::Result<OpenFileOutput>>,
|
||||
fallback_and_request: Option<(F, Request<ReqBody>)>,
|
||||
) -> Self {
|
||||
Self {
|
||||
inner: ResponseFutureInner::OpenFileFuture {
|
||||
future,
|
||||
fallback_and_request,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn invalid_path(fallback_and_request: Option<(F, Request<ReqBody>)>) -> Self {
|
||||
Self {
|
||||
inner: ResponseFutureInner::InvalidPath {
|
||||
fallback_and_request,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn method_not_allowed() -> Self {
|
||||
Self {
|
||||
inner: ResponseFutureInner::MethodNotAllowed,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pin_project! {
|
||||
#[project = ResponseFutureInnerProj]
|
||||
pub(super) enum ResponseFutureInner<ReqBody, F> {
|
||||
OpenFileFuture {
|
||||
#[pin]
|
||||
future: BoxFuture<'static, io::Result<OpenFileOutput>>,
|
||||
fallback_and_request: Option<(F, Request<ReqBody>)>,
|
||||
},
|
||||
FallbackFuture {
|
||||
future: BoxFuture<'static, Result<Response<ResponseBody>, Infallible>>,
|
||||
},
|
||||
InvalidPath {
|
||||
fallback_and_request: Option<(F, Request<ReqBody>)>,
|
||||
},
|
||||
MethodNotAllowed,
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, ReqBody, ResBody> Future for ResponseFuture<ReqBody, F>
|
||||
where
|
||||
F: Service<Request<ReqBody>, Response = Response<ResBody>, Error = Infallible> + Clone,
|
||||
F::Future: Send + 'static,
|
||||
ResBody: http_body::Body<Data = Bytes> + Send + 'static,
|
||||
ResBody::Error: Into<Box<dyn std::error::Error + Send + Sync>>,
|
||||
{
|
||||
type Output = io::Result<Response<ResponseBody>>;
|
||||
|
||||
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||
loop {
|
||||
let mut this = self.as_mut().project();
|
||||
|
||||
let new_state = match this.inner.as_mut().project() {
|
||||
ResponseFutureInnerProj::OpenFileFuture {
|
||||
future: open_file_future,
|
||||
fallback_and_request,
|
||||
} => match ready!(open_file_future.poll(cx)) {
|
||||
Ok(OpenFileOutput::FileOpened(file_output)) => {
|
||||
break Poll::Ready(Ok(build_response(*file_output)));
|
||||
}
|
||||
|
||||
Ok(OpenFileOutput::Redirect { location }) => {
|
||||
let mut res = response_with_status(StatusCode::TEMPORARY_REDIRECT);
|
||||
res.headers_mut().insert(http::header::LOCATION, location);
|
||||
break Poll::Ready(Ok(res));
|
||||
}
|
||||
|
||||
Ok(OpenFileOutput::FileNotFound | OpenFileOutput::InvalidFilename) => {
|
||||
if let Some((mut fallback, request)) = fallback_and_request.take() {
|
||||
call_fallback(&mut fallback, request)
|
||||
} else {
|
||||
break Poll::Ready(Ok(not_found()));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(OpenFileOutput::PreconditionFailed) => {
|
||||
break Poll::Ready(Ok(response_with_status(
|
||||
StatusCode::PRECONDITION_FAILED,
|
||||
)));
|
||||
}
|
||||
|
||||
Ok(OpenFileOutput::NotModified) => {
|
||||
break Poll::Ready(Ok(response_with_status(StatusCode::NOT_MODIFIED)));
|
||||
}
|
||||
|
||||
Ok(OpenFileOutput::InvalidRedirectUri) => {
|
||||
break Poll::Ready(Ok(response_with_status(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
)));
|
||||
}
|
||||
|
||||
Err(err) => {
|
||||
#[cfg(unix)]
|
||||
// 20 = libc::ENOTDIR => "not a directory
|
||||
// when `io_error_more` landed, this can be changed
|
||||
// to checking for `io::ErrorKind::NotADirectory`.
|
||||
// https://github.com/rust-lang/rust/issues/86442
|
||||
let error_is_not_a_directory = err.raw_os_error() == Some(20);
|
||||
#[cfg(not(unix))]
|
||||
let error_is_not_a_directory = false;
|
||||
|
||||
if matches!(
|
||||
err.kind(),
|
||||
io::ErrorKind::NotFound | io::ErrorKind::PermissionDenied
|
||||
) || error_is_not_a_directory
|
||||
{
|
||||
if let Some((mut fallback, request)) = fallback_and_request.take() {
|
||||
call_fallback(&mut fallback, request)
|
||||
} else {
|
||||
break Poll::Ready(Ok(not_found()));
|
||||
}
|
||||
} else {
|
||||
break Poll::Ready(Err(err));
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
ResponseFutureInnerProj::FallbackFuture { future } => {
|
||||
break Pin::new(future).poll(cx).map_err(|err| match err {})
|
||||
}
|
||||
|
||||
ResponseFutureInnerProj::InvalidPath {
|
||||
fallback_and_request,
|
||||
} => {
|
||||
if let Some((mut fallback, request)) = fallback_and_request.take() {
|
||||
call_fallback(&mut fallback, request)
|
||||
} else {
|
||||
break Poll::Ready(Ok(not_found()));
|
||||
}
|
||||
}
|
||||
|
||||
ResponseFutureInnerProj::MethodNotAllowed => {
|
||||
let mut res = response_with_status(StatusCode::METHOD_NOT_ALLOWED);
|
||||
res.headers_mut()
|
||||
.insert(ALLOW, HeaderValue::from_static("GET,HEAD"));
|
||||
break Poll::Ready(Ok(res));
|
||||
}
|
||||
};
|
||||
|
||||
this.inner.set(new_state);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn response_with_status(status: StatusCode) -> Response<ResponseBody> {
|
||||
Response::builder()
|
||||
.status(status)
|
||||
.body(empty_body())
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn not_found() -> Response<ResponseBody> {
|
||||
response_with_status(StatusCode::NOT_FOUND)
|
||||
}
|
||||
|
||||
pub(super) fn call_fallback<F, B, FResBody>(
|
||||
fallback: &mut F,
|
||||
req: Request<B>,
|
||||
) -> ResponseFutureInner<B, F>
|
||||
where
|
||||
F: Service<Request<B>, Response = Response<FResBody>, Error = Infallible> + Clone,
|
||||
F::Future: Send + 'static,
|
||||
FResBody: http_body::Body<Data = Bytes> + Send + 'static,
|
||||
FResBody::Error: Into<BoxError>,
|
||||
{
|
||||
let future = fallback
|
||||
.call(req)
|
||||
.map_ok(|response| {
|
||||
response
|
||||
.map(|body| {
|
||||
UnsyncBoxBody::new(
|
||||
body.map_err(|err| match err.into().downcast::<io::Error>() {
|
||||
Ok(err) => *err,
|
||||
Err(err) => io::Error::new(io::ErrorKind::Other, err),
|
||||
})
|
||||
.boxed_unsync(),
|
||||
)
|
||||
})
|
||||
.map(ResponseBody::new)
|
||||
})
|
||||
.boxed();
|
||||
|
||||
ResponseFutureInner::FallbackFuture { future }
|
||||
}
|
||||
|
||||
fn build_response(output: FileOpened) -> Response<ResponseBody> {
|
||||
let (maybe_file, size) = match output.extent {
|
||||
FileRequestExtent::Full(file, meta) => (Some(file), meta.len()),
|
||||
FileRequestExtent::Head(meta) => (None, meta.len()),
|
||||
};
|
||||
|
||||
let mut builder = Response::builder()
|
||||
.header(header::CONTENT_TYPE, output.mime_header_value)
|
||||
.header(header::ACCEPT_RANGES, "bytes");
|
||||
|
||||
if let Some(encoding) = output
|
||||
.maybe_encoding
|
||||
.filter(|encoding| *encoding != Encoding::Identity)
|
||||
{
|
||||
builder = builder.header(header::CONTENT_ENCODING, encoding.into_header_value());
|
||||
}
|
||||
|
||||
if let Some(last_modified) = output.last_modified {
|
||||
builder = builder.header(header::LAST_MODIFIED, last_modified.0.to_string());
|
||||
}
|
||||
|
||||
match output.maybe_range {
|
||||
Some(Ok(ranges)) => {
|
||||
if let Some(range) = ranges.first() {
|
||||
if ranges.len() > 1 {
|
||||
builder
|
||||
.header(header::CONTENT_RANGE, format!("bytes */{}", size))
|
||||
.status(StatusCode::RANGE_NOT_SATISFIABLE)
|
||||
.body(body_from_bytes(Bytes::from(
|
||||
"Cannot serve multipart range requests",
|
||||
)))
|
||||
.unwrap()
|
||||
} else {
|
||||
let body = if let Some(file) = maybe_file {
|
||||
let range_size = range.end() - range.start() + 1;
|
||||
ResponseBody::new(UnsyncBoxBody::new(
|
||||
AsyncReadBody::with_capacity_limited(
|
||||
file,
|
||||
output.chunk_size,
|
||||
range_size,
|
||||
)
|
||||
.boxed_unsync(),
|
||||
))
|
||||
} else {
|
||||
empty_body()
|
||||
};
|
||||
|
||||
let content_length = if size == 0 {
|
||||
0
|
||||
} else {
|
||||
range.end() - range.start() + 1
|
||||
};
|
||||
|
||||
builder
|
||||
.header(
|
||||
header::CONTENT_RANGE,
|
||||
format!("bytes {}-{}/{}", range.start(), range.end(), size),
|
||||
)
|
||||
.header(header::CONTENT_LENGTH, content_length)
|
||||
.status(StatusCode::PARTIAL_CONTENT)
|
||||
.body(body)
|
||||
.unwrap()
|
||||
}
|
||||
} else {
|
||||
builder
|
||||
.header(header::CONTENT_RANGE, format!("bytes */{}", size))
|
||||
.status(StatusCode::RANGE_NOT_SATISFIABLE)
|
||||
.body(body_from_bytes(Bytes::from(
|
||||
"No range found after parsing range header, please file an issue",
|
||||
)))
|
||||
.unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
Some(Err(_)) => builder
|
||||
.header(header::CONTENT_RANGE, format!("bytes */{}", size))
|
||||
.status(StatusCode::RANGE_NOT_SATISFIABLE)
|
||||
.body(empty_body())
|
||||
.unwrap(),
|
||||
|
||||
// Not a range request
|
||||
None => {
|
||||
let body = if let Some(file) = maybe_file {
|
||||
ResponseBody::new(UnsyncBoxBody::new(
|
||||
AsyncReadBody::with_capacity(file, output.chunk_size).boxed_unsync(),
|
||||
))
|
||||
} else {
|
||||
empty_body()
|
||||
};
|
||||
|
||||
builder
|
||||
.header(header::CONTENT_LENGTH, size)
|
||||
.body(body)
|
||||
.unwrap()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn body_from_bytes(bytes: Bytes) -> ResponseBody {
|
||||
let body = Full::from(bytes).map_err(|err| match err {}).boxed_unsync();
|
||||
ResponseBody::new(UnsyncBoxBody::new(body))
|
||||
}
|
||||
|
||||
fn empty_body() -> ResponseBody {
|
||||
let body = Empty::new().map_err(|err| match err {}).boxed_unsync();
|
||||
ResponseBody::new(UnsyncBoxBody::new(body))
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
use http::header::HeaderValue;
|
||||
use httpdate::HttpDate;
|
||||
use std::time::SystemTime;
|
||||
|
||||
pub(super) struct LastModified(pub(super) HttpDate);
|
||||
|
||||
impl From<SystemTime> for LastModified {
|
||||
fn from(time: SystemTime) -> Self {
|
||||
LastModified(time.into())
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct IfModifiedSince(HttpDate);
|
||||
|
||||
impl IfModifiedSince {
|
||||
/// Check if the supplied time means the resource has been modified.
|
||||
pub(super) fn is_modified(&self, last_modified: &LastModified) -> bool {
|
||||
self.0 < last_modified.0
|
||||
}
|
||||
|
||||
/// convert a header value into a IfModifiedSince, invalid values are silentely ignored
|
||||
pub(super) fn from_header_value(value: &HeaderValue) -> Option<IfModifiedSince> {
|
||||
std::str::from_utf8(value.as_bytes())
|
||||
.ok()
|
||||
.and_then(|value| httpdate::parse_http_date(value).ok())
|
||||
.map(|time| IfModifiedSince(time.into()))
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct IfUnmodifiedSince(HttpDate);
|
||||
|
||||
impl IfUnmodifiedSince {
|
||||
/// Check if the supplied time passes the precondtion.
|
||||
pub(super) fn precondition_passes(&self, last_modified: &LastModified) -> bool {
|
||||
self.0 >= last_modified.0
|
||||
}
|
||||
|
||||
/// Convert a header value into a IfModifiedSince, invalid values are silentely ignored
|
||||
pub(super) fn from_header_value(value: &HeaderValue) -> Option<IfUnmodifiedSince> {
|
||||
std::str::from_utf8(value.as_bytes())
|
||||
.ok()
|
||||
.and_then(|value| httpdate::parse_http_date(value).ok())
|
||||
.map(|time| IfUnmodifiedSince(time.into()))
|
||||
}
|
||||
}
|
||||
+661
@@ -0,0 +1,661 @@
|
||||
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` in case the `tracing`
|
||||
/// crate feature is enabled.
|
||||
///
|
||||
/// 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),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
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| {
|
||||
#[cfg(feature = "tracing")]
|
||||
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(_)))
|
||||
{
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
if is_reserved_dos_name(|| comp.encode_wide()) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
|
||||
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()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Check whether a component name matches a reserved Windows DOS device name.
|
||||
/// See: https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#naming-conventions
|
||||
///
|
||||
/// We explicitly check for Unicode superscript characters `¹` (0x00B9), `²` (0x00B2),
|
||||
/// and `³` (0x00B3) because older character tables (ISO/IEC 8859-1) define these values,
|
||||
/// which legacy Win32 file parsing resolves natively as valid port numbers (0..9).
|
||||
///
|
||||
/// This uses an iterator and stack array to avoid allocating. A closure is used because it
|
||||
/// iterates the characters twice. The closure must return the same iterator each time it is
|
||||
/// called.
|
||||
#[cfg(any(windows, test))]
|
||||
fn is_reserved_dos_name<F, I>(mut get_iter: F) -> bool
|
||||
where
|
||||
F: FnMut() -> I,
|
||||
I: Iterator<Item = u16>,
|
||||
{
|
||||
const CON: [u16; 3] = [b'C' as u16, b'O' as u16, b'N' as u16];
|
||||
const PRN: [u16; 3] = [b'P' as u16, b'R' as u16, b'N' as u16];
|
||||
const AUX: [u16; 3] = [b'A' as u16, b'U' as u16, b'X' as u16];
|
||||
const NUL: [u16; 3] = [b'N' as u16, b'U' as u16, b'L' as u16];
|
||||
const CONIN: [u16; 6] = [
|
||||
b'C' as u16,
|
||||
b'O' as u16,
|
||||
b'N' as u16,
|
||||
b'I' as u16,
|
||||
b'N' as u16,
|
||||
b'$' as u16,
|
||||
];
|
||||
const CONOUT: [u16; 7] = [
|
||||
b'C' as u16,
|
||||
b'O' as u16,
|
||||
b'N' as u16,
|
||||
b'O' as u16,
|
||||
b'U' as u16,
|
||||
b'T' as u16,
|
||||
b'$' as u16,
|
||||
];
|
||||
|
||||
const COM: [u16; 3] = [b'C' as u16, b'O' as u16, b'M' as u16];
|
||||
const LPT: [u16; 3] = [b'L' as u16, b'P' as u16, b'T' as u16];
|
||||
|
||||
const ZERO: u16 = b'0' as u16;
|
||||
const NINE: u16 = b'9' as u16;
|
||||
const SUPERSCRIPT_ONE: u16 = 0x00B9;
|
||||
const SUPERSCRIPT_TWO: u16 = 0x00B2;
|
||||
const SUPERSCRIPT_THREE: u16 = 0x00B3;
|
||||
|
||||
fn is_whitespace(c: u16) -> bool {
|
||||
c <= 0x7F && ((c as u8).is_ascii_whitespace() || c == 0x000B)
|
||||
}
|
||||
|
||||
// In a first pass over the string, obtain the length of the basename.
|
||||
let trimmed_len = get_iter()
|
||||
.enumerate()
|
||||
// We want the base name, so stop at '.' or ':' characters.
|
||||
.take_while(|&(_idx, c)| c != b'.' as u16 && c != b':' as u16)
|
||||
// We want to trim whitespace from the end, so ignore whitespace chars.
|
||||
.filter(|&(_idx, c)| !is_whitespace(c))
|
||||
// Get the last non-whitespace char before the first '.'/':' character.
|
||||
.last()
|
||||
// Convert index of that char into length of string.
|
||||
.map(|(idx, _)| idx + 1)
|
||||
.unwrap_or(0);
|
||||
|
||||
// If the trimmed base name is longer than 7, it cannot be a reserved name.
|
||||
if trimmed_len > 7 {
|
||||
return false;
|
||||
}
|
||||
|
||||
// At this point, we can store the string in an array, which is more convenient to work with.
|
||||
let mut buf = [0u16; 7];
|
||||
get_iter()
|
||||
.take(trimmed_len)
|
||||
.enumerate()
|
||||
.for_each(|(i, c)| buf[i] = c);
|
||||
|
||||
for b in &mut buf {
|
||||
if *b <= 0x7F {
|
||||
*b = (*b as u8).to_ascii_uppercase() as u16;
|
||||
}
|
||||
if *b == SUPERSCRIPT_ONE {
|
||||
*b = b'1' as u16;
|
||||
}
|
||||
if *b == SUPERSCRIPT_TWO {
|
||||
*b = b'2' as u16;
|
||||
}
|
||||
if *b == SUPERSCRIPT_THREE {
|
||||
*b = b'3' as u16;
|
||||
}
|
||||
}
|
||||
let name = &buf[..trimmed_len];
|
||||
|
||||
// Check basic fixed-length strings
|
||||
if name == CON || name == PRN || name == AUX || name == NUL || name == CONIN || name == CONOUT {
|
||||
return true;
|
||||
}
|
||||
|
||||
// COMx / LPTx
|
||||
if name.len() == 4 {
|
||||
let prefix = &name[..3];
|
||||
let suffix = name[3];
|
||||
|
||||
if (prefix == COM || prefix == LPT) && matches!(suffix, ZERO..=NINE) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,371 @@
|
||||
use super::{
|
||||
headers::{IfModifiedSince, IfUnmodifiedSince, LastModified},
|
||||
ServeVariant,
|
||||
};
|
||||
use crate::content_encoding::{Encoding, QValue};
|
||||
use bytes::Bytes;
|
||||
use http::{header, HeaderValue, Method, Request, Uri};
|
||||
use http_body_util::Empty;
|
||||
use http_range_header::RangeUnsatisfiableError;
|
||||
use std::{
|
||||
ffi::OsStr,
|
||||
fs::Metadata,
|
||||
io::{self, ErrorKind, SeekFrom},
|
||||
ops::RangeInclusive,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
use tokio::{fs::File, io::AsyncSeekExt};
|
||||
|
||||
pub(super) enum OpenFileOutput {
|
||||
FileOpened(Box<FileOpened>),
|
||||
Redirect { location: HeaderValue },
|
||||
FileNotFound,
|
||||
PreconditionFailed,
|
||||
NotModified,
|
||||
InvalidRedirectUri,
|
||||
InvalidFilename,
|
||||
}
|
||||
|
||||
pub(super) struct FileOpened {
|
||||
pub(super) extent: FileRequestExtent,
|
||||
pub(super) chunk_size: usize,
|
||||
pub(super) mime_header_value: HeaderValue,
|
||||
pub(super) maybe_encoding: Option<Encoding>,
|
||||
pub(super) maybe_range: Option<Result<Vec<RangeInclusive<u64>>, RangeUnsatisfiableError>>,
|
||||
pub(super) last_modified: Option<LastModified>,
|
||||
}
|
||||
|
||||
pub(super) enum FileRequestExtent {
|
||||
Full(File, Metadata),
|
||||
Head(Metadata),
|
||||
}
|
||||
|
||||
pub(super) async fn open_file(
|
||||
variant: ServeVariant,
|
||||
mut path_to_file: PathBuf,
|
||||
req: Request<Empty<Bytes>>,
|
||||
negotiated_encodings: Vec<(Encoding, QValue)>,
|
||||
range_header: Option<String>,
|
||||
buf_chunk_size: usize,
|
||||
) -> io::Result<OpenFileOutput> {
|
||||
let if_unmodified_since = req
|
||||
.headers()
|
||||
.get(header::IF_UNMODIFIED_SINCE)
|
||||
.and_then(IfUnmodifiedSince::from_header_value);
|
||||
|
||||
let if_modified_since = req
|
||||
.headers()
|
||||
.get(header::IF_MODIFIED_SINCE)
|
||||
.and_then(IfModifiedSince::from_header_value);
|
||||
|
||||
let mime = match variant {
|
||||
ServeVariant::Directory {
|
||||
append_index_html_on_directories,
|
||||
} => {
|
||||
// Might already at this point know a redirect or not found result should be
|
||||
// returned which corresponds to a Some(output). Otherwise the path might be
|
||||
// modified and proceed to the open file/metadata future.
|
||||
if let Some(output) = maybe_redirect_or_append_path(
|
||||
&mut path_to_file,
|
||||
req.uri(),
|
||||
append_index_html_on_directories,
|
||||
)
|
||||
.await
|
||||
{
|
||||
return Ok(output);
|
||||
}
|
||||
|
||||
mime_guess::from_path(&path_to_file)
|
||||
.first_raw()
|
||||
.map(HeaderValue::from_static)
|
||||
.unwrap_or_else(|| {
|
||||
HeaderValue::from_str(mime::APPLICATION_OCTET_STREAM.as_ref()).unwrap()
|
||||
})
|
||||
}
|
||||
|
||||
ServeVariant::SingleFile { mime } => mime,
|
||||
};
|
||||
|
||||
if req.method() == Method::HEAD {
|
||||
let (meta, maybe_encoding) =
|
||||
file_metadata_with_fallback(path_to_file, negotiated_encodings).await?;
|
||||
|
||||
let last_modified = meta.modified().ok().map(LastModified::from);
|
||||
if let Some(output) = check_modified_headers(
|
||||
last_modified.as_ref(),
|
||||
if_unmodified_since,
|
||||
if_modified_since,
|
||||
) {
|
||||
return Ok(output);
|
||||
}
|
||||
|
||||
let maybe_range = try_parse_range(range_header.as_deref(), meta.len());
|
||||
|
||||
Ok(OpenFileOutput::FileOpened(Box::new(FileOpened {
|
||||
extent: FileRequestExtent::Head(meta),
|
||||
chunk_size: buf_chunk_size,
|
||||
mime_header_value: mime,
|
||||
maybe_encoding,
|
||||
maybe_range,
|
||||
last_modified,
|
||||
})))
|
||||
} else {
|
||||
let (mut file, maybe_encoding) =
|
||||
match open_file_with_fallback(path_to_file, negotiated_encodings).await {
|
||||
Ok(result) => result,
|
||||
|
||||
Err(err) if is_invalid_filename_error(&err) => {
|
||||
return Ok(OpenFileOutput::InvalidFilename)
|
||||
}
|
||||
Err(err) => return Err(err),
|
||||
};
|
||||
|
||||
let meta = file.metadata().await?;
|
||||
let last_modified = meta.modified().ok().map(LastModified::from);
|
||||
if let Some(output) = check_modified_headers(
|
||||
last_modified.as_ref(),
|
||||
if_unmodified_since,
|
||||
if_modified_since,
|
||||
) {
|
||||
return Ok(output);
|
||||
}
|
||||
|
||||
let maybe_range = try_parse_range(range_header.as_deref(), meta.len());
|
||||
if let Some(Ok(ranges)) = maybe_range.as_ref() {
|
||||
// if there is any other amount of ranges than 1 we'll return an
|
||||
// unsatisfiable later as there isn't yet support for multipart ranges
|
||||
if ranges.len() == 1 {
|
||||
file.seek(SeekFrom::Start(*ranges[0].start())).await?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(OpenFileOutput::FileOpened(Box::new(FileOpened {
|
||||
extent: FileRequestExtent::Full(file, meta),
|
||||
chunk_size: buf_chunk_size,
|
||||
mime_header_value: mime,
|
||||
maybe_encoding,
|
||||
maybe_range,
|
||||
last_modified,
|
||||
})))
|
||||
}
|
||||
}
|
||||
|
||||
fn is_invalid_filename_error(err: &io::Error) -> bool {
|
||||
// Only applies to NULL bytes
|
||||
if err.kind() == ErrorKind::InvalidInput {
|
||||
return true;
|
||||
}
|
||||
|
||||
// FIXME: Remove when MSRV >= 1.87.
|
||||
// `io::ErrorKind::InvalidFilename` is stabilized in v1.87
|
||||
#[cfg(windows)]
|
||||
if let Some(raw_err) = err.raw_os_error() {
|
||||
// https://github.com/rust-lang/rust/blob/70e2b4a4d197f154bed0eb3dcb5cac6a948ff3a3/library/std/src/sys/pal/windows/mod.rs
|
||||
// Lines 81 and 115
|
||||
if (raw_err == 123) || (raw_err == 161) || (raw_err == 206) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
fn check_modified_headers(
|
||||
modified: Option<&LastModified>,
|
||||
if_unmodified_since: Option<IfUnmodifiedSince>,
|
||||
if_modified_since: Option<IfModifiedSince>,
|
||||
) -> Option<OpenFileOutput> {
|
||||
if let Some(since) = if_unmodified_since {
|
||||
let precondition = modified
|
||||
.as_ref()
|
||||
.map(|time| since.precondition_passes(time))
|
||||
.unwrap_or(false);
|
||||
|
||||
if !precondition {
|
||||
return Some(OpenFileOutput::PreconditionFailed);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(since) = if_modified_since {
|
||||
let unmodified = modified
|
||||
.as_ref()
|
||||
.map(|time| !since.is_modified(time))
|
||||
// no last_modified means its always modified
|
||||
.unwrap_or(false);
|
||||
if unmodified {
|
||||
return Some(OpenFileOutput::NotModified);
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
// Returns the preferred_encoding encoding and modifies the path extension
|
||||
// to the corresponding file extension for the encoding.
|
||||
fn preferred_encoding(
|
||||
path: &mut PathBuf,
|
||||
negotiated_encoding: &[(Encoding, QValue)],
|
||||
) -> Option<Encoding> {
|
||||
let preferred_encoding = Encoding::preferred_encoding(negotiated_encoding.iter().copied());
|
||||
|
||||
if let Some(file_extension) =
|
||||
preferred_encoding.and_then(|encoding| encoding.to_file_extension())
|
||||
{
|
||||
let new_file_name = path
|
||||
.file_name()
|
||||
.map(|file_name| {
|
||||
let mut os_string = file_name.to_os_string();
|
||||
os_string.push(file_extension);
|
||||
os_string
|
||||
})
|
||||
.unwrap_or_else(|| file_extension.to_os_string());
|
||||
|
||||
path.set_file_name(new_file_name);
|
||||
}
|
||||
|
||||
preferred_encoding
|
||||
}
|
||||
|
||||
// Attempts to open the file with any of the possible negotiated_encodings in the
|
||||
// preferred order. If none of the negotiated_encodings have a corresponding precompressed
|
||||
// file the uncompressed file is used as a fallback.
|
||||
async fn open_file_with_fallback(
|
||||
mut path: PathBuf,
|
||||
mut negotiated_encoding: Vec<(Encoding, QValue)>,
|
||||
) -> io::Result<(File, Option<Encoding>)> {
|
||||
let (file, encoding) = loop {
|
||||
// Get the preferred encoding among the negotiated ones.
|
||||
let encoding = preferred_encoding(&mut path, &negotiated_encoding);
|
||||
match (File::open(&path).await, encoding) {
|
||||
(Ok(file), maybe_encoding) => break (file, maybe_encoding),
|
||||
(Err(err), Some(encoding)) if err.kind() == io::ErrorKind::NotFound => {
|
||||
// Remove the extension corresponding to a precompressed file (.gz, .br, .zz)
|
||||
// to reset the path before the next iteration.
|
||||
path.set_extension(OsStr::new(""));
|
||||
// Remove the encoding from the negotiated_encodings since the file doesn't exist
|
||||
negotiated_encoding
|
||||
.retain(|(negotiated_encoding, _)| *negotiated_encoding != encoding);
|
||||
}
|
||||
(Err(err), _) => return Err(err),
|
||||
}
|
||||
};
|
||||
Ok((file, encoding))
|
||||
}
|
||||
|
||||
// Attempts to get the file metadata with any of the possible negotiated_encodings in the
|
||||
// preferred order. If none of the negotiated_encodings have a corresponding precompressed
|
||||
// file the uncompressed file is used as a fallback.
|
||||
async fn file_metadata_with_fallback(
|
||||
mut path: PathBuf,
|
||||
mut negotiated_encoding: Vec<(Encoding, QValue)>,
|
||||
) -> io::Result<(Metadata, Option<Encoding>)> {
|
||||
let (file, encoding) = loop {
|
||||
// Get the preferred encoding among the negotiated ones.
|
||||
let encoding = preferred_encoding(&mut path, &negotiated_encoding);
|
||||
match (tokio::fs::metadata(&path).await, encoding) {
|
||||
(Ok(file), maybe_encoding) => break (file, maybe_encoding),
|
||||
(Err(err), Some(encoding)) if err.kind() == io::ErrorKind::NotFound => {
|
||||
// Remove the extension corresponding to a precompressed file (.gz, .br, .zz)
|
||||
// to reset the path before the next iteration.
|
||||
path.set_extension(OsStr::new(""));
|
||||
// Remove the encoding from the negotiated_encodings since the file doesn't exist
|
||||
negotiated_encoding
|
||||
.retain(|(negotiated_encoding, _)| *negotiated_encoding != encoding);
|
||||
}
|
||||
(Err(err), _) => return Err(err),
|
||||
}
|
||||
};
|
||||
Ok((file, encoding))
|
||||
}
|
||||
|
||||
async fn maybe_redirect_or_append_path(
|
||||
path_to_file: &mut PathBuf,
|
||||
uri: &Uri,
|
||||
append_index_html_on_directories: bool,
|
||||
) -> Option<OpenFileOutput> {
|
||||
if !is_dir(path_to_file).await {
|
||||
return None;
|
||||
}
|
||||
|
||||
if !append_index_html_on_directories {
|
||||
return Some(OpenFileOutput::FileNotFound);
|
||||
}
|
||||
|
||||
if uri.path().ends_with('/') {
|
||||
path_to_file.push("index.html");
|
||||
None
|
||||
} else {
|
||||
let uri = match append_slash_on_path(uri.clone()) {
|
||||
Ok(uri) => uri,
|
||||
Err(err) => return Some(err),
|
||||
};
|
||||
let location = HeaderValue::from_str(&uri.to_string()).unwrap();
|
||||
Some(OpenFileOutput::Redirect { location })
|
||||
}
|
||||
}
|
||||
|
||||
fn try_parse_range(
|
||||
maybe_range_ref: Option<&str>,
|
||||
file_size: u64,
|
||||
) -> Option<Result<Vec<RangeInclusive<u64>>, RangeUnsatisfiableError>> {
|
||||
maybe_range_ref.map(|header_value| {
|
||||
http_range_header::parse_range_header(header_value)
|
||||
.and_then(|first_pass| first_pass.validate(file_size))
|
||||
})
|
||||
}
|
||||
|
||||
async fn is_dir(path_to_file: &Path) -> bool {
|
||||
tokio::fs::metadata(path_to_file)
|
||||
.await
|
||||
.map_or(false, |meta_data| meta_data.is_dir())
|
||||
}
|
||||
|
||||
fn append_slash_on_path(uri: Uri) -> Result<Uri, OpenFileOutput> {
|
||||
let http::uri::Parts {
|
||||
scheme,
|
||||
authority,
|
||||
path_and_query,
|
||||
..
|
||||
} = uri.into_parts();
|
||||
|
||||
let mut uri_builder = Uri::builder();
|
||||
|
||||
if let Some(scheme) = scheme {
|
||||
uri_builder = uri_builder.scheme(scheme);
|
||||
}
|
||||
|
||||
if let Some(authority) = authority {
|
||||
uri_builder = uri_builder.authority(authority);
|
||||
}
|
||||
|
||||
let uri_builder = if let Some(path_and_query) = path_and_query {
|
||||
if let Some(query) = path_and_query.query() {
|
||||
uri_builder.path_and_query(format!("{}/?{}", path_and_query.path(), query))
|
||||
} else {
|
||||
uri_builder.path_and_query(format!("{}/", path_and_query.path()))
|
||||
}
|
||||
} else {
|
||||
uri_builder.path_and_query("/")
|
||||
};
|
||||
|
||||
uri_builder.build().map_err(|_err| {
|
||||
#[cfg(feature = "tracing")]
|
||||
tracing::error!(err = ?_err, "redirect uri failed to build");
|
||||
|
||||
OpenFileOutput::InvalidRedirectUri
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preferred_encoding_with_extension() {
|
||||
let mut path = PathBuf::from("hello.txt");
|
||||
preferred_encoding(&mut path, &[(Encoding::Gzip, QValue::one())]);
|
||||
assert_eq!(path, PathBuf::from("hello.txt.gz"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preferred_encoding_without_extension() {
|
||||
let mut path = PathBuf::from("hello");
|
||||
preferred_encoding(&mut path, &[(Encoding::Gzip, QValue::one())]);
|
||||
assert_eq!(path, PathBuf::from("hello.gz"));
|
||||
}
|
||||
+1036
File diff suppressed because it is too large
Load Diff
+560
@@ -0,0 +1,560 @@
|
||||
//! Service that serves a file.
|
||||
|
||||
use super::ServeDir;
|
||||
use http::{HeaderValue, Request};
|
||||
use mime::Mime;
|
||||
use std::{
|
||||
path::Path,
|
||||
task::{Context, Poll},
|
||||
};
|
||||
use tower_service::Service;
|
||||
|
||||
/// Service that serves a file.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ServeFile(ServeDir);
|
||||
|
||||
// Note that this is just a special case of ServeDir
|
||||
impl ServeFile {
|
||||
/// Create a new [`ServeFile`].
|
||||
///
|
||||
/// The `Content-Type` will be guessed from the file extension.
|
||||
pub fn new<P: AsRef<Path>>(path: P) -> Self {
|
||||
let guess = mime_guess::from_path(path.as_ref());
|
||||
let mime = guess
|
||||
.first_raw()
|
||||
.map(HeaderValue::from_static)
|
||||
.unwrap_or_else(|| {
|
||||
HeaderValue::from_str(mime::APPLICATION_OCTET_STREAM.as_ref()).unwrap()
|
||||
});
|
||||
|
||||
Self(ServeDir::new_single_file(path, mime))
|
||||
}
|
||||
|
||||
/// Create a new [`ServeFile`] with a specific mime type.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Will panic if the mime type isn't a valid [header value].
|
||||
///
|
||||
/// [header value]: https://docs.rs/http/latest/http/header/struct.HeaderValue.html
|
||||
pub fn new_with_mime<P: AsRef<Path>>(path: P, mime: &Mime) -> Self {
|
||||
let mime = HeaderValue::from_str(mime.as_ref()).expect("mime isn't a valid header value");
|
||||
Self(ServeDir::new_single_file(path, mime))
|
||||
}
|
||||
|
||||
/// Informs the service that it should also look for a precompressed gzip
|
||||
/// version of the file.
|
||||
///
|
||||
/// If the client has an `Accept-Encoding` header that allows the gzip encoding,
|
||||
/// the file `foo.txt.gz` will be served instead of `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 same directory. Different precompressed
|
||||
/// variants can be combined.
|
||||
pub fn precompressed_gzip(self) -> Self {
|
||||
Self(self.0.precompressed_gzip())
|
||||
}
|
||||
|
||||
/// Informs the service that it should also look for a precompressed brotli
|
||||
/// version of the file.
|
||||
///
|
||||
/// If the client has an `Accept-Encoding` header that allows the brotli encoding,
|
||||
/// the file `foo.txt.br` will be served instead of `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 same directory. Different precompressed
|
||||
/// variants can be combined.
|
||||
pub fn precompressed_br(self) -> Self {
|
||||
Self(self.0.precompressed_br())
|
||||
}
|
||||
|
||||
/// Informs the service that it should also look for a precompressed deflate
|
||||
/// version of the file.
|
||||
///
|
||||
/// If the client has an `Accept-Encoding` header that allows the deflate encoding,
|
||||
/// the file `foo.txt.zz` will be served instead of `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 same directory. Different precompressed
|
||||
/// variants can be combined.
|
||||
pub fn precompressed_deflate(self) -> Self {
|
||||
Self(self.0.precompressed_deflate())
|
||||
}
|
||||
|
||||
/// Informs the service that it should also look for a precompressed zstd
|
||||
/// version of the file.
|
||||
///
|
||||
/// If the client has an `Accept-Encoding` header that allows the zstd encoding,
|
||||
/// the file `foo.txt.zst` will be served instead of `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 same directory. Different precompressed
|
||||
/// variants can be combined.
|
||||
pub fn precompressed_zstd(self) -> Self {
|
||||
Self(self.0.precompressed_zstd())
|
||||
}
|
||||
|
||||
/// Set a specific read buffer chunk size.
|
||||
///
|
||||
/// The default capacity is 64kb.
|
||||
pub fn with_buf_chunk_size(self, chunk_size: usize) -> Self {
|
||||
Self(self.0.with_buf_chunk_size(chunk_size))
|
||||
}
|
||||
|
||||
/// Call the service and get a future that contains any `std::io::Error` that might have
|
||||
/// happened.
|
||||
///
|
||||
/// See [`ServeDir::try_call`] for more details.
|
||||
pub fn try_call<ReqBody>(
|
||||
&mut self,
|
||||
req: Request<ReqBody>,
|
||||
) -> super::serve_dir::future::ResponseFuture<ReqBody>
|
||||
where
|
||||
ReqBody: Send + 'static,
|
||||
{
|
||||
self.0.try_call(req)
|
||||
}
|
||||
}
|
||||
|
||||
impl<ReqBody> Service<Request<ReqBody>> for ServeFile
|
||||
where
|
||||
ReqBody: Send + 'static,
|
||||
{
|
||||
type Error = <ServeDir as Service<Request<ReqBody>>>::Error;
|
||||
type Response = <ServeDir as Service<Request<ReqBody>>>::Response;
|
||||
type Future = <ServeDir as Service<Request<ReqBody>>>::Future;
|
||||
|
||||
#[inline]
|
||||
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn call(&mut self, req: Request<ReqBody>) -> Self::Future {
|
||||
self.0.call(req)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::services::ServeFile;
|
||||
use crate::test_helpers::Body;
|
||||
use async_compression::tokio::bufread::ZstdDecoder;
|
||||
use brotli::BrotliDecompress;
|
||||
use flate2::bufread::DeflateDecoder;
|
||||
use flate2::bufread::GzDecoder;
|
||||
use http::header;
|
||||
use http::Method;
|
||||
use http::{Request, StatusCode};
|
||||
use http_body_util::BodyExt;
|
||||
use mime::Mime;
|
||||
use std::io::Read;
|
||||
use std::str::FromStr;
|
||||
use tokio::io::AsyncReadExt;
|
||||
use tower::ServiceExt;
|
||||
|
||||
#[tokio::test]
|
||||
async fn basic() {
|
||||
let svc = ServeFile::new("../README.md");
|
||||
|
||||
let res = svc.oneshot(Request::new(Body::empty())).await.unwrap();
|
||||
|
||||
assert_eq!(res.headers()["content-type"], "text/markdown");
|
||||
|
||||
let body = res.into_body().collect().await.unwrap().to_bytes();
|
||||
let body = String::from_utf8(body.to_vec()).unwrap();
|
||||
|
||||
assert!(body.starts_with("# Tower HTTP"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn basic_with_mime() {
|
||||
let svc = ServeFile::new_with_mime("../README.md", &Mime::from_str("image/jpg").unwrap());
|
||||
|
||||
let res = svc.oneshot(Request::new(Body::empty())).await.unwrap();
|
||||
|
||||
assert_eq!(res.headers()["content-type"], "image/jpg");
|
||||
|
||||
let body = res.into_body().collect().await.unwrap().to_bytes();
|
||||
let body = String::from_utf8(body.to_vec()).unwrap();
|
||||
|
||||
assert!(body.starts_with("# Tower HTTP"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn head_request() {
|
||||
let svc = ServeFile::new("../test-files/precompressed.txt");
|
||||
|
||||
let mut request = Request::new(Body::empty());
|
||||
*request.method_mut() = Method::HEAD;
|
||||
let res = svc.oneshot(request).await.unwrap();
|
||||
|
||||
assert_eq!(res.headers()["content-type"], "text/plain");
|
||||
assert_eq!(res.headers()["content-length"], "23");
|
||||
|
||||
assert!(res.into_body().frame().await.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn precompresed_head_request() {
|
||||
let svc = ServeFile::new("../test-files/precompressed.txt").precompressed_gzip();
|
||||
|
||||
let request = Request::builder()
|
||||
.header("Accept-Encoding", "gzip")
|
||||
.method(Method::HEAD)
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
let res = svc.oneshot(request).await.unwrap();
|
||||
|
||||
assert_eq!(res.headers()["content-type"], "text/plain");
|
||||
assert_eq!(res.headers()["content-encoding"], "gzip");
|
||||
assert_eq!(res.headers()["content-length"], "59");
|
||||
|
||||
assert!(res.into_body().frame().await.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn precompressed_gzip() {
|
||||
let svc = ServeFile::new("../test-files/precompressed.txt").precompressed_gzip();
|
||||
|
||||
let request = Request::builder()
|
||||
.header("Accept-Encoding", "gzip")
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
let res = svc.oneshot(request).await.unwrap();
|
||||
|
||||
assert_eq!(res.headers()["content-type"], "text/plain");
|
||||
assert_eq!(res.headers()["content-encoding"], "gzip");
|
||||
|
||||
let body = res.into_body().collect().await.unwrap().to_bytes();
|
||||
let mut decoder = GzDecoder::new(&body[..]);
|
||||
let mut decompressed = String::new();
|
||||
decoder.read_to_string(&mut decompressed).unwrap();
|
||||
assert!(decompressed.starts_with("\"This is a test file!\""));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unsupported_precompression_alogrithm_fallbacks_to_uncompressed() {
|
||||
let svc = ServeFile::new("../test-files/precompressed.txt").precompressed_gzip();
|
||||
|
||||
let request = Request::builder()
|
||||
.header("Accept-Encoding", "br")
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
let res = svc.oneshot(request).await.unwrap();
|
||||
|
||||
assert_eq!(res.headers()["content-type"], "text/plain");
|
||||
assert!(res.headers().get("content-encoding").is_none());
|
||||
|
||||
let body = res.into_body().collect().await.unwrap().to_bytes();
|
||||
let body = String::from_utf8(body.to_vec()).unwrap();
|
||||
assert!(body.starts_with("\"This is a test file!\""));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn missing_precompressed_variant_fallbacks_to_uncompressed() {
|
||||
let svc = ServeFile::new("../test-files/missing_precompressed.txt").precompressed_gzip();
|
||||
|
||||
let request = Request::builder()
|
||||
.header("Accept-Encoding", "gzip")
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
let res = svc.oneshot(request).await.unwrap();
|
||||
|
||||
assert_eq!(res.headers()["content-type"], "text/plain");
|
||||
// Uncompressed file is served because compressed version is missing
|
||||
assert!(res.headers().get("content-encoding").is_none());
|
||||
|
||||
let body = res.into_body().collect().await.unwrap().to_bytes();
|
||||
let body = String::from_utf8(body.to_vec()).unwrap();
|
||||
assert!(body.starts_with("Test file!"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn missing_precompressed_variant_fallbacks_to_uncompressed_head_request() {
|
||||
let svc = ServeFile::new("../test-files/missing_precompressed.txt").precompressed_gzip();
|
||||
|
||||
let request = Request::builder()
|
||||
.header("Accept-Encoding", "gzip")
|
||||
.method(Method::HEAD)
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
let res = svc.oneshot(request).await.unwrap();
|
||||
|
||||
assert_eq!(res.headers()["content-type"], "text/plain");
|
||||
assert_eq!(res.headers()["content-length"], "11");
|
||||
// Uncompressed file is served because compressed version is missing
|
||||
assert!(res.headers().get("content-encoding").is_none());
|
||||
|
||||
assert!(res.into_body().frame().await.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn only_precompressed_variant_existing() {
|
||||
let svc = ServeFile::new("../test-files/only_gzipped.txt").precompressed_gzip();
|
||||
|
||||
let request = Request::builder().body(Body::empty()).unwrap();
|
||||
let res = svc.clone().oneshot(request).await.unwrap();
|
||||
|
||||
assert_eq!(res.status(), StatusCode::NOT_FOUND);
|
||||
|
||||
// Should reply with gzipped file if client supports it
|
||||
let request = Request::builder()
|
||||
.header("Accept-Encoding", "gzip")
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
let res = svc.oneshot(request).await.unwrap();
|
||||
|
||||
assert_eq!(res.headers()["content-type"], "text/plain");
|
||||
assert_eq!(res.headers()["content-encoding"], "gzip");
|
||||
|
||||
let body = res.into_body().collect().await.unwrap().to_bytes();
|
||||
let mut decoder = GzDecoder::new(&body[..]);
|
||||
let mut decompressed = String::new();
|
||||
decoder.read_to_string(&mut decompressed).unwrap();
|
||||
assert!(decompressed.starts_with("\"This is a test file\""));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn precompressed_br() {
|
||||
let svc = ServeFile::new("../test-files/precompressed.txt").precompressed_br();
|
||||
|
||||
let request = Request::builder()
|
||||
.header("Accept-Encoding", "gzip,br")
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
let res = svc.oneshot(request).await.unwrap();
|
||||
|
||||
assert_eq!(res.headers()["content-type"], "text/plain");
|
||||
assert_eq!(res.headers()["content-encoding"], "br");
|
||||
|
||||
let body = res.into_body().collect().await.unwrap().to_bytes();
|
||||
let mut decompressed = Vec::new();
|
||||
BrotliDecompress(&mut &body[..], &mut decompressed).unwrap();
|
||||
let decompressed = String::from_utf8(decompressed.to_vec()).unwrap();
|
||||
assert!(decompressed.starts_with("\"This is a test file!\""));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn precompressed_deflate() {
|
||||
let svc = ServeFile::new("../test-files/precompressed.txt").precompressed_deflate();
|
||||
let request = Request::builder()
|
||||
.header("Accept-Encoding", "deflate,br")
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
let res = svc.oneshot(request).await.unwrap();
|
||||
|
||||
assert_eq!(res.headers()["content-type"], "text/plain");
|
||||
assert_eq!(res.headers()["content-encoding"], "deflate");
|
||||
|
||||
let body = res.into_body().collect().await.unwrap().to_bytes();
|
||||
let mut decoder = DeflateDecoder::new(&body[..]);
|
||||
let mut decompressed = String::new();
|
||||
decoder.read_to_string(&mut decompressed).unwrap();
|
||||
assert!(decompressed.starts_with("\"This is a test file!\""));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn precompressed_zstd() {
|
||||
let svc = ServeFile::new("../test-files/precompressed.txt").precompressed_zstd();
|
||||
let request = Request::builder()
|
||||
.header("Accept-Encoding", "zstd,br")
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
let res = svc.oneshot(request).await.unwrap();
|
||||
|
||||
assert_eq!(res.headers()["content-type"], "text/plain");
|
||||
assert_eq!(res.headers()["content-encoding"], "zstd");
|
||||
|
||||
let body = res.into_body().collect().await.unwrap().to_bytes();
|
||||
let mut decoder = ZstdDecoder::new(&body[..]);
|
||||
let mut decompressed = String::new();
|
||||
decoder.read_to_string(&mut decompressed).await.unwrap();
|
||||
assert!(decompressed.starts_with("\"This is a test file!\""));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn multi_precompressed() {
|
||||
let svc = ServeFile::new("../test-files/precompressed.txt")
|
||||
.precompressed_gzip()
|
||||
.precompressed_br();
|
||||
|
||||
let request = Request::builder()
|
||||
.header("Accept-Encoding", "gzip")
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
let res = svc.clone().oneshot(request).await.unwrap();
|
||||
|
||||
assert_eq!(res.headers()["content-type"], "text/plain");
|
||||
assert_eq!(res.headers()["content-encoding"], "gzip");
|
||||
|
||||
let body = res.into_body().collect().await.unwrap().to_bytes();
|
||||
let mut decoder = GzDecoder::new(&body[..]);
|
||||
let mut decompressed = String::new();
|
||||
decoder.read_to_string(&mut decompressed).unwrap();
|
||||
assert!(decompressed.starts_with("\"This is a test file!\""));
|
||||
|
||||
let request = Request::builder()
|
||||
.header("Accept-Encoding", "br")
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
let res = svc.clone().oneshot(request).await.unwrap();
|
||||
|
||||
assert_eq!(res.headers()["content-type"], "text/plain");
|
||||
assert_eq!(res.headers()["content-encoding"], "br");
|
||||
|
||||
let body = res.into_body().collect().await.unwrap().to_bytes();
|
||||
let mut decompressed = Vec::new();
|
||||
BrotliDecompress(&mut &body[..], &mut decompressed).unwrap();
|
||||
let decompressed = String::from_utf8(decompressed.to_vec()).unwrap();
|
||||
assert!(decompressed.starts_with("\"This is a test file!\""));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn with_custom_chunk_size() {
|
||||
let svc = ServeFile::new("../README.md").with_buf_chunk_size(1024 * 32);
|
||||
|
||||
let res = svc.oneshot(Request::new(Body::empty())).await.unwrap();
|
||||
|
||||
assert_eq!(res.headers()["content-type"], "text/markdown");
|
||||
|
||||
let body = res.into_body().collect().await.unwrap().to_bytes();
|
||||
let body = String::from_utf8(body.to_vec()).unwrap();
|
||||
|
||||
assert!(body.starts_with("# Tower HTTP"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn fallbacks_to_different_precompressed_variant_if_not_found() {
|
||||
let svc = ServeFile::new("../test-files/precompressed_br.txt")
|
||||
.precompressed_gzip()
|
||||
.precompressed_deflate()
|
||||
.precompressed_br();
|
||||
|
||||
let request = Request::builder()
|
||||
.header("Accept-Encoding", "gzip,deflate,br")
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
let res = svc.oneshot(request).await.unwrap();
|
||||
|
||||
assert_eq!(res.headers()["content-type"], "text/plain");
|
||||
assert_eq!(res.headers()["content-encoding"], "br");
|
||||
|
||||
let body = res.into_body().collect().await.unwrap().to_bytes();
|
||||
let mut decompressed = Vec::new();
|
||||
BrotliDecompress(&mut &body[..], &mut decompressed).unwrap();
|
||||
let decompressed = String::from_utf8(decompressed.to_vec()).unwrap();
|
||||
assert!(decompressed.starts_with("Test file"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn fallbacks_to_different_precompressed_variant_if_not_found_head_request() {
|
||||
let svc = ServeFile::new("../test-files/precompressed_br.txt")
|
||||
.precompressed_gzip()
|
||||
.precompressed_deflate()
|
||||
.precompressed_br();
|
||||
|
||||
let request = Request::builder()
|
||||
.header("Accept-Encoding", "gzip,deflate,br")
|
||||
.method(Method::HEAD)
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
let res = svc.oneshot(request).await.unwrap();
|
||||
|
||||
assert_eq!(res.headers()["content-type"], "text/plain");
|
||||
assert_eq!(res.headers()["content-length"], "15");
|
||||
assert_eq!(res.headers()["content-encoding"], "br");
|
||||
|
||||
assert!(res.into_body().frame().await.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn returns_404_if_file_doesnt_exist() {
|
||||
let svc = ServeFile::new("../this-doesnt-exist.md");
|
||||
|
||||
let res = svc.oneshot(Request::new(Body::empty())).await.unwrap();
|
||||
|
||||
assert_eq!(res.status(), StatusCode::NOT_FOUND);
|
||||
assert!(res.headers().get(header::CONTENT_TYPE).is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn returns_404_if_file_doesnt_exist_when_precompression_is_used() {
|
||||
let svc = ServeFile::new("../this-doesnt-exist.md").precompressed_deflate();
|
||||
|
||||
let request = Request::builder()
|
||||
.header("Accept-Encoding", "deflate")
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
let res = svc.oneshot(request).await.unwrap();
|
||||
|
||||
assert_eq!(res.status(), StatusCode::NOT_FOUND);
|
||||
assert!(res.headers().get(header::CONTENT_TYPE).is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn last_modified() {
|
||||
let svc = ServeFile::new("../README.md");
|
||||
|
||||
let req = Request::builder().body(Body::empty()).unwrap();
|
||||
let res = svc.oneshot(req).await.unwrap();
|
||||
|
||||
assert_eq!(res.status(), StatusCode::OK);
|
||||
|
||||
let last_modified = res
|
||||
.headers()
|
||||
.get(header::LAST_MODIFIED)
|
||||
.expect("Missing last modified header!");
|
||||
|
||||
// -- If-Modified-Since
|
||||
|
||||
let svc = ServeFile::new("../README.md");
|
||||
let req = Request::builder()
|
||||
.header(header::IF_MODIFIED_SINCE, last_modified)
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
|
||||
let res = svc.oneshot(req).await.unwrap();
|
||||
assert_eq!(res.status(), StatusCode::NOT_MODIFIED);
|
||||
assert!(res.into_body().frame().await.is_none());
|
||||
|
||||
let svc = ServeFile::new("../README.md");
|
||||
let req = Request::builder()
|
||||
.header(header::IF_MODIFIED_SINCE, "Fri, 09 Aug 1996 14:21:40 GMT")
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
|
||||
let res = svc.oneshot(req).await.unwrap();
|
||||
assert_eq!(res.status(), StatusCode::OK);
|
||||
let readme_bytes = include_bytes!("../../../../README.md");
|
||||
let body = res.into_body().collect().await.unwrap().to_bytes();
|
||||
assert_eq!(body.as_ref(), readme_bytes);
|
||||
|
||||
// -- If-Unmodified-Since
|
||||
|
||||
let svc = ServeFile::new("../README.md");
|
||||
let req = Request::builder()
|
||||
.header(header::IF_UNMODIFIED_SINCE, last_modified)
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
|
||||
let res = svc.oneshot(req).await.unwrap();
|
||||
assert_eq!(res.status(), StatusCode::OK);
|
||||
let body = res.into_body().collect().await.unwrap().to_bytes();
|
||||
assert_eq!(body.as_ref(), readme_bytes);
|
||||
|
||||
let svc = ServeFile::new("../README.md");
|
||||
let req = Request::builder()
|
||||
.header(header::IF_UNMODIFIED_SINCE, "Fri, 09 Aug 1996 14:21:40 GMT")
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
|
||||
let res = svc.oneshot(req).await.unwrap();
|
||||
assert_eq!(res.status(), StatusCode::PRECONDITION_FAILED);
|
||||
assert!(res.into_body().frame().await.is_none());
|
||||
}
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
//! [`Service`]s that return responses without wrapping other [`Service`]s.
|
||||
//!
|
||||
//! These kinds of services are also referred to as "leaf services" since they sit at the leaves of
|
||||
//! a [tree] of services.
|
||||
//!
|
||||
//! [`Service`]: https://docs.rs/tower/latest/tower/trait.Service.html
|
||||
//! [tree]: https://en.wikipedia.org/wiki/Tree_(data_structure)
|
||||
|
||||
#[cfg(feature = "redirect")]
|
||||
pub mod redirect;
|
||||
|
||||
#[cfg(feature = "redirect")]
|
||||
#[doc(inline)]
|
||||
pub use self::redirect::Redirect;
|
||||
|
||||
#[cfg(feature = "fs")]
|
||||
pub mod fs;
|
||||
|
||||
#[cfg(feature = "fs")]
|
||||
#[doc(inline)]
|
||||
pub use self::fs::{ServeDir, ServeFile};
|
||||
+159
@@ -0,0 +1,159 @@
|
||||
//! Service that redirects all requests.
|
||||
//!
|
||||
//! # Example
|
||||
//!
|
||||
//! Imagine that we run `example.com` and want to redirect all requests using `HTTP` to `HTTPS`.
|
||||
//! That can be done like so:
|
||||
//!
|
||||
//! ```rust
|
||||
//! use http::{Request, Uri, StatusCode};
|
||||
//! use http_body_util::Full;
|
||||
//! use bytes::Bytes;
|
||||
//! use tower::{Service, ServiceExt};
|
||||
//! use tower_http::services::Redirect;
|
||||
//!
|
||||
//! # #[tokio::main]
|
||||
//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
//! let uri: Uri = "https://example.com/".parse().unwrap();
|
||||
//! let mut service: Redirect<Full<Bytes>> = Redirect::permanent(uri);
|
||||
//!
|
||||
//! let request = Request::builder()
|
||||
//! .uri("http://example.com")
|
||||
//! .body(Full::<Bytes>::default())
|
||||
//! .unwrap();
|
||||
//!
|
||||
//! let response = service.oneshot(request).await?;
|
||||
//!
|
||||
//! assert_eq!(response.status(), StatusCode::PERMANENT_REDIRECT);
|
||||
//! assert_eq!(response.headers()["location"], "https://example.com/");
|
||||
//! #
|
||||
//! # Ok(())
|
||||
//! # }
|
||||
//! ```
|
||||
|
||||
use http::{header, HeaderValue, Response, StatusCode, Uri};
|
||||
use std::{
|
||||
convert::{Infallible, TryFrom},
|
||||
fmt,
|
||||
future::Future,
|
||||
marker::PhantomData,
|
||||
pin::Pin,
|
||||
task::{Context, Poll},
|
||||
};
|
||||
use tower_service::Service;
|
||||
|
||||
/// Service that redirects all requests.
|
||||
///
|
||||
/// See the [module docs](crate::services::redirect) for more details.
|
||||
pub struct Redirect<ResBody> {
|
||||
status_code: StatusCode,
|
||||
location: HeaderValue,
|
||||
// Covariant over ResBody, no dropping of ResBody
|
||||
_marker: PhantomData<fn() -> ResBody>,
|
||||
}
|
||||
|
||||
impl<ResBody> Redirect<ResBody> {
|
||||
/// Create a new [`Redirect`] that uses a [`307 Temporary Redirect`][mdn] status code.
|
||||
///
|
||||
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/307
|
||||
pub fn temporary(uri: Uri) -> Self {
|
||||
Self::with_status_code(StatusCode::TEMPORARY_REDIRECT, uri)
|
||||
}
|
||||
|
||||
/// Create a new [`Redirect`] that uses a [`308 Permanent Redirect`][mdn] status code.
|
||||
///
|
||||
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/308
|
||||
pub fn permanent(uri: Uri) -> Self {
|
||||
Self::with_status_code(StatusCode::PERMANENT_REDIRECT, uri)
|
||||
}
|
||||
|
||||
/// Create a new [`Redirect`] that uses the given status code.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// - If `status_code` isn't a [redirection status code][mdn] (3xx).
|
||||
/// - If `uri` isn't a valid [`HeaderValue`].
|
||||
///
|
||||
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#redirection_messages
|
||||
pub fn with_status_code(status_code: StatusCode, uri: Uri) -> Self {
|
||||
assert!(
|
||||
status_code.is_redirection(),
|
||||
"not a redirection status code"
|
||||
);
|
||||
|
||||
Self {
|
||||
status_code,
|
||||
location: HeaderValue::try_from(uri.to_string())
|
||||
.expect("URI isn't a valid header value"),
|
||||
_marker: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<R, ResBody> Service<R> for Redirect<ResBody>
|
||||
where
|
||||
ResBody: Default,
|
||||
{
|
||||
type Response = Response<ResBody>;
|
||||
type Error = Infallible;
|
||||
type Future = ResponseFuture<ResBody>;
|
||||
|
||||
#[inline]
|
||||
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
|
||||
fn call(&mut self, _req: R) -> Self::Future {
|
||||
ResponseFuture {
|
||||
status_code: self.status_code,
|
||||
location: Some(self.location.clone()),
|
||||
_marker: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<ResBody> fmt::Debug for Redirect<ResBody> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("Redirect")
|
||||
.field("status_code", &self.status_code)
|
||||
.field("location", &self.location)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl<ResBody> Clone for Redirect<ResBody> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
status_code: self.status_code,
|
||||
location: self.location.clone(),
|
||||
_marker: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Response future of [`Redirect`].
|
||||
#[derive(Debug)]
|
||||
pub struct ResponseFuture<ResBody> {
|
||||
location: Option<HeaderValue>,
|
||||
status_code: StatusCode,
|
||||
// Covariant over ResBody, no dropping of ResBody
|
||||
_marker: PhantomData<fn() -> ResBody>,
|
||||
}
|
||||
|
||||
impl<ResBody> Future for ResponseFuture<ResBody>
|
||||
where
|
||||
ResBody: Default,
|
||||
{
|
||||
type Output = Result<Response<ResBody>, Infallible>;
|
||||
|
||||
fn poll(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||
let mut res = Response::default();
|
||||
|
||||
*res.status_mut() = self.status_code;
|
||||
|
||||
res.headers_mut()
|
||||
.insert(header::LOCATION, self.location.take().unwrap());
|
||||
|
||||
Poll::Ready(Ok(res))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user