1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
//! File System Filters

use std::cmp;
use std::io;
use std::fs::Metadata;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use bytes::{BufMut, BytesMut};
use futures::{future, Future, stream, Stream};
use futures::future::Either;
use headers::{AcceptRanges, ContentLength, ContentRange, ContentType, HeaderMapExt, IfModifiedSince, IfRange, IfUnmodifiedSince, LastModified, Range};
use http::StatusCode;
use hyper::{Body, Chunk};
use mime_guess;
use tokio::fs::File as TkFile;
use tokio::io::AsyncRead;
use tokio_threadpool;
use urlencoding::decode;

use ::never::Never;
use ::filter::{Filter, FilterClone, One};
use ::reject::{self, Rejection};
use ::reply::{ReplySealed, Response};

/// Creates a `Filter` that serves a File at the `path`.
///
/// Does not filter out based on any information of the request. Always serves
/// the file at the exact `path` provided. Thus, this can be used to serve a
/// single file with `GET`s, but could also be used in combination with other
/// filters, such as after validating in `POST` request, wanting to return a
/// specific file as the body.
///
/// For serving a directory, see [dir](dir).
///
/// # Example
///
/// ```
/// // Always serves this file from the file system.
/// let route = warp::fs::file("/www/static/app.js");
/// ```
///
/// # Note
///
/// This filter uses `tokio-fs` to serve files, which requires the server
/// to be run in the threadpool runtime. This is only important to remember
/// if starting a runtime manually.
pub fn file(path: impl Into<PathBuf>) -> impl FilterClone<Extract=One<File>, Error=Rejection> {
    let path = Arc::new(path.into());
    ::any()
        .map(move || {
            trace!("file: {:?}", path);
            ArcPath(path.clone())
        })
        .and(conditionals())
        .and_then(file_reply)
}

/// Creates a `Filter` that serves a directory at the base `path` joined
/// by the request path.
///
/// This can be used to serve "static files" from a directory. By far the most
/// common pattern of serving static files is for `GET` requests, so this
/// filter automatically includes a `GET` check.
///
/// # Example
///
/// ```
/// use warp::Filter;
///
/// // Matches requests that start with `/static`,
/// // and then uses the rest of that path to lookup
/// // and serve a file from `/www/static`.
/// let route = warp::path("static")
///     .and(warp::fs::dir("/www/static"));
///
/// // For example:
/// // - `GET /static/app.js` would serve the file `/www/static/app.js`
/// // - `GET /static/css/app.css` would serve the file `/www/static/css/app.css`
/// ```
///
/// # Note
///
/// This filter uses `tokio-fs` to serve files, which requires the server
/// to be run in the threadpool runtime. This is only important to remember
/// if starting a runtime manually.
pub fn dir(path: impl Into<PathBuf>) -> impl FilterClone<Extract=One<File>, Error=Rejection> {
    let base = Arc::new(path.into());
    ::get2()
        .and(path_from_tail(base))
        .and(conditionals())
        .and_then(file_reply)
}

fn path_from_tail(base: Arc<PathBuf>) -> impl FilterClone<Extract=One<ArcPath>, Error=Rejection> {
    ::path::tail()
        .and_then(move |tail: ::path::Tail| {
            let mut buf = PathBuf::from(base.as_ref());
            let p = match decode(tail.as_str()) {
                Ok(p) => p,
                Err(err) => {
                    debug!("dir: failed to decode route={:?}: {:?}", tail.as_str(), err);
                    // FromUrlEncodingError doesn't implement StdError
                    return Err(reject::not_found());
                }
            };
            trace!("dir? base={:?}, route={:?}", base, p);
            for seg in p.split('/') {
                if seg.starts_with("..") {
                    warn!("dir: rejecting segment starting with '..'");
                    return Err(reject::not_found());
                } else {
                    buf.push(seg);
                }
            }
            Ok(buf)
        })
        .and_then(|buf: PathBuf| {
            // Checking Path::is_dir can block since it has to read from disk,
            // so put it in a blocking() future
            let mut buf = Some(buf);
            future::poll_fn(move || {
                let is_dir = try_ready!(tokio_threadpool::blocking(|| {
                    buf.as_ref().unwrap().is_dir()
                }));
                let mut buf = buf.take().unwrap();
                if is_dir {
                    debug!("dir: appending index.html to directory path");
                    buf.push("index.html");
                }

                trace!("dir: {:?}", buf);

                Ok(ArcPath(Arc::new(buf)).into())
            })
                .map_err(|blocking_err: tokio_threadpool::BlockingError| {
                    error!(
                        "threadpool blocking error checking buf.is_dir(): {}",
                        blocking_err,
                    );
                    reject::known(FsNeedsTokioThreadpool)
                })
        })
}


#[derive(Debug)]
struct Conditionals {
    if_modified_since: Option<IfModifiedSince>,
    if_unmodified_since: Option<IfUnmodifiedSince>,
    if_range: Option<IfRange>,
    range: Option<Range>,
}

enum Cond {
    NoBody(Response),
    WithBody(Option<Range>),
}

impl Conditionals {
    fn check(self, last_modified: Option<LastModified>) -> Cond {
        if let Some(since) = self.if_unmodified_since {
            let precondition = last_modified
                .map(|time| since.precondition_passes(time.into()))
                .unwrap_or(false);

            trace!("if-unmodified-since? {:?} vs {:?} = {}", since, last_modified, precondition);
            if !precondition {
                let mut res = Response::new(Body::empty());
                *res.status_mut() = StatusCode::PRECONDITION_FAILED;
                return Cond::NoBody(res);
            }
        }

        if let Some(since) = self.if_modified_since {
            trace!("if-modified-since? header = {:?}, file = {:?}", since, last_modified);
            let unmodified = last_modified
                .map(|time| !since.is_modified(time.into()))
                // no last_modified means its always modified
                .unwrap_or(false);
            if unmodified {
                let mut res = Response::new(Body::empty());
                *res.status_mut() = StatusCode::NOT_MODIFIED;
                return Cond::NoBody(res);
            }
        }

        if let Some(if_range) = self.if_range {
            trace!("if-range? {:?} vs {:?}", if_range, last_modified);
            let can_range = !if_range.is_modified(None, last_modified.as_ref());

            if !can_range {
                return Cond::WithBody(None);
            }
        }

        Cond::WithBody(self.range)
    }
}

fn conditionals() -> impl Filter<Extract=One<Conditionals>, Error=Never> + Copy {
    ::header::optional()
        .and(::header::optional())
        .and(::header::optional())
        .and(::header::optional())
        .map(|if_modified_since, if_unmodified_since, if_range, range| Conditionals {
            if_modified_since,
            if_unmodified_since,
            if_range,
            range,
        })
}

/// A file response.
#[derive(Debug)]
pub struct File {
    resp: Response,
}

// Silly wrapper since Arc<PathBuf> doesn't implement AsRef<Path> ;_;
#[derive(Clone, Debug)]
struct ArcPath(Arc<PathBuf>);

impl AsRef<Path> for ArcPath {
    fn as_ref(&self) -> &Path {
        (*self.0).as_ref()
    }
}

impl ReplySealed for File {
    fn into_response(self) -> Response {
        self.resp
    }
}

fn file_reply(path: ArcPath, conditionals: Conditionals) -> impl Future<Item=File, Error=Rejection> + Send {
    TkFile::open(path.clone())
        .then(move |res| match res {
            Ok(f) => Either::A(file_conditional(f, path, conditionals)),
            Err(err) => {
                let rej = match err.kind() {
                    io::ErrorKind::NotFound => {
                        debug!("file not found: {:?}", path.as_ref().display());
                        reject::not_found()
                    },
                    _ => {
                        error!("file open error (path={:?}): {} ", path.as_ref().display(), err);
                        reject::not_found()
                    },
                };
                Either::B(future::err(rej))
            }
        })
}

fn file_metadata(f: TkFile) -> impl Future<Item=(TkFile, Metadata), Error=Rejection> {
    let mut f = Some(f);
    future::poll_fn(move || {
        let meta = try_ready!(f.as_mut().unwrap().poll_metadata());
        Ok((f.take().unwrap(), meta).into())
    })
        .map_err(|err: ::std::io::Error| {
            debug!("file metadata error: {}", err);
            reject::not_found()
        })
}

fn file_conditional(f: TkFile, path: ArcPath, conditionals: Conditionals) -> impl Future<Item=File, Error=Rejection> + Send {
    file_metadata(f).map(move |(file, meta)| {
        let mut len = meta.len();
        let modified = meta.modified().ok().map(LastModified::from);


        let mut resp = match conditionals.check(modified) {
            Cond::NoBody(resp) => resp,
            Cond::WithBody(range) => {
                bytes_range(range, len)
                    .map(|(start, end)| {
                        let sub_len = end - start;
                        let buf_size = optimal_buf_size(&meta);
                        let stream = file_stream(file, buf_size, (start, end));
                        let body = Body::wrap_stream(stream);

                        let mut resp = Response::new(body);

                        if sub_len != len {
                            *resp.status_mut() = StatusCode::PARTIAL_CONTENT;
                            resp.headers_mut().typed_insert(
                                ContentRange::bytes(start..end, len)
                                    .expect("valid ContentRange")
                            );

                            len = sub_len;
                        }

                        resp
                    })
                    .unwrap_or_else(|BadRange| {
                        // bad byte range
                        let mut resp = Response::new(Body::empty());
                        *resp.status_mut() = StatusCode::RANGE_NOT_SATISFIABLE;
                        resp.headers_mut().typed_insert(
                            ContentRange::unsatisfied_bytes(len)
                        );
                        resp
                    })
            }
        };

        if resp.status() != StatusCode::RANGE_NOT_SATISFIABLE {
            let mime = mime_guess::guess_mime_type(path.as_ref());

            resp.headers_mut().typed_insert(ContentLength(len));
            resp.headers_mut().typed_insert(ContentType::from(mime));
            resp.headers_mut().typed_insert(AcceptRanges::bytes());

            if let Some(last_modified) = modified {
                resp.headers_mut().typed_insert(last_modified);
            }
        }

        File {
            resp,
        }
    })
}

struct BadRange;

fn bytes_range(range: Option<Range>, max_len: u64) -> Result<(u64, u64), BadRange> {
    use std::ops::Bound;

    let range = if let Some(range) = range {
        range
    } else {
        return Ok((0, max_len));
    };

    let ret = range
        .iter()
        .map(|(start, end)| {
            let start = match start {
                Bound::Unbounded => 0,
                Bound::Included(s) => s,
                Bound::Excluded(s) => s + 1,
            };

            let end = match end {
                Bound::Unbounded => max_len,
                Bound::Included(s) => s + 1,
                Bound::Excluded(s) => s,
            };

            if start < end && end <= max_len {
                Ok((start, end))
            } else {
                trace!("unsatisfiable byte range: {}-{}/{}", start, end, max_len);
                Err(BadRange)
            }
        })
        .next()
        .unwrap_or(Ok((0, max_len)));
    ret
}

fn file_stream(file: TkFile, buf_size: usize, (start, end): (u64, u64)) -> impl Stream<Item=Chunk, Error=io::Error> + Send {
    use std::io::SeekFrom;

    // seek
    let seek = if start != 0 {
        trace!("partial content; seeking ({}..{})", start, end);
        Either::A(file
            .seek(SeekFrom::Start(start))
            .map(|(f, _pos)| f))
    } else {
        Either::B(future::ok(file))
    };

    seek
        .into_stream()
        .map(move |mut f| {

            let mut buf = BytesMut::new();
            let mut len = end - start;
            stream::poll_fn(move || {
                if len == 0 {
                    return Ok(None.into());
                }
                if buf.remaining_mut() < buf_size {
                    buf.reserve(buf_size);
                }
                let n = try_ready!(f.read_buf(&mut buf).map_err(|err| {
                    debug!("file read error: {}", err);
                    err
                })) as u64;

                if n == 0 {
                    debug!("file read found EOF before expected length");
                    return Ok(None.into());
                }

                let mut chunk = buf.take().freeze();
                if n > len {
                    chunk = chunk.split_to(len as usize);
                    len = 0;
                } else {
                    len -= n;
                }

                Ok(Some(Chunk::from(chunk)).into())
            })
        })
        .flatten()
}

fn optimal_buf_size(metadata: &Metadata) -> usize {
    let block_size = get_block_size(metadata);

    // If file length is smaller than block size, don't waste space
    // reserving a bigger-than-needed buffer.
    cmp::min(block_size as u64, metadata.len()) as usize
}

#[cfg(unix)]
fn get_block_size(metadata: &Metadata) -> usize {
    use std::os::unix::fs::MetadataExt;
    //TODO: blksize() returns u64, should handle bad cast...
    //(really, a block size bigger than 4gb?)
    metadata.blksize() as usize
}

#[cfg(not(unix))]
fn get_block_size(_metadata: &Metadata) -> usize {
    8_192
}

// ===== Rejections =====

#[derive(Debug)]
pub(crate) struct FsNeedsTokioThreadpool;

impl ::std::fmt::Display for FsNeedsTokioThreadpool {
    fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
        f.write_str("File system operations require tokio threadpool runtime")
    }
}

impl ::std::error::Error for FsNeedsTokioThreadpool {
    fn description(&self) -> &str {
        "File system operations require tokio threadpool runtime"
    }
}