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
use crate::router::{Handler, HandlerObj, ResponseFuture, Router};
use crate::web::response;
use failure::{Backtrace, Context, Fail, ResultExt};
use futures::sync::oneshot;
use futures::Stream;
use hyper::rt::Future;
use hyper::{rt, Body, Request, Server, StatusCode};
use rustls;
use rustls::internal::pemfile;
use std::fmt::{self, Display};
use std::fs::File;
use std::net::SocketAddr;
use std::sync::Arc;
use std::{io, thread};
use tokio_rustls::ServerConfigExt;
use tokio_tcp;
#[derive(Debug)]
pub struct Error {
inner: Context<ErrorKind>,
}
#[derive(Clone, Eq, PartialEq, Debug, Fail)]
pub enum ErrorKind {
#[fail(display = "Internal error: {}", _0)]
Internal(String),
#[fail(display = "Bad arguments: {}", _0)]
Argument(String),
#[fail(display = "Not found.")]
NotFound,
#[fail(display = "Request error: {}", _0)]
RequestError(String),
#[fail(display = "ResponseError error: {}", _0)]
ResponseError(String),
}
impl Fail for Error {
fn cause(&self) -> Option<&dyn Fail> {
self.inner.cause()
}
fn backtrace(&self) -> Option<&Backtrace> {
self.inner.backtrace()
}
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Display::fmt(&self.inner, f)
}
}
impl Error {
pub fn kind(&self) -> &ErrorKind {
self.inner.get_context()
}
}
impl From<ErrorKind> for Error {
fn from(kind: ErrorKind) -> Error {
Error {
inner: Context::new(kind),
}
}
}
impl From<Context<ErrorKind>> for Error {
fn from(inner: Context<ErrorKind>) -> Error {
Error { inner: inner }
}
}
#[derive(Clone)]
pub struct TLSConfig {
pub certificate: String,
pub private_key: String,
}
impl TLSConfig {
pub fn new(certificate: String, private_key: String) -> TLSConfig {
TLSConfig {
certificate,
private_key,
}
}
fn load_certs(&self) -> Result<Vec<rustls::Certificate>, Error> {
let certfile = File::open(&self.certificate).context(ErrorKind::Internal(format!(
"failed to open file {}",
self.certificate
)))?;
let mut reader = io::BufReader::new(certfile);
pemfile::certs(&mut reader)
.map_err(|_| ErrorKind::Internal("failed to load certificate".to_string()).into())
}
fn load_private_key(&self) -> Result<rustls::PrivateKey, Error> {
let keyfile = File::open(&self.private_key).context(ErrorKind::Internal(format!(
"failed to open file {}",
self.private_key
)))?;
let mut reader = io::BufReader::new(keyfile);
let keys = pemfile::pkcs8_private_keys(&mut reader)
.map_err(|_| ErrorKind::Internal("failed to load private key".to_string()))?;
if keys.len() != 1 {
return Err(ErrorKind::Internal(
"expected a single private key".to_string(),
))?;
}
Ok(keys[0].clone())
}
pub fn build_server_config(&self) -> Result<Arc<rustls::ServerConfig>, Error> {
let certs = self.load_certs()?;
let key = self.load_private_key()?;
let mut cfg = rustls::ServerConfig::new(rustls::NoClientAuth::new());
cfg.set_single_cert(certs, key)
.context(ErrorKind::Internal(
"set single certificate failed".to_string(),
))?;
Ok(Arc::new(cfg))
}
}
pub struct ApiServer {
shutdown_sender: Option<oneshot::Sender<()>>,
}
impl ApiServer {
pub fn new() -> ApiServer {
ApiServer {
shutdown_sender: None,
}
}
pub fn start(
&mut self,
addr: SocketAddr,
router: Router,
conf: Option<TLSConfig>,
) -> Result<thread::JoinHandle<()>, Error> {
match conf {
Some(conf) => self.start_tls(addr, router, conf),
None => self.start_no_tls(addr, router),
}
}
fn start_no_tls(
&mut self,
addr: SocketAddr,
router: Router,
) -> Result<thread::JoinHandle<()>, Error> {
if self.shutdown_sender.is_some() {
return Err(ErrorKind::Internal(
"Can't start HTTP API server, it's running already".to_string(),
))?;
}
let (tx, _rx) = oneshot::channel::<()>();
self.shutdown_sender = Some(tx);
thread::Builder::new()
.name("apis".to_string())
.spawn(move || {
let server = Server::bind(&addr)
.serve(router)
.map_err(|e| eprintln!("HTTP API server error: {}", e));
rt::run(server);
})
.map_err(|_| ErrorKind::Internal("failed to spawn API thread".to_string()).into())
}
fn start_tls(
&mut self,
addr: SocketAddr,
router: Router,
conf: TLSConfig,
) -> Result<thread::JoinHandle<()>, Error> {
if self.shutdown_sender.is_some() {
return Err(ErrorKind::Internal(
"Can't start HTTPS API server, it's running already".to_string(),
))?;
}
let tls_conf = conf.build_server_config()?;
thread::Builder::new()
.name("apis".to_string())
.spawn(move || {
let listener = tokio_tcp::TcpListener::bind(&addr).expect("failed to bind");
let tls = listener
.incoming()
.and_then(move |s| tls_conf.accept_async(s))
.then(|r| match r {
Ok(x) => Ok::<_, io::Error>(Some(x)),
Err(e) => {
error!("accept_async failed: {}", e);
Ok(None)
}
})
.filter_map(|x| x);
let server = Server::builder(tls)
.serve(router)
.map_err(|e| eprintln!("HTTP API server error: {}", e));
rt::run(server);
})
.map_err(|_| ErrorKind::Internal("failed to spawn API thread".to_string()).into())
}
pub fn stop(&mut self) -> bool {
if self.shutdown_sender.is_some() {
info!("API server has been stoped");
true
} else {
error!("Can't stop API server, it's not running or doesn't spport stop operation");
false
}
}
}
pub struct LoggingMiddleware {}
impl Handler for LoggingMiddleware {
fn call(
&self,
req: Request<Body>,
mut handlers: Box<dyn Iterator<Item = HandlerObj>>,
) -> ResponseFuture {
debug!("REST call: {} {}", req.method(), req.uri().path());
match handlers.next() {
Some(handler) => handler.call(req, handlers),
None => response(StatusCode::INTERNAL_SERVER_ERROR, "no handler found"),
}
}
}