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
use crate::Response;
use crate::into::IntoResponse;
use tokio::io;
use std::fmt;
use std::path::{Path, PathBuf};
use std::convert::AsRef;
use std::str::Utf8Error;
use percent_encoding::percent_decode_str;
mod file;
pub use file::File;
mod partial_file;
pub use partial_file::{PartialFile, Range};
mod caching;
pub use caching::Caching;
mod static_files;
pub use static_files::{StaticFiles, StaticFile, serve_file};
mod memory_files;
pub use memory_files::{serve_memory_file, MemoryFile};
#[macro_export]
macro_rules! memory_file {
($uri:expr, $path:expr) => (
$crate::fs::MemoryFile::new($uri, $path, include_bytes!($path))
);
($uri:expr, $path:expr, $duration:expr) => (
$crate::fs::MemoryFile::cache_with_age(
$uri,
$path,
include_bytes!($path),
$duration
)
)
}
pub(crate) async fn with_file<P>(path: P) -> io::Result<Response>
where P: AsRef<Path> {
File::open(path).await
.map(|f| f.into_response())
}
pub(crate) async fn with_partial_file<P>(path: P, range: Range) -> io::Result<Response>
where P: AsRef<Path> {
PartialFile::open(path, range).await
.map(|pf| pf.into_response())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IntoPathBufError {
TraversalAttack,
InvalidCharacter,
Utf8(Utf8Error)
}
impl fmt::Display for IntoPathBufError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(self, f)
}
}
impl std::error::Error for IntoPathBufError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Utf8(u) => Some(u),
_ => None
}
}
}
impl From<Utf8Error> for IntoPathBufError {
fn from(e: Utf8Error) -> Self {
Self::Utf8(e)
}
}
pub trait IntoPathBuf {
fn into_path_buf(self) -> Result<PathBuf, IntoPathBufError>;
}
impl IntoPathBuf for &str {
fn into_path_buf(self) -> Result<PathBuf, IntoPathBufError> {
let mut path_buf = PathBuf::new();
for (i, part) in self.split('/').enumerate() {
match (i, part) {
(0, "") => continue,
(_, "..") => { path_buf.pop(); },
(_, ".") => continue,
(_, p) => {
let dec = percent_decode_str(p)
.decode_utf8()?;
if dec.contains('\\') ||
dec.contains('/') ||
dec.starts_with('.') {
return Err(IntoPathBufError::InvalidCharacter)
}
path_buf.push(dec.as_ref());
}
}
}
Ok(path_buf)
}
}