tower_http/services/fs/serve_dir/
future.rs1use super::{
2 open_file::{FileOpened, FileRequestExtent, OpenFileOutput},
3 DefaultServeDirFallback, ResponseBody,
4};
5use crate::{
6 body::UnsyncBoxBody, content_encoding::Encoding, services::fs::AsyncReadBody, BoxError,
7};
8use bytes::Bytes;
9use futures_util::future::{BoxFuture, FutureExt, TryFutureExt};
10use http::{
11 header::{self, ALLOW},
12 HeaderValue, Request, Response, StatusCode,
13};
14use http_body_util::{BodyExt, Empty, Full};
15use pin_project_lite::pin_project;
16use std::{
17 convert::Infallible,
18 future::Future,
19 io,
20 pin::Pin,
21 task::{ready, Context, Poll},
22};
23use tower_service::Service;
24
25pin_project! {
26 pub struct ResponseFuture<ReqBody, F = DefaultServeDirFallback> {
28 #[pin]
29 pub(super) inner: ResponseFutureInner<ReqBody, F>,
30 }
31}
32
33impl<ReqBody, F> ResponseFuture<ReqBody, F> {
34 pub(super) fn open_file_future(
35 future: BoxFuture<'static, io::Result<OpenFileOutput>>,
36 fallback_and_request: Option<(F, Request<ReqBody>)>,
37 ) -> Self {
38 Self {
39 inner: ResponseFutureInner::OpenFileFuture {
40 future,
41 fallback_and_request,
42 },
43 }
44 }
45
46 pub(super) fn invalid_path(fallback_and_request: Option<(F, Request<ReqBody>)>) -> Self {
47 Self {
48 inner: ResponseFutureInner::InvalidPath {
49 fallback_and_request,
50 },
51 }
52 }
53
54 pub(super) fn method_not_allowed() -> Self {
55 Self {
56 inner: ResponseFutureInner::MethodNotAllowed,
57 }
58 }
59}
60
61pin_project! {
62 #[project = ResponseFutureInnerProj]
63 pub(super) enum ResponseFutureInner<ReqBody, F> {
64 OpenFileFuture {
65 #[pin]
66 future: BoxFuture<'static, io::Result<OpenFileOutput>>,
67 fallback_and_request: Option<(F, Request<ReqBody>)>,
68 },
69 FallbackFuture {
70 future: BoxFuture<'static, Result<Response<ResponseBody>, Infallible>>,
71 },
72 InvalidPath {
73 fallback_and_request: Option<(F, Request<ReqBody>)>,
74 },
75 MethodNotAllowed,
76 }
77}
78
79impl<F, ReqBody, ResBody> Future for ResponseFuture<ReqBody, F>
80where
81 F: Service<Request<ReqBody>, Response = Response<ResBody>, Error = Infallible> + Clone,
82 F::Future: Send + 'static,
83 ResBody: http_body::Body<Data = Bytes> + Send + 'static,
84 ResBody::Error: Into<Box<dyn std::error::Error + Send + Sync>>,
85{
86 type Output = io::Result<Response<ResponseBody>>;
87
88 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
89 loop {
90 let mut this = self.as_mut().project();
91
92 let new_state = match this.inner.as_mut().project() {
93 ResponseFutureInnerProj::OpenFileFuture {
94 future: open_file_future,
95 fallback_and_request,
96 } => match ready!(open_file_future.poll(cx)) {
97 Ok(OpenFileOutput::FileOpened(file_output)) => {
98 break Poll::Ready(Ok(build_response(*file_output)));
99 }
100
101 Ok(OpenFileOutput::Redirect { location }) => {
102 let mut res = response_with_status(StatusCode::TEMPORARY_REDIRECT);
103 res.headers_mut().insert(http::header::LOCATION, location);
104 break Poll::Ready(Ok(res));
105 }
106
107 Ok(OpenFileOutput::FileNotFound) => {
108 if let Some((mut fallback, request)) = fallback_and_request.take() {
109 call_fallback(&mut fallback, request)
110 } else {
111 break Poll::Ready(Ok(not_found()));
112 }
113 }
114
115 Ok(OpenFileOutput::PreconditionFailed) => {
116 break Poll::Ready(Ok(response_with_status(
117 StatusCode::PRECONDITION_FAILED,
118 )));
119 }
120
121 Ok(OpenFileOutput::NotModified) => {
122 break Poll::Ready(Ok(response_with_status(StatusCode::NOT_MODIFIED)));
123 }
124
125 Err(err) => {
126 #[cfg(unix)]
127 let error_is_not_a_directory = err.raw_os_error() == Some(20);
132 #[cfg(not(unix))]
133 let error_is_not_a_directory = false;
134
135 if matches!(
136 err.kind(),
137 io::ErrorKind::NotFound | io::ErrorKind::PermissionDenied
138 ) || error_is_not_a_directory
139 {
140 if let Some((mut fallback, request)) = fallback_and_request.take() {
141 call_fallback(&mut fallback, request)
142 } else {
143 break Poll::Ready(Ok(not_found()));
144 }
145 } else {
146 break Poll::Ready(Err(err));
147 }
148 }
149 },
150
151 ResponseFutureInnerProj::FallbackFuture { future } => {
152 break Pin::new(future).poll(cx).map_err(|err| match err {})
153 }
154
155 ResponseFutureInnerProj::InvalidPath {
156 fallback_and_request,
157 } => {
158 if let Some((mut fallback, request)) = fallback_and_request.take() {
159 call_fallback(&mut fallback, request)
160 } else {
161 break Poll::Ready(Ok(not_found()));
162 }
163 }
164
165 ResponseFutureInnerProj::MethodNotAllowed => {
166 let mut res = response_with_status(StatusCode::METHOD_NOT_ALLOWED);
167 res.headers_mut()
168 .insert(ALLOW, HeaderValue::from_static("GET,HEAD"));
169 break Poll::Ready(Ok(res));
170 }
171 };
172
173 this.inner.set(new_state);
174 }
175 }
176}
177
178fn response_with_status(status: StatusCode) -> Response<ResponseBody> {
179 Response::builder()
180 .status(status)
181 .body(empty_body())
182 .unwrap()
183}
184
185fn not_found() -> Response<ResponseBody> {
186 response_with_status(StatusCode::NOT_FOUND)
187}
188
189pub(super) fn call_fallback<F, B, FResBody>(
190 fallback: &mut F,
191 req: Request<B>,
192) -> ResponseFutureInner<B, F>
193where
194 F: Service<Request<B>, Response = Response<FResBody>, Error = Infallible> + Clone,
195 F::Future: Send + 'static,
196 FResBody: http_body::Body<Data = Bytes> + Send + 'static,
197 FResBody::Error: Into<BoxError>,
198{
199 let future = fallback
200 .call(req)
201 .map_ok(|response| {
202 response
203 .map(|body| {
204 UnsyncBoxBody::new(
205 body.map_err(|err| match err.into().downcast::<io::Error>() {
206 Ok(err) => *err,
207 Err(err) => io::Error::new(io::ErrorKind::Other, err),
208 })
209 .boxed_unsync(),
210 )
211 })
212 .map(ResponseBody::new)
213 })
214 .boxed();
215
216 ResponseFutureInner::FallbackFuture { future }
217}
218
219fn build_response(output: FileOpened) -> Response<ResponseBody> {
220 let (maybe_file, size) = match output.extent {
221 FileRequestExtent::Full(file, meta) => (Some(file), meta.len()),
222 FileRequestExtent::Head(meta) => (None, meta.len()),
223 };
224
225 let mut builder = Response::builder()
226 .header(header::CONTENT_TYPE, output.mime_header_value)
227 .header(header::ACCEPT_RANGES, "bytes");
228
229 if let Some(encoding) = output
230 .maybe_encoding
231 .filter(|encoding| *encoding != Encoding::Identity)
232 {
233 builder = builder.header(header::CONTENT_ENCODING, encoding.into_header_value());
234 }
235
236 if let Some(last_modified) = output.last_modified {
237 builder = builder.header(header::LAST_MODIFIED, last_modified.0.to_string());
238 }
239
240 match output.maybe_range {
241 Some(Ok(ranges)) => {
242 if let Some(range) = ranges.first() {
243 if ranges.len() > 1 {
244 builder
245 .header(header::CONTENT_RANGE, format!("bytes */{}", size))
246 .status(StatusCode::RANGE_NOT_SATISFIABLE)
247 .body(body_from_bytes(Bytes::from(
248 "Cannot serve multipart range requests",
249 )))
250 .unwrap()
251 } else {
252 let body = if let Some(file) = maybe_file {
253 let range_size = range.end() - range.start() + 1;
254 ResponseBody::new(UnsyncBoxBody::new(
255 AsyncReadBody::with_capacity_limited(
256 file,
257 output.chunk_size,
258 range_size,
259 )
260 .boxed_unsync(),
261 ))
262 } else {
263 empty_body()
264 };
265
266 builder
267 .header(
268 header::CONTENT_RANGE,
269 format!("bytes {}-{}/{}", range.start(), range.end(), size),
270 )
271 .header(header::CONTENT_LENGTH, range.end() - range.start() + 1)
272 .status(StatusCode::PARTIAL_CONTENT)
273 .body(body)
274 .unwrap()
275 }
276 } else {
277 builder
278 .header(header::CONTENT_RANGE, format!("bytes */{}", size))
279 .status(StatusCode::RANGE_NOT_SATISFIABLE)
280 .body(body_from_bytes(Bytes::from(
281 "No range found after parsing range header, please file an issue",
282 )))
283 .unwrap()
284 }
285 }
286
287 Some(Err(_)) => builder
288 .header(header::CONTENT_RANGE, format!("bytes */{}", size))
289 .status(StatusCode::RANGE_NOT_SATISFIABLE)
290 .body(empty_body())
291 .unwrap(),
292
293 None => {
295 let body = if let Some(file) = maybe_file {
296 ResponseBody::new(UnsyncBoxBody::new(
297 AsyncReadBody::with_capacity(file, output.chunk_size).boxed_unsync(),
298 ))
299 } else {
300 empty_body()
301 };
302
303 builder
304 .header(header::CONTENT_LENGTH, size.to_string())
305 .body(body)
306 .unwrap()
307 }
308 }
309}
310
311fn body_from_bytes(bytes: Bytes) -> ResponseBody {
312 let body = Full::from(bytes).map_err(|err| match err {}).boxed_unsync();
313 ResponseBody::new(UnsyncBoxBody::new(body))
314}
315
316fn empty_body() -> ResponseBody {
317 let body = Empty::new().map_err(|err| match err {}).boxed_unsync();
318 ResponseBody::new(UnsyncBoxBody::new(body))
319}