]> git.proxmox.com Git - proxmox-backup.git/blame - src/server/rest.rs
reduce compiler warnings
[proxmox-backup.git] / src / server / rest.rs
CommitLineData
f17db0ab
DM
1use crate::api::schema::*;
2use crate::api::router::*;
3use crate::api::config::*;
1571873d 4use super::formatter::*;
16b48b81 5
4dcf43d2 6use std::fmt;
826bb982 7use std::path::{Path, PathBuf};
9bc17e8d 8use std::sync::Arc;
e7ea17de 9use std::collections::HashMap;
9bc17e8d
DM
10
11use failure::*;
f4c514c1 12use serde_json::{json, Value};
e7ea17de 13use url::form_urlencoded;
9bc17e8d 14
9bc17e8d
DM
15use futures::future::{self, Either};
16//use tokio::prelude::*;
17//use tokio::timer::Delay;
18use tokio::fs::File;
19use tokio_codec;
20//use bytes::{BytesMut, BufMut};
21
22//use hyper::body::Payload;
23use hyper::http::request::Parts;
10be1d29 24use hyper::{Body, Request, Response, StatusCode};
9bc17e8d
DM
25use hyper::service::{Service, NewService};
26use hyper::rt::{Future, Stream};
27use hyper::header;
28
f0b10921
DM
29pub struct RestServer {
30 pub api_config: Arc<ApiConfig>,
31}
32
33impl RestServer {
34
35 pub fn new(api_config: ApiConfig) -> Self {
36 Self { api_config: Arc::new(api_config) }
37 }
38}
39
40impl 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
53pub struct ApiService {
54 pub api_config: Arc<ApiConfig>,
55}
56
57
58impl 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)]
86pub struct HttpError {
87 pub code: StatusCode,
88 pub message: String,
89}
90
91impl HttpError {
92 pub fn new(code: StatusCode, message: String) -> Self {
93 HttpError { code, message }
94 }
95}
96
97impl 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
103macro_rules! http_err {
104 ($status:ident, $msg:expr) => {{
105 Error::from(HttpError::new(StatusCode::$status, $msg))
106 }}
107}
108
279ecfdf
DM
109fn 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(&param_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
160fn 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
181fn handle_upload_api_request(
182 info: &'static ApiUploadMethod,
1629d2ad
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
192 for (k, v) in uri_param {
193 param_list.push((k.clone(), v.clone()));
194 }
195
196 let params = match parse_parameter_strings(&param_list, &info.parameters, true) {
197 Ok(v) => v,
198 Err(err) => {
199 return Box::new(future::err(err.into()));
200 }
201 };
202
203 (info.handler)(req_body, params, info)
204}
205
f4c514c1
DM
206fn get_index() -> BoxFut {
207
208 let nodename = "unknown";
209 let username = "";
210 let token = "abc";
211
212 let setup = json!({
213 "Setup": { "auth_cookie_name": "PBSAuthCookie" },
214 "NodeName": nodename,
215 "UserName": username,
216 "CSRFPreventionToken": token
217 });
218
219 let index = format!(r###"
220<!DOCTYPE html>
221<html>
222 <head>
223 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
224 <meta http-equiv="X-UA-Compatible" content="IE=edge">
225 <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
226 <title>Proxmox Backup Server</title>
8adbdb0a 227 <link rel="icon" sizes="128x128" href="/images/logo-128.png" />
f4c514c1 228 <link rel="apple-touch-icon" sizes="128x128" href="/pve2/images/logo-128.png" />
8adbdb0a
DM
229 <link rel="stylesheet" type="text/css" href="/extjs/theme-crisp/resources/theme-crisp-all.css" />
230 <link rel="stylesheet" type="text/css" href="/extjs/crisp/resources/charts-all.css" />
f4c514c1
DM
231 <link rel="stylesheet" type="text/css" href="/fontawesome/css/font-awesome.css" />
232 <script type='text/javascript'> function gettext(buf) {{ return buf; }} </script>
8adbdb0a
DM
233 <script type="text/javascript" src="/extjs/ext-all-debug.js"></script>
234 <script type="text/javascript" src="/extjs/charts-debug.js"></script>
f4c514c1
DM
235 <script type="text/javascript">
236 Proxmox = {};
237 </script>
8adbdb0a
DM
238 <script type="text/javascript" src="/widgettoolkit/proxmoxlib.js"></script>
239 <script type="text/javascript" src="/extjs/locale/locale-en.js"></script>
f4c514c1
DM
240 <script type="text/javascript">
241 Ext.History.fieldid = 'x-history-field';
242 </script>
5c7a1b15 243 <script type="text/javascript" src="/js/proxmox-backup-gui.js"></script>
f4c514c1
DM
244 </head>
245 <body>
246 <!-- Fields required for history management -->
247 <form id="history-form" class="x-hidden">
248 <input type="hidden" id="x-history-field"/>
249 </form>
250 </body>
251</html>
252"###, setup.to_string());
253
254 Box::new(future::ok(Response::new(index.into())))
255}
256
826bb982
DM
257fn extension_to_content_type(filename: &Path) -> (&'static str, bool) {
258
259 if let Some(ext) = filename.extension().and_then(|osstr| osstr.to_str()) {
260 return match ext {
261 "css" => ("text/css", false),
262 "html" => ("text/html", false),
263 "js" => ("application/javascript", false),
264 "json" => ("application/json", false),
265 "map" => ("application/json", false),
266 "png" => ("image/png", true),
267 "ico" => ("image/x-icon", true),
268 "gif" => ("image/gif", true),
269 "svg" => ("image/svg+xml", false),
270 "jar" => ("application/java-archive", true),
271 "woff" => ("application/font-woff", true),
272 "woff2" => ("application/font-woff2", true),
273 "ttf" => ("application/font-snft", true),
274 "pdf" => ("application/pdf", true),
275 "epub" => ("application/epub+zip", true),
276 "mp3" => ("audio/mpeg", true),
277 "oga" => ("audio/ogg", true),
278 "tgz" => ("application/x-compressed-tar", true),
279 _ => ("application/octet-stream", false),
280 };
281 }
282
283 ("application/octet-stream", false)
284}
285
9bc17e8d
DM
286fn simple_static_file_download(filename: PathBuf) -> BoxFut {
287
826bb982
DM
288 let (content_type, _nocomp) = extension_to_content_type(&filename);
289
9bc17e8d 290 Box::new(File::open(filename)
4dcf43d2 291 .map_err(|err| http_err!(BAD_REQUEST, format!("File open failed: {}", err)))
826bb982 292 .and_then(move |file| {
9bc17e8d
DM
293 let buf: Vec<u8> = Vec::new();
294 tokio::io::read_to_end(file, buf)
4dcf43d2 295 .map_err(|err| http_err!(BAD_REQUEST, format!("File read failed: {}", err)))
826bb982
DM
296 .and_then(move |data| {
297 let mut response = Response::new(data.1.into());
298 response.headers_mut().insert(
299 header::CONTENT_TYPE,
300 header::HeaderValue::from_static(content_type));
301 Ok(response)
302 })
9bc17e8d
DM
303 }))
304}
305
306fn chuncked_static_file_download(filename: PathBuf) -> BoxFut {
307
826bb982
DM
308 let (content_type, _nocomp) = extension_to_content_type(&filename);
309
9bc17e8d 310 Box::new(File::open(filename)
4dcf43d2 311 .map_err(|err| http_err!(BAD_REQUEST, format!("File open failed: {}", err)))
826bb982 312 .and_then(move |file| {
9bc17e8d
DM
313 let payload = tokio_codec::FramedRead::new(file, tokio_codec::BytesCodec::new()).
314 map(|bytes| {
315 //sigh - howto avoid copy here? or the whole map() ??
316 hyper::Chunk::from(bytes.to_vec())
317 });
318 let body = Body::wrap_stream(payload);
826bb982
DM
319
320 // fixme: set other headers ?
9bc17e8d
DM
321 Ok(Response::builder()
322 .status(StatusCode::OK)
826bb982 323 .header(header::CONTENT_TYPE, content_type)
9bc17e8d
DM
324 .body(body)
325 .unwrap())
326 }))
327}
328
329fn handle_static_file_download(filename: PathBuf) -> BoxFut {
330
331 let response = tokio::fs::metadata(filename.clone())
4dcf43d2 332 .map_err(|err| http_err!(BAD_REQUEST, format!("File access problems: {}", err)))
9bc17e8d
DM
333 .and_then(|metadata| {
334 if metadata.len() < 1024*32 {
335 Either::A(simple_static_file_download(filename))
336 } else {
337 Either::B(chuncked_static_file_download(filename))
338 }
339 });
340
341 return Box::new(response);
342}
343
344pub fn handle_request(api: Arc<ApiConfig>, req: Request<Body>) -> BoxFut {
345
346 let (parts, body) = req.into_parts();
347
348 let method = parts.method.clone();
349 let path = parts.uri.path();
350
351 // normalize path
352 // do not allow ".", "..", or hidden files ".XXXX"
353 // also remove empty path components
354
355 let items = path.split('/');
356 let mut path = String::new();
357 let mut components = vec![];
358
359 for name in items {
360 if name.is_empty() { continue; }
361 if name.starts_with(".") {
10be1d29 362 return Box::new(future::err(http_err!(BAD_REQUEST, "Path contains illegal components.".to_string())));
9bc17e8d
DM
363 }
364 path.push('/');
365 path.push_str(name);
366 components.push(name);
367 }
368
369 let comp_len = components.len();
370
371 println!("REQUEST {} {}", method, path);
372 println!("COMPO {:?}", components);
373
374 if comp_len >= 1 && components[0] == "api3" {
375 println!("GOT API REQUEST");
376 if comp_len >= 2 {
377 let format = components[1];
1571873d
DM
378 let formatter = match format {
379 "json" => &JSON_FORMATTER,
380 "extjs" => &EXTJS_FORMATTER,
381 _ => {
382 return Box::new(future::err(http_err!(BAD_REQUEST, format!("Unsupported output format '{}'.", format))));
383 }
384 };
9bc17e8d 385
e7ea17de
DM
386 let mut uri_param = HashMap::new();
387
7e21da6e
DM
388 // fixme: handle auth
389 match api.find_method(&components[2..], method, &mut uri_param) {
390 MethodDefinition::None => {}
391 MethodDefinition::Simple(api_method) => {
392 return handle_sync_api_request(api_method, formatter, parts, body, uri_param);
393 }
394 MethodDefinition::Upload(upload_method) => {
395 return handle_upload_api_request(upload_method, formatter, parts, body, uri_param);
396 }
9bc17e8d
DM
397 }
398 }
399 } else {
400 // not Auth for accessing files!
401
f4c514c1
DM
402 if comp_len == 0 {
403 return get_index();
404 } else {
405 let filename = api.find_alias(&components);
406 return handle_static_file_download(filename);
407 }
9bc17e8d
DM
408 }
409
10be1d29 410 Box::new(future::err(http_err!(NOT_FOUND, "Path not found.".to_string())))
9bc17e8d 411}