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
//! File service module
use bytes::Bytes;

use crate::config::{FileServeConfig, FsTaskSpawner};
use crate::headers::cd::{self, ContentDisposition, DispositionType};
use crate::utils;
use crate::headers::range::HttpRange;
use crate::body::Body;

use std::io::{self, Seek, Read};
use std::path::Path;
use std::fs;
use core::{mem, cmp, task};
use core::str::FromStr;
use core::marker::PhantomData;
use core::future::Future;
use core::pin::Pin;

///Result of file read.
pub type FileReadResult = Result<Bytes, io::Error>;

///Performs match of `ETag` against `If-Match`
///
///Returns `true` if has no `If-Match` header or the `Etag` doesn't match it
pub fn if_match(etag: &etag::EntityTag, headers: &http::header::HeaderMap) -> bool {
    match headers.get(http::header::IF_MATCH).and_then(|header| header.to_str().ok()) {
        Some(header) => {
            for header_tag in header.split(',').map(|tag| tag.trim()) {
                match header_tag.parse::<etag::EntityTag>() {
                    Ok(header_tag) => match etag.strong_eq(&header_tag) {
                        true => return true,
                        false => (),
                    },
                    Err(_) => ()
                }
            }
            false
        },
        None => true
    }
}

///Matches given ETag against `If-None-Match` header.
///
///Returns `true` if matching value found is not found or misses the header
pub fn if_none_match(etag: &etag::EntityTag, headers: &http::header::HeaderMap) -> bool {
    match headers.get(http::header::IF_NONE_MATCH).and_then(|header| header.to_str().ok()) {
        Some(header) => {
            for header_tag in header.split(',').map(|tag| tag.trim()) {
                match header_tag.parse::<etag::EntityTag>() {
                    Ok(header_tag) => match etag.weak_eq(&header_tag) {
                        true => return false,
                        false => (),
                    },
                    Err(_) => ()
                }
            }
            true
        },
        None => true
    }
}

///Matches `Last-Modified` against `If-Unmodified-Since`
///
///Returns true if `Last-Modified` is not after `If-Unmodified-Since`
///Or the header is missing
pub fn if_unmodified_since(last_modified: httpdate::HttpDate, headers: &http::header::HeaderMap) -> bool {
    match headers.get(http::header::IF_UNMODIFIED_SINCE).and_then(|header| header.to_str().ok()).and_then(|header| httpdate::HttpDate::from_str(header.trim()).ok()) {
        Some(header) => last_modified <= header,
        None => true,
    }
}

///Matches `Last-Modified` against `If-Modified-Since`
///
///Returns true if `Last-Modified` is before `If-Modified-Since`, header is missing or
///`If-None-Matches` is present
pub fn if_modified_since(last_modified: httpdate::HttpDate, headers: &http::header::HeaderMap) -> bool {
    if headers.contains_key(http::header::IF_NONE_MATCH) {
        return true;
    }

    match headers.get(http::header::IF_MODIFIED_SINCE).and_then(|header| header.to_str().ok()).and_then(|header| httpdate::HttpDate::from_str(header.trim()).ok()) {
        Some(header) => last_modified > header,
        None => true,
    }
}

///File service helper
pub struct ServeFile<W, C> {
    file: fs::File,
    meta: fs::Metadata,
    ///File's MIME type
    pub content_type: mime::Mime,
    ///File's Content-Disposition
    pub content_disposition: ContentDisposition,
    _config: PhantomData<(W, C)>,
}

impl<W: FsTaskSpawner, C: FileServeConfig> ServeFile<W, C> {
    ///Opens file to serve.
    pub fn open(path: &Path) -> io::Result<Self> {
        let file = fs::File::open(path)?;
        let meta = file.metadata()?;

        if let Some(file_name) = path.file_name().and_then(|file_name| file_name.to_str()) {
            Ok(Self::from_parts_with_cfg(file_name, file, meta))
        } else {
            Err(io::Error::new(io::ErrorKind::InvalidInput, "Provided path has no filename"))
        }
    }

    #[inline]
    ///Creates new instance from already opened file
    pub fn from_parts(file_name: &str, file: fs::File, meta: fs::Metadata) -> Self {
        Self::from_parts_with_cfg(file_name, file, meta)
    }

    ///Creates new instance from already opened file
    pub fn from_parts_with_cfg(file_name: &str, file: fs::File, meta: fs::Metadata) -> Self {
        let (content_type, content_disposition) = {
            let content_type = mime_guess::from_path(&file_name).first_or_octet_stream();
            let content_disposition = match C::content_disposition_map(content_type.type_()) {
                DispositionType::Inline => ContentDisposition::Inline,
                DispositionType::Attachment => ContentDisposition::Attachment(cd::Filename::with_encoded_name(file_name.into())),
            };

            (content_type, content_disposition)
        };

        Self {
            file,
            meta,
            content_type,
            content_disposition,
            _config: PhantomData,
        }
    }

    #[inline]
    ///Creates `EntityTag` for file
    pub fn etag(&self) -> etag::EntityTag {
        etag::EntityTag::from_file_meta(&self.meta)
    }

    #[inline]
    ///Creates `HttpDate` instance for file, if possible
    pub fn last_modified(&self) -> Option<httpdate::HttpDate> {
        self.meta.modified().map(|modified| modified.into()).ok()
    }

    #[inline]
    ///Returns length of File.
    pub fn len(&self) -> u64 {
        self.meta.len()
    }

    ///Prepares file for service
    pub fn prepare(self, path: &Path, method: http::Method, headers: &http::HeaderMap, out_headers: &mut http::HeaderMap) -> (http::StatusCode, Body<W, C>) {
        //ETag is more reliable so it is given priority.
        if C::is_use_etag(&path) {
            let etag = self.etag();

            //As per RFC we must send useful cache related headers.
            //Since cache is from ETag let's send ETag only
            out_headers.insert(http::header::ETAG, utils::display_to_header(&etag));

            if !if_match(&etag, headers) {
                return (http::StatusCode::PRECONDITION_FAILED, Body::empty());
            } else if !if_none_match(&etag, headers) {
                return (http::StatusCode::NOT_MODIFIED, Body::empty());
            }
        }

        if C::is_use_last_modifier(&path) {
            if let Some(last_modified) = self.last_modified() {
                out_headers.insert(http::header::LAST_MODIFIED, utils::display_to_header(&last_modified));

                if !if_unmodified_since(last_modified, headers) {
                    return (http::StatusCode::PRECONDITION_FAILED, Body::empty());
                } else if !if_modified_since(last_modified, headers) {
                    return (http::StatusCode::NOT_MODIFIED, Body::empty());
                }
            }
        }

        out_headers.insert(http::header::CONTENT_TYPE, utils::display_to_header(&self.content_type));
        out_headers.insert(http::header::CONTENT_DISPOSITION, utils::display_to_header(&self.content_disposition));
        out_headers.insert(http::header::ACCEPT_RANGES, http::header::HeaderValue::from_static("bytes"));

        let mut length = self.len();
        let mut offset = 0;

        // check for range header
        if let Some(ranges) = headers.get(http::header::RANGE) {
            if let Ok(ranges_header) = ranges.to_str() {
                if let Ok(ranges_vec) = HttpRange::parse(ranges_header, length) {
                    length = ranges_vec[0].length;
                    offset = ranges_vec[0].start;
                    let content_range = utils::display_to_header(&format_args!("bytes {}-{}/{}", offset, offset + length - 1, self.len()));
                    out_headers.insert(http::header::CONTENT_RANGE, content_range);
                } else {
                    let content_range = utils::display_to_header(&format_args!("bytes */{}", length));
                    out_headers.insert(http::header::CONTENT_RANGE, content_range);
                    return (http::StatusCode::RANGE_NOT_SATISFIABLE, Body::empty());
                }
            } else {
                return (http::StatusCode::BAD_REQUEST, Body::empty());
            };
        };

        out_headers.insert(http::header::CONTENT_LENGTH, utils::display_to_header(&length));

        match method {
            http::Method::HEAD => (http::StatusCode::OK, Body::empty()),
            _ => {
                let code = if offset != 0 || length != self.len() {
                    http::StatusCode::PARTIAL_CONTENT
                } else {
                    http::StatusCode::OK
                };

                let reader = ChunkedReadFile::<W, C>::new(length, offset, self.into());
                (code, Body::Chunked(reader))
            },
        }
    }
}

impl<W, C> Into<fs::File> for ServeFile<W, C> {
    fn into(self) -> fs::File {
        self.file
    }
}

#[cold]
#[inline(never)]
fn map_spawn_error<T: Into<Box<dyn std::error::Error + Send + Sync>>>(error: T) -> io::Error {
    io::Error::new(io::ErrorKind::Other, error)
}

///Stream to read chunks of file
pub struct ChunkedReadFile<W: FsTaskSpawner, C> {
    ///Size of file to read
    pub size: u64,
    offset: u64,
    ongoing: Option<W::FileReadFut>,
    file: fs::File,
    counter: u64,
    _config: PhantomData<(W, C)>,
}

impl<W: FsTaskSpawner, C: FileServeConfig> ChunkedReadFile<W, C> {
    ///Creates new instance
    pub fn new(size: u64, offset: u64, file: fs::File) -> Self {
        Self {
            size,
            offset,
            ongoing: None,
            file,
            counter: 0,
            _config: PhantomData
        }
    }

    fn next_read(&mut self) -> W::FileReadFut {
        #[cfg(not(windows))]
        use std::os::fd::{AsRawFd, FromRawFd};
        #[cfg(windows)]
        use std::os::windows::io::{AsRawHandle, FromRawHandle};

        #[cfg(windows)]
        pub struct Handle(std::os::windows::io::RawHandle);
        #[cfg(windows)]
        unsafe impl Send for Handle {}

        #[cfg(not(windows))]
        let fd = self.file.as_raw_fd();
        #[cfg(windows)]
        let fd = Handle(self.file.as_raw_handle());

        let size = self.size;
        let offset = self.offset;
        let counter = self.counter;

        W::spawn_file_read(move || {
            #[cfg(not(windows))]
            let mut file = unsafe {
                fs::File::from_raw_fd(fd)
            };
            #[cfg(windows)]
            let mut file = unsafe {
                fs::File::from_raw_handle(fd.0)
            };

            let max_bytes = cmp::min(size.saturating_sub(counter), C::max_buffer_size());
            let mut buf = Vec::with_capacity(max_bytes as usize);
            let result = match file.seek(io::SeekFrom::Start(offset)) {
                Ok(_) => match file.by_ref().take(max_bytes).read_to_end(&mut buf) {
                    Ok(0) => Err(io::ErrorKind::UnexpectedEof.into()),
                    Ok(_) => Ok(Bytes::from(buf)),
                    Err(error) => Err(error),
                },
                Err(error) => Err(error),
            };
            mem::forget(file);
            result
        })
    }

    ///Fetches next chunk
    pub async fn next(&mut self) -> Result<Option<Bytes>, io::Error> {
        self.await
    }

    #[inline(always)]
    ///Returns `true` if reading is finished
    pub fn is_finished(&self) -> bool {
        self.size == self.counter
    }

    #[inline(always)]
    ///Returns number of bytes left to read.
    pub fn remaining(&self) -> u64 {
        self.size.saturating_sub(self.offset)
    }
}

impl<W: FsTaskSpawner, C: FileServeConfig> Future for ChunkedReadFile<W, C> {
    type Output = Result<Option<Bytes>, io::Error>;

    fn poll(self: Pin<&mut Self>, ctx: &mut task::Context<'_>) -> task::Poll<Self::Output> {
        if self.is_finished() {
            return task::Poll::Ready(Ok(None));
        }
        let this = self.get_mut();

        loop {
            if let Some(ongoing) = this.ongoing.as_mut() {
                break match Future::poll(Pin::new(ongoing), ctx) {
                    task::Poll::Pending => task::Poll::Pending,
                    task::Poll::Ready(result) => {
                        this.ongoing = None;
                        match result {
                            Ok(Ok(bytes)) => task::Poll::Ready(Ok(Some(bytes))),
                            Ok(Err(error)) => task::Poll::Ready(Err(error)),
                            Err(error) => task::Poll::Ready(Err(map_spawn_error(error))),
                        }
                    }
                }
            } else {
                this.ongoing = Some(this.next_read());
            }
        }
    }
}