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
use std::path::PathBuf;
use std::fs::{self, File};
use std::io::{Read, ErrorKind as IoErrorKind};
use std::{mem, time};
use futures::{Future, Stream, Sink, Poll, Async, future};
use futures::sync::mpsc::SendError;
use hyper::{Error, Chunk, Method, StatusCode, Body, header};
use hyper::server::{Service, Request, Response};
use tokio;
use requested_path::RequestedPath;
pub type ResponseFuture = Box<Future<Item=Response, Error=Error> + Send + 'static>;
pub struct DefaultUpstream;
impl Service for DefaultUpstream {
type Request = Request;
type Response = Response;
type Error = Error;
type Future = ResponseFuture;
fn call(&self, req: Self::Request) -> Self::Future {
Box::new(future::ok(Response::new().with_status(match req.method() {
&Method::Head | &Method::Get => StatusCode::NotFound,
_ => StatusCode::BadRequest,
})))
}
}
struct FileChunkStream(File);
impl Stream for FileChunkStream {
type Item = Result<Chunk, Error>;
type Error = SendError<Self::Item>;
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
let mut buf: [u8; 16384] = unsafe { mem::uninitialized() };
match self.0.read(&mut buf) {
Ok(0) => Ok(Async::Ready(None)),
Ok(size) => Ok(Async::Ready(Some(Ok(
Chunk::from(buf[0..size].to_owned())
)))),
Err(err) => Ok(Async::Ready(Some(Err(Error::Io(err))))),
}
}
}
#[derive(Clone)]
pub struct Static<U = DefaultUpstream> {
root: PathBuf,
upstream: U,
cache_seconds: u32,
}
impl<U> Static<U> {
pub fn with_upstream<P: Into<PathBuf>>(root: P, upstream: U) -> Self {
Self {
root: root.into(),
upstream: upstream,
cache_seconds: 0,
}
}
pub fn with_cache_headers(mut self, seconds: u32) -> Self {
self.cache_seconds = seconds;
self
}
}
impl Static<DefaultUpstream> {
pub fn new<P: Into<PathBuf>>(root: P) -> Self {
Self::with_upstream(root, DefaultUpstream)
}
}
impl<U> Service for Static<U>
where U: Service<
Request = Request,
Response = Response,
Error = Error,
Future = ResponseFuture
> {
type Request = Request;
type Response = Response;
type Error = Error;
type Future = ResponseFuture;
fn call(&self, req: Request) -> Self::Future {
match req.method() {
&Method::Head | &Method::Get => {},
_ => return self.upstream.call(req),
}
if req.uri().is_absolute() {
return self.upstream.call(req);
}
let requested_path = RequestedPath::new(&self.root, &req);
let metadata = match fs::metadata(&requested_path.path) {
Ok(meta) => meta,
Err(e) => {
return match e.kind() {
IoErrorKind::NotFound => {
self.upstream.call(req)
},
IoErrorKind::PermissionDenied => {
Box::new(future::ok(Response::new().with_status(StatusCode::Forbidden)))
},
_ => {
Box::new(future::err(Error::Io(e)))
},
};
},
};
if requested_path.should_redirect(&metadata, &req) {
let mut target = req.path().to_owned();
target.push('/');
if let Some(query) = req.query() {
target.push('?');
target.push_str(query);
}
return Box::new(future::ok(Response::new()
.with_status(StatusCode::MovedPermanently)
.with_header(header::Location::new(target))
));
}
let (path, metadata) = match requested_path.get_file(metadata) {
None => return self.upstream.call(req),
Some(val) => val,
};
let modified = match metadata.modified() {
Ok(time) => time,
Err(err) => return Box::new(future::err(Error::Io(err))),
};
let http_modified = header::HttpDate::from(modified);
if let Some(&header::IfModifiedSince(ref value)) = req.headers().get() {
if http_modified <= *value {
return Box::new(future::ok(Response::new()
.with_status(StatusCode::NotModified)
));
}
}
let size = metadata.len();
let delta_modified = modified.duration_since(time::UNIX_EPOCH)
.expect("cannot express mtime as duration since epoch");
let etag = format!("{0:x}-{1:x}.{2:x}", size, delta_modified.as_secs(), delta_modified.subsec_nanos());
let mut res = Response::new()
.with_header(header::ContentLength(size))
.with_header(header::LastModified(http_modified))
.with_header(header::ETag(header::EntityTag::weak(etag)));
if self.cache_seconds != 0 {
res.headers_mut().set(header::CacheControl(vec![
header::CacheDirective::Public,
header::CacheDirective::MaxAge(self.cache_seconds)
]));
}
match req.method() {
&Method::Head => {},
&Method::Get => {
let file = match File::open(path) {
Ok(file) => file,
Err(err) => return Box::new(future::err(Error::Io(err))),
};
let (sender, body) = Body::pair();
tokio::spawn(
sender.send_all(FileChunkStream(file))
.map(|_| ())
.map_err(|_| ())
);
res.set_body(body);
},
_ => unreachable!(),
}
Box::new(future::ok(res))
}
}