hreq 0.8.0

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

/// Serve static files.
///
/// * Supports `HEAD` requests.
/// * Directory default "index.html" (on windows "index.htm").
/// * Caching using [`if-modified-since`] and [`must-revalidate`].
/// * Maps file extension to `content-type` using [mime-guess].
/// * Guesses character encoding of `text/*` mime types using [chardetng].
/// * Supports [range requests].
///
/// # Example
///
/// A request for `http://localhost:3000/static/foo.html` would attempt to read a file
/// from disk `/www/static/foo.html`.
///
/// ```no_run
/// use hreq::prelude::*;
/// use hreq::server::Static;
///
/// async fn start_server() {
///    let mut server = Server::new();
///
///    server.at("/static/*file").all(Static::dir("/www/static"));
///
///    let (handle, addr) = server.listen(3000).await.unwrap();
///
///    handle.keep_alive().await;
/// }
/// ```
///
/// [`if-modified-since`]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Conditional_requests
/// [`must-revalidate`]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control
/// [mime-guess]: https://crates.io/crates/mime_guess
/// [chardetng]: https://crates.io/crates/chardetng
/// [range requests]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Range_requests
#[derive(Debug)]
pub struct Static {
    root: PathBuf,
    use_path_param: bool,
    index_file: Option<String>,
}

impl Static {
    /// Creates a handler that serves files from a directory.
    ///
    /// * Must be used with a path parameter `/path/*name`.
    /// * Cannot serve files from parent paths. I.e. `/path/../foo.txt`.
    /// * Path is either absolute, or made absolute by using [`current_dir`] upon creation.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use hreq::prelude::*;
    /// use hreq::server::Static;
    ///
    /// async fn start_server() {
    ///    let mut server = Server::new();
    ///
    ///    server.at("/static/*file").all(Static::dir("/www/static"));
    ///
    ///    let (handle, addr) = server.listen(3000).await.unwrap();
    ///
    ///    handle.keep_alive().await;
    /// }
    /// ```
    ///
    /// [`current_dir`]: https://doc.rust-lang.org/std/env/fn.current_dir.html
    pub fn dir(path: impl AsRef<Path>) -> Self {
        Static::new(path, true)
    }

    /// Creates a handler that serves the same file for every request.
    ///
    /// * Path is either absolute, or made absolute by using [`current_dir`] upon creation.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use hreq::prelude::*;
    /// use hreq::server::Static;
    ///
    /// async fn start_server() {
    ///    let mut server = Server::new();
    ///
    ///    server.at("/*any").all(Static::file("/www/single-page-app.html"));
    ///
    ///    let (handle, addr) = server.listen(3000).await.unwrap();
    ///
    ///    handle.keep_alive().await;
    /// }
    /// ```
    ///
    /// [`current_dir`]: https://doc.rust-lang.org/std/env/fn.current_dir.html
    pub fn file(path: impl AsRef<Path>) -> Self {
        Static::new(path, false)
    }

    /// Send a file as part of a handler.
    ///
    /// Inspired by express js [`res.sendFile`].
    ///
    /// ```no_run
    /// use hreq::prelude::*;
    /// use hreq::server::Static;
    ///
    /// async fn start_server() {
    ///    let mut server = Server::new();
    ///
    ///    server.at("/do/something").get(do_something);
    ///
    ///    let (handle, addr) = server.listen(3000).await.unwrap();
    ///
    ///    handle.keep_alive().await;
    /// }
    ///
    /// async fn do_something(
    ///   req: http::Request<Body>
    /// ) -> Result<http::Response<Body>, hreq::Error> {
    ///   // do stuff with req.
    ///
    ///   Static::send_file(&req, "/www/my-file.txt").await
    /// }
    /// ```
    ///
    /// [`res.sendFile`]: http://expressjs.com/en/api.html#res.sendFile
    pub async fn send_file(
        req: &http::Request<Body>,
        path: impl AsRef<Path>,
    ) -> Result<http::Response<Body>, Error> {
        let st = Static::new("", false);
        st.handle(req, Some(path.as_ref())).await
    }

    fn new(path: impl AsRef<Path>, use_path_param: bool) -> Self {
        let path = path.as_ref();

        let root = if path.is_absolute() {
            path.to_path_buf()
        } else {
            std::env::current_dir().unwrap().join(path)
        };

        let index_file = Some(
            if cfg!(target_os = "windows") {
                "index.htm"
            } else {
                "index.html"
            }
            .to_string(),
        );

        Static {
            root,
            use_path_param,
            index_file,
        }
    }

    /// Change directory index file.
    ///
    /// This defaults to "index.html" and on windows "index.htm".
    ///
    /// Set `None` to turn off index files (and respond with 404 instead).
    pub fn index_file(mut self, file: Option<&str>) -> Self {
        self.index_file = file.map(|v| v.to_string());
        self
    }

    fn resolve_path(&self, path: Option<&Path>) -> io::Result<PathBuf> {
        // Use the segment from the /*name appended to the dir we use.
        // This could be relative such as `"/path/to/serve"` + `"blah/../foo.txt"`
        let mut root = self.root.clone();

        // Canonicalized form of root. This must exist,
        let root_canon = root.canonicalize()?;

        if let Some(path) = path {
            root.push(&path);
        }

        // By canonicalizing we remove any `..`. This errors if the file doesn't exist.
        let absolute = root.canonicalize()?;

        // This is a security check that the resolved doesn't go to a parent dir/file.
        // "/path/to/serve" + "../../../etc/passwd". It works because self.0 is canonicalized.
        if !absolute.starts_with(&root_canon) {
            debug!("Path not under base path: {:?}", path);
            return Err(io::Error::new(io::ErrorKind::NotFound, "Base path"));
        }

        Ok(absolute)
    }

    async fn handle(
        &self,
        req: &Request<Body>,
        path: Option<&Path>,
    ) -> Result<http::Response<Body>, Error> {
        // only accept HEAD or GET, all other we error on.
        if req.method() != http::Method::GET && req.method() != http::Method::HEAD {
            return Ok(err(http::StatusCode::METHOD_NOT_ALLOWED, "Use GET or HEAD"));
        }

        let mut absolute = match self.resolve_path(path) {
            Err(e) => {
                if e.kind() == io::ErrorKind::NotFound {
                    return Ok(err(StatusCode::NOT_FOUND, "Not found"));
                } else {
                    warn!("Failed to canonicalize ({:?}): {:?}", path, e);
                    return Ok(err(StatusCode::BAD_REQUEST, "Bad request"));
                }
            }
            Ok(v) => v,
        };

        if absolute.is_dir() {
            if let Some(index) = &self.index_file {
                absolute.push(index);
            } else {
                return Ok(err(StatusCode::NOT_FOUND, "Not found"));
            }
        }

        let d = Dispatch::new(absolute, req);

        Ok(d.into_response().await?)
    }
}

impl Handler for Static {
    fn call<'a>(&'a self, req: Request<Body>) -> Pin<Box<dyn Future<Output = Reply> + Send + 'a>> {
        if self.use_path_param {
            let params = req.path_params();

            if params.is_empty() || params.len() > 1 {
                let msg = "serve_dir() must be used with none path param. Example: /dir/*file";

                warn!("{}", msg);

                Box::pin(async move { err(StatusCode::INTERNAL_SERVER_ERROR, msg).into() })
            } else {
                let path: PathBuf = params[0].1.to_owned().into();

                Box::pin(async move {
                    let ret = self.handle(&req, Some(&path)).await;
                    ret.into()
                })
            }
        } else {
            Box::pin(async move {
                let ret = self.handle(&req, None).await;
                ret.into()
            })
        }
    }
}

fn err(status: http::StatusCode, msg: &str) -> http::Response<Body> {
    http::Response::builder()
        .status(status)
        .body(msg.into())
        .unwrap()
}
struct Dispatch {
    file: PathBuf,
    if_modified_since: Option<SystemTime>,
    is_head: bool,
    range: Option<(u64, u64)>,
}

impl Dispatch {
    fn new(file: PathBuf, req: &http::Request<Body>) -> Self {
        let if_modified_since = req
            .headers()
            .get_as::<String>("if-modified-since")
            .and_then(|v| parse_http_date(&v).ok());

        let is_head = req.method() == http::Method::HEAD;

        let is_get = req.method() == http::Method::GET;

        // https://tools.ietf.org/html/rfc7233#section-3.1
        // A server MUST ignore a Range header field received with a request method other than GET.
        //
        // Range: bytes=0-1023
        let range = if is_get {
            req.headers()
                .get("range")
                .and_then(|v| v.to_str().ok())
                .filter(|v| v.starts_with("bytes="))
                .map(|v| &v[6..])
                .and_then(|v| {
                    if let Some(i) = v.find('-') {
                        Some((&v[0..i], &v[i + 1..]))
                    } else {
                        None
                    }
                })
                .and_then(|(s, e)| match (s.parse::<u64>(), e.parse::<u64>()) {
                    (Ok(s), Ok(e)) => Some((s, e)),
                    _ => None,
                })
                // incoming range is end inclusive, internal arithmetic is exclusive.
                .map(|(s, e)| (s, e + 1))
        } else {
            None
        };

        Dispatch {
            file,
            if_modified_since,
            is_head,
            range,
        }
    }

    async fn into_response(self) -> Result<http::Response<Body>, Error> {
        match self.into_response_io().await {
            Ok(v) => Ok(v),
            Err(e) => match e.kind() {
                io::ErrorKind::NotFound => Ok(err(StatusCode::NOT_FOUND, "File not found")),
                io::ErrorKind::PermissionDenied => {
                    Ok(err(StatusCode::FORBIDDEN, "File permission denied"))
                }
                _ => Err(e.into()),
            },
        }
    }

    async fn into_response_io(self) -> io::Result<http::Response<Body>> {
        let file = std::fs::File::open(&self.file)?;
        let meta = file.metadata()?;
        let length = meta.len();
        let modified = meta.modified()?;

        if let Some(since) = self.if_modified_since {
            // for files that updated, since will be earlier than modified.
            if let Ok(diff) = modified.duration_since(since) {
                // The web format has a resultion of seconds: Fri, 15 May 2015 15:34:21 GMT
                // So the diff must be less than a second.
                if diff.as_secs_f32() < 1.0 {
                    return Ok(http::Response::builder()
                        // https://tools.ietf.org/html/rfc7232#section-4.1
                        //
                        // The server generating a 304 response MUST generate any of the
                        // following header fields that would have been sent in a 200 (OK)
                        // response to the same request: Cache-Control, Content-Location, Date,
                        // ETag, Expires, and Vary.
                        .status(http::StatusCode::NOT_MODIFIED)
                        .header("cache-control", "must-revalidate")
                        .header("last-modified", fmt_http_date(modified))
                        .body(Body::empty())
                        .unwrap());
                }
            }
        }

        let guess = mime_guess::from_path(&self.file);
        let mut content_type = if let Some(mime) = guess.first() {
            mime.to_string()
        } else {
            "application/octet-stream".to_string()
        };

        let read = AsyncRuntime::file_to_reader(file);
        const PEEK_LEN: usize = 1024;
        let mut peek = Peekable::new(read, PEEK_LEN);

        // For text files, we try to guess the character encoding.
        if content_type.starts_with("text/") {
            // attempt to guess charset
            let max = (PEEK_LEN as u64).min(length);

            let buf = peek.peek(max as usize).await?;

            let mut det = chardetng::EncodingDetector::new();
            det.feed(buf, length < PEEK_LEN as u64);

            let enc = det.guess(None, true);

            content_type.push_str(&format!("; charset={}", enc.name()));
        }

        let res = http::Response::builder()
            .header("cache-control", "must-revalidate")
            .header("accept-ranges", "bytes")
            .header("content-type", content_type)
            .charset_encode(false) // serve text files as is
            .header("last-modified", httpdate::fmt_http_date(modified));

        let (body, res) = self.create_body(length, peek, res).await?;

        Ok(res.body(body).unwrap())
    }

    async fn create_body<Z: AsyncReadSeek + Unpin + Send + Sync + 'static>(
        &self,
        length: u64,
        mut reader: Z,
        mut res: http::response::Builder,
    ) -> io::Result<(Body, http::response::Builder)> {
        let body = if self.is_head {
            res = res.header("content-length", length.to_string());

            Body::empty()
        } else if let Some((start, end)) = self.range {
            if end <= start || start >= length || end > length {
                debug!("Bad range [{}..{}] of {}", start, end, length);

                res = res.status(http::StatusCode::RANGE_NOT_SATISFIABLE);

                Body::empty()
            } else {
                debug!("Serve range [{}..{}] of {}", start, end, length);

                reader.seek(io::SeekFrom::Start(start)).await?;

                let sub = end - start;

                let limit = ContentLengthRead::new(reader, sub);

                res = res.status(http::StatusCode::PARTIAL_CONTENT).header(
                    "content-range",
                    format!("bytes {}-{}/{}", start, end - 1, length),
                );

                Body::from_async_read(limit, Some(sub))
            }
        } else {
            Body::from_async_read(reader, Some(length))
        };

        Ok((body, res))
    }
}