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