http_file/
lib.rs

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
//! local file serving with http.

#![feature(impl_trait_in_assoc_type)]

pub mod runtime;

mod buf;
mod chunk;
mod date;
mod error;

pub use self::{chunk::ChunkReader, error::ServeError};

use std::{
    io::SeekFrom,
    path::{Component, Path, PathBuf},
};

use http::{
    header::{HeaderValue, ACCEPT_RANGES, CONTENT_LENGTH, CONTENT_RANGE, CONTENT_TYPE, LAST_MODIFIED, RANGE},
    Method, Request, Response, StatusCode,
};
use mime_guess::mime;

use self::{
    buf::buf_write_header,
    runtime::{AsyncFs, ChunkRead, Meta},
};

#[cfg(feature = "tokio")]
#[derive(Clone)]
pub struct ServeDir<FS: AsyncFs = runtime::TokioFs> {
    chunk_size: usize,
    base_path: PathBuf,
    async_fs: FS,
}

#[cfg(not(feature = "tokio"))]
#[derive(Clone)]
pub struct ServeDir<FS: AsyncFs> {
    chunk_size: usize,
    base_path: PathBuf,
    async_fs: FS,
}

#[cfg(feature = "default")]
impl ServeDir<runtime::TokioFs> {
    /// Construct a new ServeDir with given path.
    pub fn new(path: impl Into<PathBuf>) -> Self {
        Self::with_fs(path, runtime::TokioFs)
    }
}

#[cfg(feature = "tokio-uring")]
impl ServeDir<runtime::TokioUringFs> {
    /// Construct a new ServeDir with given path.
    pub fn new_tokio_uring(path: impl Into<PathBuf>) -> Self {
        Self::with_fs(path, runtime::TokioUringFs)
    }
}

impl<FS: AsyncFs> ServeDir<FS> {
    /// construct a new ServeDir with given path and async file system type. The type must impl
    /// [AsyncFs] trait for properly handling file streaming.
    pub fn with_fs(path: impl Into<PathBuf>, async_fs: FS) -> Self {
        Self {
            chunk_size: 4096,
            base_path: path.into(),
            async_fs,
        }
    }

    /// hint for chunk size of async file streaming.
    /// it's a best effort upper bound and should not be trusted to produce exact chunk size as
    /// under/over shoot can happen
    pub fn chunk_size(&mut self, size: usize) -> &mut Self {
        self.chunk_size = size;
        self
    }

    /// try to find a matching file from given input request and generate http response with stream
    /// reader of matched file.
    ///
    /// # Examples
    /// ```rust
    /// # use http_file::ServeDir;
    /// # use http::Request;
    /// async fn serve(req: &Request<()>) {
    ///     let dir = ServeDir::new("sample");
    ///     let res = dir.serve(&req).await;
    /// }
    /// ```
    pub async fn serve<Ext>(&self, req: &Request<Ext>) -> Result<Response<ChunkReader<FS::File>>, ServeError> {
        if !matches!(*req.method(), Method::HEAD | Method::GET) {
            return Err(ServeError::MethodNotAllowed);
        }

        let path = self.path_check(req.uri().path())?;

        // TODO: enable nest dir serving?
        if path.is_dir() {
            return Err(ServeError::InvalidPath);
        }

        let ct = mime_guess::from_path(&path)
            .first_raw()
            .unwrap_or_else(|| mime::APPLICATION_OCTET_STREAM.as_ref());

        let mut file = self.async_fs.open(path).await?;

        let modified = date::mod_date_check(req, &mut file)?;

        let mut res = Response::new(());

        let mut size = file.len();

        if let Some(range) = req
            .headers()
            .get(RANGE)
            .and_then(|h| h.to_str().ok())
            .and_then(|range| http_range_header::parse_range_header(range).ok())
            .map(|range| range.validate(size))
        {
            let (start, end) = range
                .map_err(|_| ServeError::RangeNotSatisfied(size))?
                .pop()
                .expect("http_range_header produced empty range")
                .into_inner();

            file.seek(SeekFrom::Start(start)).await?;

            *res.status_mut() = StatusCode::PARTIAL_CONTENT;
            let val = buf_write_header!(0, "bytes {start}-{end}/{size}");
            res.headers_mut().insert(CONTENT_RANGE, val);

            size = end - start + 1;
        }

        res.headers_mut().insert(CONTENT_TYPE, HeaderValue::from_static(ct));
        res.headers_mut().insert(CONTENT_LENGTH, HeaderValue::from(size));
        res.headers_mut()
            .insert(ACCEPT_RANGES, HeaderValue::from_static("bytes"));

        if let Some(modified) = modified {
            let val = date::date_to_header(modified);
            res.headers_mut().insert(LAST_MODIFIED, val);
        }

        let stream = if matches!(*req.method(), Method::HEAD) {
            ChunkReader::empty()
        } else {
            ChunkReader::reader(file, size, self.chunk_size)
        };

        Ok(res.map(|_| stream))
    }
}

impl<FS: AsyncFs> ServeDir<FS> {
    fn path_check(&self, path: &str) -> Result<PathBuf, ServeError> {
        let path = path.trim_start_matches('/').as_bytes();

        let path_decoded = percent_encoding::percent_decode(path)
            .decode_utf8()
            .map_err(|_| ServeError::InvalidPath)?;
        let path_decoded = Path::new(&*path_decoded);

        let mut path = self.base_path.clone();

        for component in path_decoded.components() {
            match component {
                Component::Normal(comp) => {
                    if Path::new(&comp)
                        .components()
                        .any(|c| !matches!(c, Component::Normal(_)))
                    {
                        return Err(ServeError::InvalidPath);
                    }
                    path.push(comp)
                }
                Component::CurDir => {}
                Component::Prefix(_) | Component::RootDir | Component::ParentDir => {
                    return Err(ServeError::InvalidPath)
                }
            }
        }

        Ok(path)
    }
}

#[cfg(test)]
mod test {
    use core::future::poll_fn;

    use futures_core::stream::Stream;

    use super::*;

    fn assert_send<F: Send>(_: &F) {}

    #[tokio::test]
    async fn tokio_fs_assert_send() {
        let dir = ServeDir::new("sample");
        let req = Request::builder().uri("/test.txt").body(()).unwrap();

        let fut = dir.serve(&req);

        assert_send(&fut);

        let res = fut.await.unwrap();

        assert_send(&res);
    }

    #[tokio::test]
    async fn method() {
        let dir = ServeDir::new("sample");
        let req = Request::builder()
            .method(Method::POST)
            .uri("/test.txt")
            .body(())
            .unwrap();

        let e = dir.serve(&req).await.err().unwrap();
        assert!(matches!(e, ServeError::MethodNotAllowed));
    }

    #[tokio::test]
    async fn head_method_body_check() {
        let dir = ServeDir::new("sample");
        let req = Request::builder()
            .method(Method::HEAD)
            .uri("/test.txt")
            .body(())
            .unwrap();

        let res = dir.serve(&req).await.unwrap();

        assert_eq!(
            res.headers().get(CONTENT_LENGTH).unwrap(),
            HeaderValue::from("hello, world!".len())
        );

        let mut stream = Box::pin(res.into_body());

        assert_eq!(stream.size_hint(), (usize::MAX, Some(0)));

        let body_chunk = poll_fn(|cx| stream.as_mut().poll_next(cx)).await;

        assert!(body_chunk.is_none())
    }

    #[tokio::test]
    async fn invalid_path() {
        let dir = ServeDir::new("sample");
        let req = Request::builder().uri("/../test.txt").body(()).unwrap();
        assert!(matches!(dir.serve(&req).await.err(), Some(ServeError::InvalidPath)));
    }

    #[tokio::test]
    async fn response_headers() {
        let dir = ServeDir::new("sample");
        let req = Request::builder().uri("/test.txt").body(()).unwrap();
        let res = dir.serve(&req).await.unwrap();
        assert_eq!(
            res.headers().get(CONTENT_TYPE).unwrap(),
            HeaderValue::from_static("text/plain")
        );
        assert_eq!(
            res.headers().get(ACCEPT_RANGES).unwrap(),
            HeaderValue::from_static("bytes")
        );
        assert_eq!(
            res.headers().get(CONTENT_LENGTH).unwrap(),
            HeaderValue::from("hello, world!".len())
        );
    }

    #[tokio::test]
    async fn body_size_hint() {
        let dir = ServeDir::new("sample");
        let req = Request::builder().uri("/test.txt").body(()).unwrap();
        let res = dir.serve(&req).await.unwrap();
        let (lower, Some(upper)) = res.body().size_hint() else {
            panic!("ChunkReadStream does not have a size")
        };
        assert_eq!(lower, upper);
        assert_eq!(lower, "hello, world!".len());
    }

    async fn _basic<FS: AsyncFs>(dir: ServeDir<FS>) {
        let req = Request::builder().uri("/test.txt").body(()).unwrap();

        let mut stream = Box::pin(dir.serve(&req).await.unwrap().into_body());

        let (low, high) = stream.size_hint();

        assert_eq!(low, high.unwrap());
        assert_eq!(low, "hello, world!".len());

        let mut res = String::new();

        while let Some(Ok(bytes)) = poll_fn(|cx| stream.as_mut().poll_next(cx)).await {
            res.push_str(std::str::from_utf8(bytes.as_ref()).unwrap());
        }

        assert_eq!(res, "hello, world!");
    }

    #[tokio::test]
    async fn basic() {
        _basic(ServeDir::new("sample")).await;
    }

    #[cfg(all(target_os = "linux", feature = "tokio-uring"))]
    #[test]
    fn basic_tokio_uring() {
        tokio_uring::start(_basic(ServeDir::new_tokio_uring("sample")));
    }

    async fn test_range<FS: AsyncFs>(dir: ServeDir<FS>) {
        let req = Request::builder()
            .uri("/test.txt")
            .header("range", "bytes=2-12")
            .body(())
            .unwrap();
        let res = dir.serve(&req).await.unwrap();
        assert_eq!(res.status(), StatusCode::PARTIAL_CONTENT);
        assert_eq!(
            res.headers().get(CONTENT_TYPE).unwrap(),
            HeaderValue::from_static("text/plain")
        );
        assert_eq!(
            res.headers().get(CONTENT_RANGE).unwrap(),
            HeaderValue::from_static("bytes 2-12/13")
        );
        assert_eq!(
            res.headers().get(CONTENT_LENGTH).unwrap(),
            HeaderValue::from("llo, world!".len())
        );

        let mut stream = Box::pin(res.into_body());

        let mut res = String::new();

        while let Some(Ok(bytes)) = poll_fn(|cx| stream.as_mut().poll_next(cx)).await {
            res.push_str(std::str::from_utf8(bytes.as_ref()).unwrap());
        }

        assert_eq!("llo, world!", res);
    }

    #[tokio::test]
    async fn ranged() {
        test_range(ServeDir::new("sample")).await;
    }

    #[cfg(all(target_os = "linux", feature = "tokio-uring"))]
    #[test]
    fn ranged_tokio_uring() {
        tokio_uring::start(test_range(ServeDir::new_tokio_uring("sample")))
    }
}