proxmox-backup/src/main.rs

367 lines
11 KiB
Rust
Raw Normal View History

extern crate apitest;
2018-10-30 09:04:30 +00:00
2018-11-05 14:20:27 +00:00
use failure::*;
use std::collections::HashMap;
2018-11-12 13:11:04 +00:00
//use std::io;
2018-11-13 11:36:56 +00:00
//use std::fs;
use std::path::{PathBuf};
2018-11-01 12:05:45 +00:00
2018-11-09 12:48:57 +00:00
//use std::collections::HashMap;
2018-11-03 09:42:48 +00:00
use lazy_static::lazy_static;
2018-11-01 10:30:49 +00:00
2018-11-03 09:42:48 +00:00
//use apitest::json_schema::*;
2018-10-31 09:42:14 +00:00
use apitest::api_info::*;
2018-11-05 14:20:27 +00:00
use apitest::json_schema::*;
2018-10-31 09:42:14 +00:00
2018-11-03 09:42:48 +00:00
//use serde_derive::{Serialize, Deserialize};
2018-11-10 11:06:39 +00:00
use serde_json::{json, Value};
2018-11-13 11:36:56 +00:00
use futures::future::{self, Either};
//use tokio::prelude::*;
//use tokio::timer::Delay;
use tokio::fs::File;
use tokio_codec;
//use bytes::{BytesMut, BufMut};
2018-10-30 13:06:37 +00:00
2018-11-09 12:48:57 +00:00
//use hyper::body::Payload;
2018-11-09 07:22:54 +00:00
use hyper::http::request::Parts;
2018-11-01 10:30:49 +00:00
use hyper::{Method, Body, Request, Response, Server, StatusCode};
2018-11-09 07:22:54 +00:00
use hyper::rt::{Future, Stream};
use hyper::service::service_fn;
2018-11-11 11:55:30 +00:00
use hyper::header;
2018-11-09 07:22:54 +00:00
//use std::time::{Duration, Instant};
2018-11-09 07:22:54 +00:00
2018-11-10 09:00:48 +00:00
type BoxFut = Box<Future<Item = Response<Body>, Error = failure::Error> + Send>;
2018-10-30 09:04:30 +00:00
2018-11-10 09:00:48 +00:00
macro_rules! error_response {
2018-11-01 10:30:49 +00:00
($status:ident, $msg:expr) => {{
let mut resp = Response::new(Body::from($msg));
*resp.status_mut() = StatusCode::$status;
2018-11-10 09:00:48 +00:00
resp
2018-11-09 07:22:54 +00:00
}}
}
2018-11-10 09:00:48 +00:00
2018-11-09 07:22:54 +00:00
macro_rules! http_error_future {
($status:ident, $msg:expr) => {{
2018-11-10 09:00:48 +00:00
let resp = error_response!($status, $msg);
2018-11-13 11:36:56 +00:00
return Box::new(future::ok(resp));
2018-11-01 10:30:49 +00:00
}}
}
2018-11-10 11:06:39 +00:00
fn get_request_parameters_async<'a>(
2018-11-09 12:48:57 +00:00
info: &'a ApiMethod,
parts: Parts,
req_body: Body,
2018-11-10 11:06:39 +00:00
) -> Box<Future<Item = Value, Error = failure::Error> + Send + 'a>
2018-11-09 07:22:54 +00:00
{
2018-11-11 12:24:14 +00:00
let resp = req_body
2018-11-13 11:36:56 +00:00
.map_err(|err| Error::from(ApiError::new(StatusCode::BAD_REQUEST, format!("Promlems reading request body: {}", err))))
2018-11-11 12:24:14 +00:00
.fold(Vec::new(), |mut acc, chunk| {
if acc.len() + chunk.len() < 64*1024 { //fimxe: max request body size?
acc.extend_from_slice(&*chunk);
2018-11-14 10:38:26 +00:00
Ok(acc)
2018-11-11 12:24:14 +00:00
}
2018-11-14 10:38:26 +00:00
else { Err(Error::from(ApiError::new(StatusCode::BAD_REQUEST, format!("Request body too large")))) }
2018-11-11 12:24:14 +00:00
})
2018-11-10 09:00:48 +00:00
.and_then(move |body| {
2018-11-09 07:22:54 +00:00
2018-11-10 09:00:48 +00:00
let bytes = String::from_utf8(body.to_vec())?; // why copy??
2018-11-09 07:22:54 +00:00
2018-11-10 09:00:48 +00:00
println!("GOT BODY {:?}", bytes);
2018-11-09 07:22:54 +00:00
2018-11-10 09:00:48 +00:00
let mut test_required = true;
2018-11-09 07:22:54 +00:00
2018-11-10 09:00:48 +00:00
let mut params = json!({});
2018-11-09 12:48:57 +00:00
2018-11-10 09:00:48 +00:00
if bytes.len() > 0 {
params = parse_query_string(&bytes, &info.parameters, true)?;
test_required = false;
}
2018-11-09 12:48:57 +00:00
2018-11-10 09:00:48 +00:00
if let Some(query_str) = parts.uri.query() {
let query_params = parse_query_string(query_str, &info.parameters, test_required)?;
2018-11-09 12:48:57 +00:00
2018-11-10 09:00:48 +00:00
for (k, v) in query_params.as_object().unwrap() {
params[k] = v.clone(); // fixme: why clone()??
}
2018-11-09 07:22:54 +00:00
}
2018-11-10 11:06:39 +00:00
println!("GOT PARAMS {}", params);
Ok(params)
});
Box::new(resp)
}
fn handle_async_api_request<'a>(
info: &'a ApiMethod,
parts: Parts,
req_body: Body,
) -> Box<Future<Item = Response<Body>, Error = failure::Error> + Send + 'a>
{
let params = get_request_parameters_async(info, parts, req_body);
let resp = params
.and_then(move |params| {
println!("GOT PARAMS {}", params);
/*
let when = Instant::now() + Duration::from_millis(3000);
let task = Delay::new(when).then(|_| {
println!("A LAZY TASK");
ok(())
});
tokio::spawn(task);
*/
(info.async_handler)(params, info)
});
Box::new(resp)
}
fn handle_sync_api_request<'a>(
info: &'a ApiMethod,
parts: Parts,
req_body: Body,
) -> Box<Future<Item = Response<Body>, Error = failure::Error> + Send + 'a>
{
let params = get_request_parameters_async(info, parts, req_body);
let resp = params
.and_then(move |params| {
2018-11-10 09:00:48 +00:00
println!("GOT PARAMS {}", params);
2018-11-10 11:06:39 +00:00
/*
let when = Instant::now() + Duration::from_millis(3000);
let task = Delay::new(when).then(|_| {
println!("A LAZY TASK");
ok(())
});
tokio::spawn(task);
*/
2018-11-10 09:00:48 +00:00
let res = (info.handler)(params, info)?;
2018-11-09 12:48:57 +00:00
2018-11-10 09:00:48 +00:00
Ok(res)
2018-11-09 12:48:57 +00:00
2018-11-10 11:06:39 +00:00
}).then(|result| {
match result {
Ok(ref value) => {
let json_str = value.to_string();
2018-11-09 12:48:57 +00:00
2018-11-10 11:06:39 +00:00
Ok(Response::builder()
.status(StatusCode::OK)
2018-11-11 11:55:30 +00:00
.header(header::CONTENT_TYPE, "application/json")
2018-11-10 11:06:39 +00:00
.body(Body::from(json_str))?)
}
Err(err) => Ok(error_response!(BAD_REQUEST, err.to_string()))
2018-11-10 09:00:48 +00:00
}
2018-11-10 11:06:39 +00:00
});
2018-11-09 07:22:54 +00:00
Box::new(resp)
}
2018-11-11 16:19:24 +00:00
fn simple_static_file_download(filename: PathBuf) -> BoxFut {
Box::new(File::open(filename)
2018-11-13 11:36:56 +00:00
.map_err(|err| Error::from(ApiError::new(StatusCode::BAD_REQUEST, format!("File open failed: {}", err))))
2018-11-11 16:19:24 +00:00
.and_then(|file| {
let buf: Vec<u8> = Vec::new();
tokio::io::read_to_end(file, buf)
2018-11-13 11:36:56 +00:00
.map_err(|err| Error::from(ApiError::new(StatusCode::BAD_REQUEST, format!("File read failed: {}", err))))
2018-11-11 16:19:24 +00:00
.and_then(|data| Ok(Response::new(data.1.into())))
}))
}
fn chuncked_static_file_download(filename: PathBuf) -> BoxFut {
Box::new(File::open(filename)
2018-11-13 11:36:56 +00:00
.map_err(|err| Error::from(ApiError::new(StatusCode::BAD_REQUEST, format!("File open failed: {}", err))))
2018-11-11 16:19:24 +00:00
.and_then(|file| {
let payload = tokio_codec::FramedRead::new(file, tokio_codec::BytesCodec::new()).
map(|bytes| {
//sigh - howto avoid copy here? or the whole map() ??
hyper::Chunk::from(bytes.to_vec())
});
let body = Body::wrap_stream(payload);
// fixme: set content type and other headers
Ok(Response::builder()
.status(StatusCode::OK)
.body(body)
.unwrap())
}))
}
fn handle_static_file_download(filename: PathBuf) -> BoxFut {
let response = tokio::fs::metadata(filename.clone())
2018-11-13 11:36:56 +00:00
.map_err(|err| Error::from(ApiError::new(StatusCode::BAD_REQUEST, format!("File access problems: {}", err))))
.and_then(|metadata| {
2018-11-11 16:19:24 +00:00
if metadata.len() < 1024*32 {
Either::A(simple_static_file_download(filename))
} else {
2018-11-11 16:19:24 +00:00
Either::B(chuncked_static_file_download(filename))
}
});
return Box::new(response);
}
fn handle_request(api: &ApiServer, req: Request<Body>) -> BoxFut {
2018-11-09 07:22:54 +00:00
let (parts, body) = req.into_parts();
2018-11-01 10:30:49 +00:00
2018-11-09 07:22:54 +00:00
let method = parts.method.clone();
let path = parts.uri.path();
2018-10-31 09:42:14 +00:00
// normalize path
2018-11-12 12:19:53 +00:00
// do not allow ".", "..", or hidden files ".XXXX"
// also remove empty path components
let items = path.split('/');
let mut path = String::new();
let mut components = vec![];
for name in items {
if name.is_empty() { continue; }
if name.starts_with(".") {
http_error_future!(BAD_REQUEST, "Path contains illegal components.\n");
}
path.push('/');
path.push_str(name);
components.push(name);
}
2018-11-01 10:30:49 +00:00
let comp_len = components.len();
2018-10-31 09:42:14 +00:00
println!("REQUEST {} {}", method, path);
2018-11-01 10:30:49 +00:00
println!("COMPO {:?}", components);
if comp_len >= 1 && components[0] == "api3" {
println!("GOT API REQUEST");
if comp_len >= 2 {
let format = components[1];
if format != "json" {
2018-11-10 09:32:25 +00:00
http_error_future!(BAD_REQUEST, format!("Unsupported output format '{}'.", format))
2018-11-01 10:30:49 +00:00
}
if let Some(info) = api.router.find_method(&components[2..]) {
2018-11-01 10:30:49 +00:00
println!("FOUND INFO");
let api_method_opt = match method {
2018-11-09 07:22:54 +00:00
Method::GET => &info.get,
Method::PUT => &info.put,
Method::POST => &info.post,
Method::DELETE => &info.delete,
2018-11-03 14:10:21 +00:00
_ => &None,
2018-11-01 10:30:49 +00:00
};
2018-11-01 14:41:08 +00:00
let api_method = match api_method_opt {
2018-11-01 10:30:49 +00:00
Some(m) => m,
2018-11-10 09:32:25 +00:00
_ => http_error_future!(NOT_FOUND, format!("No such method '{}'.", method)),
2018-11-01 10:30:49 +00:00
};
2018-11-07 12:58:09 +00:00
// fixme: handle auth
2018-11-01 10:30:49 +00:00
2018-11-10 11:06:39 +00:00
//return handle_sync_api_request(api_method, parts, body);
return handle_async_api_request(api_method, parts, body);
2018-11-01 10:30:49 +00:00
}
}
2018-11-12 13:11:04 +00:00
} else {
// not Auth for accessing files!
let mut prefix = String::new();
let mut filename = PathBuf::from("/var/www"); // fixme
if comp_len >= 1 {
prefix.push_str(components[0]);
if let Some(subdir) = api.aliases.get(&prefix) {
2018-11-12 13:11:04 +00:00
filename.push(subdir);
for i in 1..comp_len { filename.push(components[i]) }
}
}
return handle_static_file_download(filename);
2018-11-01 10:30:49 +00:00
}
2018-10-31 09:42:14 +00:00
http_error_future!(NOT_FOUND, "Path not found.")
//Box::new(ok(Response::new(Body::from("RETURN WEB GUI\n"))))
2018-10-31 09:42:14 +00:00
}
// add default dirs which includes jquery and bootstrap
// my $base = '/usr/share/libpve-http-server-perl';
// add_dirs($self->{dirs}, '/css/' => "$base/css/");
// add_dirs($self->{dirs}, '/js/' => "$base/js/");
// add_dirs($self->{dirs}, '/fonts/' => "$base/fonts/");
2018-11-12 13:11:04 +00:00
fn initialize_directory_aliases() -> HashMap<String, PathBuf> {
2018-11-12 13:11:04 +00:00
let mut basedirs: HashMap<String, PathBuf> = HashMap::new();
2018-11-12 13:11:04 +00:00
let mut add_directory_alias = |name, path| {
basedirs.insert(String::from(name), PathBuf::from(path));
};
2018-11-12 13:11:04 +00:00
add_directory_alias("novnc", "/usr/share/novnc-pve");
add_directory_alias("extjs", "/usr/share/javascript/extjs");
add_directory_alias("fontawesome", "/usr/share/fonts-font-awesome");
add_directory_alias("xtermjs", "/usr/share/pve-xtermjs");
add_directory_alias("widgettoolkit", "/usr/share/javascript/proxmox-widget-toolkit");
2018-11-12 13:11:04 +00:00
basedirs
}
2018-11-13 11:36:56 +00:00
struct ApiServer {
basedir: PathBuf,
router: &'static MethodInfo,
aliases: &'static HashMap<String, PathBuf>,
2018-11-03 09:42:48 +00:00
}
2018-10-30 09:04:30 +00:00
fn main() {
println!("Fast Static Type Definitions 1");
2018-10-31 09:42:14 +00:00
let addr = ([127, 0, 0, 1], 8007).into();
let new_svc = || {
service_fn(|req| {
lazy_static!{
static ref ALIASES: HashMap<String, PathBuf> = initialize_directory_aliases();
static ref ROUTER: MethodInfo = apitest::api3::router();
}
let api_server = ApiServer {
basedir: "/var/www". into(),
router: &ROUTER,
aliases: &ALIASES,
};
handle_request(&api_server, req).then(|result| {
match result {
Ok(res) => Ok::<_,String>(res),
Err(err) => {
if let Some(apierr) = err.downcast_ref::<ApiError>() {
let mut resp = Response::new(Body::from(apierr.message.clone()));
*resp.status_mut() = apierr.code;
Ok(resp)
} else {
Ok(error_response!(BAD_REQUEST, err.to_string()))
}
}
}
})
})
2018-10-31 09:42:14 +00:00
};
let server = Server::bind(&addr)
.serve(new_svc)
.map_err(|e| eprintln!("server error: {}", e));
// Run this server for... forever!
hyper::rt::run(server);
2018-10-30 09:04:30 +00:00
}