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
use std::{
io::{Error as IoError, ErrorKind as IoErrorKind},
ops::BitAnd,
path::PathBuf,
sync::Arc,
time::SystemTime,
};
use http::{header, HeaderValue, Method, Request};
use mime_guess::MimeGuess;
use tokio::fs::File;
use crate::{
util::RequestedPath,
vfs::{FileOpener, FileWithMetadata, TokioFileOpener},
};
#[derive(Debug)]
pub struct ResolvedFile<F = File> {
pub handle: F,
pub size: u64,
pub modified: Option<SystemTime>,
pub content_type: Option<String>,
pub encoding: Option<Encoding>,
}
impl<F> ResolvedFile<F> {
fn new(
file: FileWithMetadata<F>,
content_type: Option<String>,
encoding: Option<Encoding>,
) -> Self {
Self {
handle: file.handle,
size: file.size,
modified: file.modified,
content_type,
encoding,
}
}
}
pub struct Resolver<O = TokioFileOpener> {
pub opener: Arc<O>,
pub allowed_encodings: AcceptEncoding,
}
#[derive(Debug)]
pub enum ResolveResult<F = File> {
MethodNotMatched,
NotFound,
PermissionDenied,
IsDirectory {
redirect_to: String,
},
Found(ResolvedFile<F>),
}
fn map_open_err<F>(err: IoError) -> Result<ResolveResult<F>, IoError> {
match err.kind() {
IoErrorKind::NotFound => Ok(ResolveResult::NotFound),
IoErrorKind::PermissionDenied => Ok(ResolveResult::PermissionDenied),
_ => Err(err),
}
}
impl Resolver<TokioFileOpener> {
pub fn new(root: impl Into<PathBuf>) -> Self {
Self::with_opener(TokioFileOpener::new(root))
}
}
impl<O: FileOpener> Resolver<O> {
pub fn with_opener(opener: O) -> Self {
Self {
opener: Arc::new(opener),
allowed_encodings: AcceptEncoding::none(),
}
}
pub async fn resolve_request<B>(
&self,
req: &Request<B>,
) -> Result<ResolveResult<O::File>, IoError> {
match *req.method() {
Method::HEAD | Method::GET => {}
_ => {
return Ok(ResolveResult::MethodNotMatched);
}
}
let accept_encoding = self.allowed_encodings
& req
.headers()
.get(header::ACCEPT_ENCODING)
.map(AcceptEncoding::from_header_value)
.unwrap_or(AcceptEncoding::none());
self.resolve_path(req.uri().path(), accept_encoding).await
}
pub async fn resolve_path(
&self,
request_path: &str,
accept_encoding: AcceptEncoding,
) -> Result<ResolveResult<O::File>, IoError> {
let RequestedPath {
sanitized: mut path,
is_dir_request,
} = RequestedPath::resolve(request_path);
let file = match self.opener.open(&path).await {
Ok(pair) => pair,
Err(err) => return map_open_err(err),
};
if is_dir_request && !file.is_dir {
return Ok(ResolveResult::NotFound);
}
if !is_dir_request && file.is_dir {
let mut target = String::with_capacity(path.as_os_str().len() + 2);
target.push('/');
for component in path.components() {
target.push_str(&component.as_os_str().to_string_lossy());
target.push('/');
}
return Ok(ResolveResult::IsDirectory {
redirect_to: target,
});
}
if !is_dir_request {
return self.resolve_final(file, path, accept_encoding).await;
}
path.push("index.html");
let file = match self.opener.open(&path).await {
Ok(pair) => pair,
Err(err) => return map_open_err(err),
};
if file.is_dir {
return Ok(ResolveResult::NotFound);
}
self.resolve_final(file, path, accept_encoding).await
}
async fn resolve_final(
&self,
file: FileWithMetadata<O::File>,
path: PathBuf,
accept_encoding: AcceptEncoding,
) -> Result<ResolveResult<O::File>, IoError> {
let mime = MimeGuess::from_path(&path)
.first()
.map(|mime| mime.to_string());
if accept_encoding.br {
let mut br_path = path.clone().into_os_string();
br_path.push(".br");
if let Ok(file) = self.opener.open(br_path.as_ref()).await {
return Ok(ResolveResult::Found(ResolvedFile::new(
file,
mime,
Some(Encoding::Br),
)));
}
}
if accept_encoding.gzip {
let mut gzip_path = path.into_os_string();
gzip_path.push(".gz");
if let Ok(file) = self.opener.open(gzip_path.as_ref()).await {
return Ok(ResolveResult::Found(ResolvedFile::new(
file,
mime,
Some(Encoding::Gzip),
)));
}
}
Ok(ResolveResult::Found(ResolvedFile::new(file, mime, None)))
}
}
impl<O> Clone for Resolver<O> {
fn clone(&self) -> Self {
Self {
opener: self.opener.clone(),
allowed_encodings: self.allowed_encodings,
}
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Encoding {
Gzip,
Br,
}
impl Encoding {
pub fn to_header_value(&self) -> HeaderValue {
HeaderValue::from_static(match self {
Encoding::Gzip => "gzip",
Encoding::Br => "br",
})
}
}
#[derive(Debug, Copy, Clone)]
pub struct AcceptEncoding {
pub gzip: bool,
pub br: bool,
}
impl AcceptEncoding {
pub const fn all() -> Self {
Self {
gzip: true,
br: true,
}
}
pub const fn none() -> Self {
Self {
gzip: false,
br: false,
}
}
pub fn from_header_value(value: &HeaderValue) -> Self {
let mut res = Self::none();
if let Ok(value) = value.to_str() {
for enc in value.split(',') {
match enc.split(';').next().unwrap().trim() {
"gzip" => res.gzip = true,
"br" => res.br = true,
_ => {}
}
}
}
res
}
}
impl BitAnd for AcceptEncoding {
type Output = Self;
fn bitand(self, rhs: Self) -> Self {
Self {
gzip: self.gzip && rhs.gzip,
br: self.br && rhs.br,
}
}
}