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
use std::io::{BufReader, BufWriter};
use std::marker::PhantomData;
use std::net::{IpAddr, SocketAddr};
use std::os;
use std::path::Path;
use std::thread::{self, JoinGuard};
pub use self::request::Request;
pub use self::response::Response;
pub use net::{Fresh, Streaming};
use HttpError::HttpIoError;
use {HttpResult};
use header::Connection;
use header::ConnectionOption::{Close, KeepAlive};
use net::{NetworkListener, NetworkStream, HttpListener};
use version::HttpVersion::{Http10, Http11};
use self::listener::ListenerPool;
pub mod request;
pub mod response;
mod listener;
pub struct Server<'a, H: Handler, L = HttpListener> {
handler: H,
ssl: Option<(&'a Path, &'a Path)>,
_marker: PhantomData<L>
}
macro_rules! try_option(
($e:expr) => {{
match $e {
Some(v) => v,
None => return None
}
}}
);
impl<'a, H: Handler, L: NetworkListener> Server<'a, H, L> {
pub fn new(handler: H) -> Server<'a, H, L> {
Server {
handler: handler,
ssl: None,
_marker: PhantomData
}
}
}
impl<'a, H: Handler + 'static> Server<'a, H, HttpListener> {
pub fn http(handler: H) -> Server<'a, H, HttpListener> {
Server::new(handler)
}
pub fn https(handler: H, cert: &'a Path, key: &'a Path) -> Server<'a, H, HttpListener> {
Server {
handler: handler,
ssl: Some((cert, key)),
_marker: PhantomData
}
}
}
impl<'a, H: Handler + 'static> Server<'a, H, HttpListener> {
pub fn listen_threads(self, ip: IpAddr, port: u16, threads: usize) -> HttpResult<Listening> {
let addr = &(ip, port);
let listener = try!(match self.ssl {
Some((cert, key)) => HttpListener::https(addr, cert, key),
None => HttpListener::http(addr)
});
self.with_listener(listener, threads)
}
pub fn listen(self, ip: IpAddr, port: u16) -> HttpResult<Listening> {
self.listen_threads(ip, port, os::num_cpus() * 5 / 4)
}
}
impl<
'a,
H: Handler + 'static,
L: NetworkListener<Stream=S> + Send + 'static,
S: NetworkStream + Clone + Send> Server<'a, H, L> {
pub fn with_listener(self, mut listener: L, threads: usize) -> HttpResult<Listening> {
let socket = try!(listener.socket_addr());
let handler = self.handler;
debug!("threads = {:?}", threads);
let pool = ListenerPool::new(listener.clone());
let work = move |stream| handle_connection(stream, &handler);
let guard = thread::scoped(move || pool.accept(work, threads));
Ok(Listening {
_guard: guard,
socket: socket,
})
}
}
fn handle_connection<S, H>(mut stream: S, handler: &H)
where S: NetworkStream + Clone, H: Handler {
debug!("Incoming stream");
let addr = match stream.peer_addr() {
Ok(addr) => addr,
Err(e) => {
error!("Peer Name error: {:?}", e);
return;
}
};
let mut rdr = BufReader::new(stream.clone());
let mut wrt = BufWriter::new(stream);
let mut keep_alive = true;
while keep_alive {
let mut res = Response::new(&mut wrt);
let req = match Request::new(&mut rdr, addr) {
Ok(req) => req,
Err(e@HttpIoError(_)) => {
debug!("ioerror in keepalive loop = {:?}", e);
return;
}
Err(e) => {
error!("request error = {:?}", e);
return;
}
};
keep_alive = match (req.version, req.headers.get::<Connection>()) {
(Http10, Some(conn)) if !conn.contains(&KeepAlive) => false,
(Http11, Some(conn)) if conn.contains(&Close) => false,
_ => true
};
res.version = req.version;
handler.handle(req, res);
debug!("keep_alive = {:?}", keep_alive);
}
}
pub struct Listening {
_guard: JoinGuard<'static, ()>,
pub socket: SocketAddr,
}
impl Listening {
pub fn close(&mut self) -> HttpResult<()> {
debug!("closing server");
Ok(())
}
}
pub trait Handler: Sync + Send {
fn handle<'a>(&'a self, Request<'a>, Response<'a, Fresh>);
}
impl<F> Handler for F where F: Fn(Request, Response<Fresh>), F: Sync + Send {
fn handle(&self, req: Request, res: Response<Fresh>) {
(*self)(req, res)
}
}