]>
Commit | Line | Data |
---|---|---|
f17db0ab DM |
1 | use crate::api::schema::*; |
2 | use crate::api::router::*; | |
3 | use crate::api::config::*; | |
1571873d | 4 | use super::formatter::*; |
16b48b81 | 5 | |
4dcf43d2 | 6 | use std::fmt; |
826bb982 | 7 | use std::path::{Path, PathBuf}; |
9bc17e8d | 8 | use std::sync::Arc; |
e7ea17de | 9 | use std::collections::HashMap; |
9bc17e8d DM |
10 | |
11 | use failure::*; | |
f4c514c1 | 12 | use serde_json::{json, Value}; |
e7ea17de | 13 | use url::form_urlencoded; |
9bc17e8d | 14 | |
9bc17e8d DM |
15 | use futures::future::{self, Either}; |
16 | //use tokio::prelude::*; | |
17 | //use tokio::timer::Delay; | |
18 | use tokio::fs::File; | |
19 | use tokio_codec; | |
20 | //use bytes::{BytesMut, BufMut}; | |
21 | ||
22 | //use hyper::body::Payload; | |
23 | use hyper::http::request::Parts; | |
10be1d29 | 24 | use hyper::{Body, Request, Response, StatusCode}; |
9bc17e8d DM |
25 | use hyper::service::{Service, NewService}; |
26 | use hyper::rt::{Future, Stream}; | |
27 | use hyper::header; | |
28 | ||
f0b10921 DM |
29 | pub struct RestServer { |
30 | pub api_config: Arc<ApiConfig>, | |
31 | } | |
32 | ||
33 | impl RestServer { | |
34 | ||
35 | pub fn new(api_config: ApiConfig) -> Self { | |
36 | Self { api_config: Arc::new(api_config) } | |
37 | } | |
38 | } | |
39 | ||
40 | impl NewService for RestServer | |
41 | { | |
42 | type ReqBody = Body; | |
43 | type ResBody = Body; | |
44 | type Error = hyper::Error; | |
45 | type InitError = hyper::Error; | |
46 | type Service = ApiService; | |
47 | type Future = Box<Future<Item = Self::Service, Error = Self::InitError> + Send>; | |
48 | fn new_service(&self) -> Self::Future { | |
49 | Box::new(future::ok(ApiService { api_config: self.api_config.clone() })) | |
50 | } | |
51 | } | |
52 | ||
53 | pub struct ApiService { | |
54 | pub api_config: Arc<ApiConfig>, | |
55 | } | |
56 | ||
57 | ||
58 | impl Service for ApiService { | |
59 | type ReqBody = Body; | |
60 | type ResBody = Body; | |
61 | type Error = hyper::Error; | |
62 | type Future = Box<Future<Item = Response<Body>, Error = Self::Error> + Send>; | |
63 | ||
64 | fn call(&mut self, req: Request<Self::ReqBody>) -> Self::Future { | |
65 | ||
66 | Box::new(handle_request(self.api_config.clone(), req).then(|result| { | |
67 | match result { | |
68 | Ok(res) => Ok::<_, hyper::Error>(res), | |
69 | Err(err) => { | |
1571873d | 70 | if let Some(apierr) = err.downcast_ref::<HttpError>() { |
f0b10921 DM |
71 | let mut resp = Response::new(Body::from(apierr.message.clone())); |
72 | *resp.status_mut() = apierr.code; | |
73 | Ok(resp) | |
74 | } else { | |
75 | let mut resp = Response::new(Body::from(err.to_string())); | |
76 | *resp.status_mut() = StatusCode::BAD_REQUEST; | |
77 | Ok(resp) | |
78 | } | |
79 | } | |
80 | } | |
81 | })) | |
82 | } | |
83 | } | |
84 | ||
4dcf43d2 DM |
85 | #[derive(Debug, Fail)] |
86 | pub struct HttpError { | |
87 | pub code: StatusCode, | |
88 | pub message: String, | |
89 | } | |
90 | ||
91 | impl HttpError { | |
92 | pub fn new(code: StatusCode, message: String) -> Self { | |
93 | HttpError { code, message } | |
94 | } | |
95 | } | |
96 | ||
97 | impl fmt::Display for HttpError { | |
98 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
99 | write!(f, "Error {}: {}", self.code, self.message) | |
100 | } | |
101 | } | |
102 | ||
103 | macro_rules! http_err { | |
104 | ($status:ident, $msg:expr) => {{ | |
105 | Error::from(HttpError::new(StatusCode::$status, $msg)) | |
106 | }} | |
107 | } | |
108 | ||
279ecfdf DM |
109 | fn get_request_parameters_async( |
110 | info: &'static ApiMethod, | |
9bc17e8d DM |
111 | parts: Parts, |
112 | req_body: Body, | |
e7ea17de | 113 | uri_param: HashMap<String, String>, |
279ecfdf | 114 | ) -> Box<Future<Item = Value, Error = failure::Error> + Send> |
9bc17e8d DM |
115 | { |
116 | let resp = req_body | |
4dcf43d2 | 117 | .map_err(|err| http_err!(BAD_REQUEST, format!("Promlems reading request body: {}", err))) |
9bc17e8d DM |
118 | .fold(Vec::new(), |mut acc, chunk| { |
119 | if acc.len() + chunk.len() < 64*1024 { //fimxe: max request body size? | |
120 | acc.extend_from_slice(&*chunk); | |
121 | Ok(acc) | |
122 | } | |
4dcf43d2 | 123 | else { Err(http_err!(BAD_REQUEST, format!("Request body too large"))) } |
9bc17e8d DM |
124 | }) |
125 | .and_then(move |body| { | |
126 | ||
1ed86a0b | 127 | let utf8 = std::str::from_utf8(&body)?; |
9bc17e8d | 128 | |
1ed86a0b | 129 | println!("GOT BODY {:?}", utf8); |
9bc17e8d | 130 | |
e7ea17de | 131 | let mut param_list: Vec<(String, String)> = vec![]; |
9bc17e8d | 132 | |
1ed86a0b WB |
133 | if utf8.len() > 0 { |
134 | for (k, v) in form_urlencoded::parse(utf8.as_bytes()).into_owned() { | |
e7ea17de DM |
135 | param_list.push((k, v)); |
136 | } | |
137 | ||
9bc17e8d DM |
138 | } |
139 | ||
140 | if let Some(query_str) = parts.uri.query() { | |
e7ea17de | 141 | for (k, v) in form_urlencoded::parse(query_str.as_bytes()).into_owned() { |
1571873d | 142 | if k == "_dc" { continue; } // skip extjs "disable cache" parameter |
e7ea17de | 143 | param_list.push((k, v)); |
9bc17e8d DM |
144 | } |
145 | } | |
146 | ||
e7ea17de DM |
147 | for (k, v) in uri_param { |
148 | param_list.push((k.clone(), v.clone())); | |
149 | } | |
150 | ||
151 | let params = parse_parameter_strings(¶m_list, &info.parameters, true)?; | |
152 | ||
9bc17e8d DM |
153 | println!("GOT PARAMS {}", params); |
154 | Ok(params) | |
155 | }); | |
156 | ||
157 | Box::new(resp) | |
158 | } | |
159 | ||
279ecfdf DM |
160 | fn handle_sync_api_request( |
161 | info: &'static ApiMethod, | |
1571873d | 162 | formatter: &'static OutputFormatter, |
9bc17e8d DM |
163 | parts: Parts, |
164 | req_body: Body, | |
e7ea17de | 165 | uri_param: HashMap<String, String>, |
279ecfdf | 166 | ) -> BoxFut |
9bc17e8d | 167 | { |
e7ea17de | 168 | let params = get_request_parameters_async(info, parts, req_body, uri_param); |
9bc17e8d DM |
169 | |
170 | let resp = params | |
171 | .and_then(move |params| { | |
c548fa25 | 172 | let res = (info.handler)(params, info)?; |
9bc17e8d | 173 | Ok(res) |
1571873d | 174 | }).then(move |result| { |
c578fcd9 | 175 | Ok((formatter.format_result)(result)) |
9bc17e8d DM |
176 | }); |
177 | ||
178 | Box::new(resp) | |
179 | } | |
180 | ||
7e21da6e DM |
181 | fn handle_upload_api_request( |
182 | info: &'static ApiUploadMethod, | |
cf16af2a DM |
183 | formatter: &'static OutputFormatter, |
184 | parts: Parts, | |
7e21da6e DM |
185 | req_body: Body, |
186 | uri_param: HashMap<String, String>, | |
187 | ) -> BoxFut | |
188 | { | |
189 | // fixme: convert parameters to Json | |
190 | let mut param_list: Vec<(String, String)> = vec![]; | |
191 | ||
cf16af2a DM |
192 | if let Some(query_str) = parts.uri.query() { |
193 | for (k, v) in form_urlencoded::parse(query_str.as_bytes()).into_owned() { | |
194 | if k == "_dc" { continue; } // skip extjs "disable cache" parameter | |
195 | param_list.push((k, v)); | |
196 | } | |
197 | } | |
198 | ||
7e21da6e DM |
199 | for (k, v) in uri_param { |
200 | param_list.push((k.clone(), v.clone())); | |
201 | } | |
202 | ||
203 | let params = match parse_parameter_strings(¶m_list, &info.parameters, true) { | |
204 | Ok(v) => v, | |
205 | Err(err) => { | |
cf16af2a DM |
206 | let resp = (formatter.format_result)(Err(Error::from(err))); |
207 | return Box::new(future::ok(resp)); | |
7e21da6e DM |
208 | } |
209 | }; | |
210 | ||
211 | (info.handler)(req_body, params, info) | |
212 | } | |
213 | ||
f4c514c1 DM |
214 | fn get_index() -> BoxFut { |
215 | ||
216 | let nodename = "unknown"; | |
217 | let username = ""; | |
218 | let token = "abc"; | |
219 | ||
220 | let setup = json!({ | |
221 | "Setup": { "auth_cookie_name": "PBSAuthCookie" }, | |
222 | "NodeName": nodename, | |
223 | "UserName": username, | |
224 | "CSRFPreventionToken": token | |
225 | }); | |
226 | ||
227 | let index = format!(r###" | |
228 | <!DOCTYPE html> | |
229 | <html> | |
230 | <head> | |
231 | <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> | |
232 | <meta http-equiv="X-UA-Compatible" content="IE=edge"> | |
233 | <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> | |
234 | <title>Proxmox Backup Server</title> | |
8adbdb0a | 235 | <link rel="icon" sizes="128x128" href="/images/logo-128.png" /> |
f4c514c1 | 236 | <link rel="apple-touch-icon" sizes="128x128" href="/pve2/images/logo-128.png" /> |
8adbdb0a DM |
237 | <link rel="stylesheet" type="text/css" href="/extjs/theme-crisp/resources/theme-crisp-all.css" /> |
238 | <link rel="stylesheet" type="text/css" href="/extjs/crisp/resources/charts-all.css" /> | |
f4c514c1 DM |
239 | <link rel="stylesheet" type="text/css" href="/fontawesome/css/font-awesome.css" /> |
240 | <script type='text/javascript'> function gettext(buf) {{ return buf; }} </script> | |
8adbdb0a DM |
241 | <script type="text/javascript" src="/extjs/ext-all-debug.js"></script> |
242 | <script type="text/javascript" src="/extjs/charts-debug.js"></script> | |
f4c514c1 DM |
243 | <script type="text/javascript"> |
244 | Proxmox = {}; | |
245 | </script> | |
8adbdb0a DM |
246 | <script type="text/javascript" src="/widgettoolkit/proxmoxlib.js"></script> |
247 | <script type="text/javascript" src="/extjs/locale/locale-en.js"></script> | |
f4c514c1 DM |
248 | <script type="text/javascript"> |
249 | Ext.History.fieldid = 'x-history-field'; | |
250 | </script> | |
5c7a1b15 | 251 | <script type="text/javascript" src="/js/proxmox-backup-gui.js"></script> |
f4c514c1 DM |
252 | </head> |
253 | <body> | |
254 | <!-- Fields required for history management --> | |
255 | <form id="history-form" class="x-hidden"> | |
256 | <input type="hidden" id="x-history-field"/> | |
257 | </form> | |
258 | </body> | |
259 | </html> | |
260 | "###, setup.to_string()); | |
261 | ||
262 | Box::new(future::ok(Response::new(index.into()))) | |
263 | } | |
264 | ||
826bb982 DM |
265 | fn extension_to_content_type(filename: &Path) -> (&'static str, bool) { |
266 | ||
267 | if let Some(ext) = filename.extension().and_then(|osstr| osstr.to_str()) { | |
268 | return match ext { | |
269 | "css" => ("text/css", false), | |
270 | "html" => ("text/html", false), | |
271 | "js" => ("application/javascript", false), | |
272 | "json" => ("application/json", false), | |
273 | "map" => ("application/json", false), | |
274 | "png" => ("image/png", true), | |
275 | "ico" => ("image/x-icon", true), | |
276 | "gif" => ("image/gif", true), | |
277 | "svg" => ("image/svg+xml", false), | |
278 | "jar" => ("application/java-archive", true), | |
279 | "woff" => ("application/font-woff", true), | |
280 | "woff2" => ("application/font-woff2", true), | |
281 | "ttf" => ("application/font-snft", true), | |
282 | "pdf" => ("application/pdf", true), | |
283 | "epub" => ("application/epub+zip", true), | |
284 | "mp3" => ("audio/mpeg", true), | |
285 | "oga" => ("audio/ogg", true), | |
286 | "tgz" => ("application/x-compressed-tar", true), | |
287 | _ => ("application/octet-stream", false), | |
288 | }; | |
289 | } | |
290 | ||
291 | ("application/octet-stream", false) | |
292 | } | |
293 | ||
9bc17e8d DM |
294 | fn simple_static_file_download(filename: PathBuf) -> BoxFut { |
295 | ||
826bb982 DM |
296 | let (content_type, _nocomp) = extension_to_content_type(&filename); |
297 | ||
9bc17e8d | 298 | Box::new(File::open(filename) |
4dcf43d2 | 299 | .map_err(|err| http_err!(BAD_REQUEST, format!("File open failed: {}", err))) |
826bb982 | 300 | .and_then(move |file| { |
9bc17e8d DM |
301 | let buf: Vec<u8> = Vec::new(); |
302 | tokio::io::read_to_end(file, buf) | |
4dcf43d2 | 303 | .map_err(|err| http_err!(BAD_REQUEST, format!("File read failed: {}", err))) |
826bb982 DM |
304 | .and_then(move |data| { |
305 | let mut response = Response::new(data.1.into()); | |
306 | response.headers_mut().insert( | |
307 | header::CONTENT_TYPE, | |
308 | header::HeaderValue::from_static(content_type)); | |
309 | Ok(response) | |
310 | }) | |
9bc17e8d DM |
311 | })) |
312 | } | |
313 | ||
314 | fn chuncked_static_file_download(filename: PathBuf) -> BoxFut { | |
315 | ||
826bb982 DM |
316 | let (content_type, _nocomp) = extension_to_content_type(&filename); |
317 | ||
9bc17e8d | 318 | Box::new(File::open(filename) |
4dcf43d2 | 319 | .map_err(|err| http_err!(BAD_REQUEST, format!("File open failed: {}", err))) |
826bb982 | 320 | .and_then(move |file| { |
9bc17e8d DM |
321 | let payload = tokio_codec::FramedRead::new(file, tokio_codec::BytesCodec::new()). |
322 | map(|bytes| { | |
323 | //sigh - howto avoid copy here? or the whole map() ?? | |
324 | hyper::Chunk::from(bytes.to_vec()) | |
325 | }); | |
326 | let body = Body::wrap_stream(payload); | |
826bb982 DM |
327 | |
328 | // fixme: set other headers ? | |
9bc17e8d DM |
329 | Ok(Response::builder() |
330 | .status(StatusCode::OK) | |
826bb982 | 331 | .header(header::CONTENT_TYPE, content_type) |
9bc17e8d DM |
332 | .body(body) |
333 | .unwrap()) | |
334 | })) | |
335 | } | |
336 | ||
337 | fn handle_static_file_download(filename: PathBuf) -> BoxFut { | |
338 | ||
339 | let response = tokio::fs::metadata(filename.clone()) | |
4dcf43d2 | 340 | .map_err(|err| http_err!(BAD_REQUEST, format!("File access problems: {}", err))) |
9bc17e8d DM |
341 | .and_then(|metadata| { |
342 | if metadata.len() < 1024*32 { | |
343 | Either::A(simple_static_file_download(filename)) | |
344 | } else { | |
345 | Either::B(chuncked_static_file_download(filename)) | |
346 | } | |
347 | }); | |
348 | ||
349 | return Box::new(response); | |
350 | } | |
351 | ||
352 | pub fn handle_request(api: Arc<ApiConfig>, req: Request<Body>) -> BoxFut { | |
353 | ||
354 | let (parts, body) = req.into_parts(); | |
355 | ||
356 | let method = parts.method.clone(); | |
357 | let path = parts.uri.path(); | |
358 | ||
359 | // normalize path | |
360 | // do not allow ".", "..", or hidden files ".XXXX" | |
361 | // also remove empty path components | |
362 | ||
363 | let items = path.split('/'); | |
364 | let mut path = String::new(); | |
365 | let mut components = vec![]; | |
366 | ||
367 | for name in items { | |
368 | if name.is_empty() { continue; } | |
369 | if name.starts_with(".") { | |
10be1d29 | 370 | return Box::new(future::err(http_err!(BAD_REQUEST, "Path contains illegal components.".to_string()))); |
9bc17e8d DM |
371 | } |
372 | path.push('/'); | |
373 | path.push_str(name); | |
374 | components.push(name); | |
375 | } | |
376 | ||
377 | let comp_len = components.len(); | |
378 | ||
379 | println!("REQUEST {} {}", method, path); | |
380 | println!("COMPO {:?}", components); | |
381 | ||
382 | if comp_len >= 1 && components[0] == "api3" { | |
383 | println!("GOT API REQUEST"); | |
384 | if comp_len >= 2 { | |
385 | let format = components[1]; | |
1571873d DM |
386 | let formatter = match format { |
387 | "json" => &JSON_FORMATTER, | |
388 | "extjs" => &EXTJS_FORMATTER, | |
389 | _ => { | |
390 | return Box::new(future::err(http_err!(BAD_REQUEST, format!("Unsupported output format '{}'.", format)))); | |
391 | } | |
392 | }; | |
9bc17e8d | 393 | |
e7ea17de DM |
394 | let mut uri_param = HashMap::new(); |
395 | ||
7e21da6e DM |
396 | // fixme: handle auth |
397 | match api.find_method(&components[2..], method, &mut uri_param) { | |
398 | MethodDefinition::None => {} | |
399 | MethodDefinition::Simple(api_method) => { | |
400 | return handle_sync_api_request(api_method, formatter, parts, body, uri_param); | |
401 | } | |
402 | MethodDefinition::Upload(upload_method) => { | |
403 | return handle_upload_api_request(upload_method, formatter, parts, body, uri_param); | |
404 | } | |
9bc17e8d DM |
405 | } |
406 | } | |
407 | } else { | |
408 | // not Auth for accessing files! | |
409 | ||
f4c514c1 DM |
410 | if comp_len == 0 { |
411 | return get_index(); | |
412 | } else { | |
413 | let filename = api.find_alias(&components); | |
414 | return handle_static_file_download(filename); | |
415 | } | |
9bc17e8d DM |
416 | } |
417 | ||
10be1d29 | 418 | Box::new(future::err(http_err!(NOT_FOUND, "Path not found.".to_string()))) |
9bc17e8d | 419 | } |