2 use crate::api
::schema
::*;
3 use crate::api
::router
::*;
4 use crate::api
::config
::*;
5 use crate::auth_helpers
::*;
6 use super::environment
::RestEnvironment
;
7 use super::formatter
::*;
9 use std
::path
::{Path, PathBuf}
;
11 use std
::collections
::HashMap
;
14 use serde_json
::{json, Value}
;
15 use url
::form_urlencoded
;
17 use futures
::future
::{self, Either}
;
18 //use tokio::prelude::*;
19 //use tokio::timer::Delay;
21 //use bytes::{BytesMut, BufMut};
23 //use hyper::body::Payload;
24 use hyper
::http
::request
::Parts
;
25 use hyper
::{Body, Request, Response, StatusCode}
;
26 use hyper
::service
::{Service, NewService}
;
27 use hyper
::rt
::{Future, Stream}
;
30 extern "C" { fn tzset(); }
32 pub struct RestServer
{
33 pub api_config
: Arc
<ApiConfig
>,
38 pub fn new(api_config
: ApiConfig
) -> Self {
39 Self { api_config: Arc::new(api_config) }
43 impl NewService
for RestServer
47 type Error
= hyper
::Error
;
48 type InitError
= hyper
::Error
;
49 type Service
= ApiService
;
50 type Future
= Box
<Future
<Item
= Self::Service
, Error
= Self::InitError
> + Send
>;
51 fn new_service(&self) -> Self::Future
{
52 Box
::new(future
::ok(ApiService { api_config: self.api_config.clone() }
))
56 pub struct ApiService
{
57 pub api_config
: Arc
<ApiConfig
>,
61 fn log_response(path
: &str, resp
: &Response
<Body
>) {
63 if resp
.headers().contains_key("PBS_PROXIED") { return; }
65 let status
= resp
.status();
67 if !status
.is_success() {
68 let reason
= status
.canonical_reason().unwrap_or("unknown reason");
69 let client
= "unknown"; // fixme: howto get peer_addr ?
70 let message
= "request failed";
72 log
::error
!("{}: {} {}: [client {}] {}", path
, status
.as_str(), reason
, client
, message
);
77 impl Service
for ApiService
{
80 type Error
= hyper
::Error
;
81 type Future
= Box
<Future
<Item
= Response
<Body
>, Error
= Self::Error
> + Send
>;
83 fn call(&mut self, req
: Request
<Self::ReqBody
>) -> Self::Future
{
84 let path
= req
.uri().path().to_owned();
85 Box
::new(handle_request(self.api_config
.clone(), req
).then(move |result
| {
88 Self::log_response(&path
, &res
);
89 Ok
::<_
, hyper
::Error
>(res
)
92 if let Some(apierr
) = err
.downcast_ref
::<HttpError
>() {
93 let mut resp
= Response
::new(Body
::from(apierr
.message
.clone()));
94 *resp
.status_mut() = apierr
.code
;
95 Self::log_response(&path
, &resp
);
98 let mut resp
= Response
::new(Body
::from(err
.to_string()));
99 *resp
.status_mut() = StatusCode
::BAD_REQUEST
;
100 Self::log_response(&path
, &resp
);
109 fn get_request_parameters_async(
110 info
: &'
static ApiMethod
,
113 uri_param
: HashMap
<String
, String
>,
114 ) -> Box
<Future
<Item
= Value
, Error
= failure
::Error
> + Send
>
117 .map_err(|err
| http_err
!(BAD_REQUEST
, format
!("Promlems reading request body: {}", err
)))
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
);
123 else { Err(http_err!(BAD_REQUEST, format!("Request body too large"))) }
125 .and_then(move |body
| {
127 let utf8
= std
::str::from_utf8(&body
)?
;
129 let mut param_list
: Vec
<(String
, String
)> = vec
![];
132 for (k
, v
) in form_urlencoded
::parse(utf8
.as_bytes()).into_owned() {
133 param_list
.push((k
, v
));
138 if let Some(query_str
) = parts
.uri
.query() {
139 for (k
, v
) in form_urlencoded
::parse(query_str
.as_bytes()).into_owned() {
140 if k
== "_dc" { continue; }
// skip extjs "disable cache" parameter
141 param_list
.push((k
, v
));
145 for (k
, v
) in uri_param
{
146 param_list
.push((k
.clone(), v
.clone()));
149 let params
= parse_parameter_strings(¶m_list
, &info
.parameters
, true)?
;
157 fn proxy_protected_request(
158 info
: &'
static ApiMethod
,
164 let mut uri_parts
= parts
.uri
.clone().into_parts();
166 uri_parts
.scheme
= Some(http
::uri
::Scheme
::HTTP
);
167 uri_parts
.authority
= Some(http
::uri
::Authority
::from_static("127.0.0.1:82"));
168 let new_uri
= http
::Uri
::from_parts(uri_parts
).unwrap();
172 let request
= Request
::from_parts(parts
, req_body
);
174 let resp
= hyper
::client
::Client
::new()
176 .map_err(|e
| Error
::from(e
))
178 resp
.headers_mut().insert("PBS_PROXIED", header
::HeaderValue
::from_static("1"));
182 let resp
= if info
.reload_timezone
{
183 Either
::A(resp
.then(|resp
| {unsafe { tzset() }
; resp
}))
188 return Box
::new(resp
);
191 fn handle_sync_api_request(
192 mut rpcenv
: RestEnvironment
,
193 info
: &'
static ApiMethod
,
194 formatter
: &'
static OutputFormatter
,
197 uri_param
: HashMap
<String
, String
>,
200 let params
= get_request_parameters_async(info
, parts
, req_body
, uri_param
);
202 let delay_unauth_time
= std
::time
::Instant
::now() + std
::time
::Duration
::from_millis(3000);
205 .and_then(move |params
| {
206 let mut delay
= false;
207 let resp
= match (info
.handler
)(params
, info
, &mut rpcenv
) {
208 Ok(data
) => (formatter
.format_result
)(data
, &rpcenv
),
210 if let Some(httperr
) = err
.downcast_ref
::<HttpError
>() {
211 if httperr
.code
== StatusCode
::UNAUTHORIZED { delay = true; }
213 (formatter
.format_error
)(err
)
217 if info
.reload_timezone
{
222 let delayed_response
= tokio
::timer
::Delay
::new(delay_unauth_time
)
223 .map_err(|err
| http_err
!(INTERNAL_SERVER_ERROR
, format
!("tokio timer delay error: {}", err
)))
224 .and_then(|_
| Ok(resp
));
226 Either
::A(delayed_response
)
228 Either
::B(future
::ok(resp
))
235 fn handle_async_api_request(
236 mut rpcenv
: RestEnvironment
,
237 info
: &'
static ApiAsyncMethod
,
238 formatter
: &'
static OutputFormatter
,
241 uri_param
: HashMap
<String
, String
>,
244 // fixme: convert parameters to Json
245 let mut param_list
: Vec
<(String
, String
)> = vec
![];
247 if let Some(query_str
) = parts
.uri
.query() {
248 for (k
, v
) in form_urlencoded
::parse(query_str
.as_bytes()).into_owned() {
249 if k
== "_dc" { continue; }
// skip extjs "disable cache" parameter
250 param_list
.push((k
, v
));
254 for (k
, v
) in uri_param
{
255 param_list
.push((k
.clone(), v
.clone()));
258 let params
= match parse_parameter_strings(¶m_list
, &info
.parameters
, true) {
261 let resp
= (formatter
.format_error
)(Error
::from(err
));
262 return Box
::new(future
::ok(resp
));
266 match (info
.handler
)(parts
, req_body
, params
, info
, &mut rpcenv
) {
267 Ok(future
) => future
,
269 let resp
= (formatter
.format_error
)(Error
::from(err
));
270 Box
::new(future
::ok(resp
))
275 fn get_index() -> BoxFut
{
277 let nodename
= tools
::nodename();
278 let username
= ""; // fixme: implement real auth
282 "Setup": { "auth_cookie_name": "PBSAuthCookie" }
,
283 "NodeName": nodename
,
284 "UserName": username
,
285 "CSRFPreventionToken": token
,
288 let index
= format
!(r
###"
292 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
293 <meta http-equiv="X-UA-Compatible" content="IE=edge">
294 <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
295 <title>Proxmox Backup Server</title>
296 <link rel="icon" sizes="128x128" href="/images/logo-128.png" />
297 <link rel="apple-touch-icon" sizes="128x128" href="/pve2/images/logo-128.png" />
298 <link rel="stylesheet" type="text/css" href="/extjs/theme-crisp/resources/theme-crisp-all.css" />
299 <link rel="stylesheet" type="text/css" href="/extjs/crisp/resources/charts-all.css" />
300 <link rel="stylesheet" type="text/css" href="/fontawesome/css/font-awesome.css" />
301 <script type='text/javascript'> function gettext(buf) {{ return buf; }} </script>
302 <script type="text/javascript" src="/extjs/ext-all-debug.js"></script>
303 <script type="text/javascript" src="/extjs/charts-debug.js"></script>
304 <script type="text/javascript">
307 <script type="text/javascript" src="/widgettoolkit/proxmoxlib.js"></script>
308 <script type="text/javascript" src="/extjs/locale/locale-en.js"></script>
309 <script type="text/javascript">
310 Ext.History.fieldid = 'x-history-field';
312 <script type="text/javascript" src="/js/proxmox-backup-gui.js"></script>
315 <!-- Fields required for history management -->
316 <form id="history-form" class="x-hidden">
317 <input type="hidden" id="x-history-field"/>
321 "###, setup.to_string());
323 let resp
= Response
::builder()
324 .status(StatusCode
::OK
)
325 .header(header
::CONTENT_TYPE
, "text/html")
329 Box
::new(future
::ok(resp
))
332 fn extension_to_content_type(filename
: &Path
) -> (&'
static str, bool
) {
334 if let Some(ext
) = filename
.extension().and_then(|osstr
| osstr
.to_str()) {
336 "css" => ("text/css", false),
337 "html" => ("text/html", false),
338 "js" => ("application/javascript", false),
339 "json" => ("application/json", false),
340 "map" => ("application/json", false),
341 "png" => ("image/png", true),
342 "ico" => ("image/x-icon", true),
343 "gif" => ("image/gif", true),
344 "svg" => ("image/svg+xml", false),
345 "jar" => ("application/java-archive", true),
346 "woff" => ("application/font-woff", true),
347 "woff2" => ("application/font-woff2", true),
348 "ttf" => ("application/font-snft", true),
349 "pdf" => ("application/pdf", true),
350 "epub" => ("application/epub+zip", true),
351 "mp3" => ("audio/mpeg", true),
352 "oga" => ("audio/ogg", true),
353 "tgz" => ("application/x-compressed-tar", true),
354 _
=> ("application/octet-stream", false),
358 ("application/octet-stream", false)
361 fn simple_static_file_download(filename
: PathBuf
) -> BoxFut
{
363 let (content_type
, _nocomp
) = extension_to_content_type(&filename
);
365 Box
::new(File
::open(filename
)
366 .map_err(|err
| http_err
!(BAD_REQUEST
, format
!("File open failed: {}", err
)))
367 .and_then(move |file
| {
368 let buf
: Vec
<u8> = Vec
::new();
369 tokio
::io
::read_to_end(file
, buf
)
370 .map_err(|err
| http_err
!(BAD_REQUEST
, format
!("File read failed: {}", err
)))
371 .and_then(move |data
| {
372 let mut response
= Response
::new(data
.1.into
());
373 response
.headers_mut().insert(
374 header
::CONTENT_TYPE
,
375 header
::HeaderValue
::from_static(content_type
));
381 fn chuncked_static_file_download(filename
: PathBuf
) -> BoxFut
{
383 let (content_type
, _nocomp
) = extension_to_content_type(&filename
);
385 Box
::new(File
::open(filename
)
386 .map_err(|err
| http_err
!(BAD_REQUEST
, format
!("File open failed: {}", err
)))
387 .and_then(move |file
| {
388 let payload
= tokio
::codec
::FramedRead
::new(file
, tokio
::codec
::BytesCodec
::new()).
390 //sigh - howto avoid copy here? or the whole map() ??
391 hyper
::Chunk
::from(bytes
.to_vec())
393 let body
= Body
::wrap_stream(payload
);
395 // fixme: set other headers ?
396 Ok(Response
::builder()
397 .status(StatusCode
::OK
)
398 .header(header
::CONTENT_TYPE
, content_type
)
404 fn handle_static_file_download(filename
: PathBuf
) -> BoxFut
{
406 let response
= tokio
::fs
::metadata(filename
.clone())
407 .map_err(|err
| http_err
!(BAD_REQUEST
, format
!("File access problems: {}", err
)))
408 .and_then(|metadata
| {
409 if metadata
.len() < 1024*32 {
410 Either
::A(simple_static_file_download(filename
))
412 Either
::B(chuncked_static_file_download(filename
))
416 return Box
::new(response
);
419 pub fn handle_request(api
: Arc
<ApiConfig
>, req
: Request
<Body
>) -> BoxFut
{
421 let (parts
, body
) = req
.into_parts();
423 let method
= parts
.method
.clone();
424 let path
= parts
.uri
.path();
427 // do not allow ".", "..", or hidden files ".XXXX"
428 // also remove empty path components
430 let items
= path
.split('
/'
);
431 let mut path
= String
::new();
432 let mut components
= vec
![];
435 if name
.is_empty() { continue; }
436 if name
.starts_with(".") {
437 return Box
::new(future
::err(http_err
!(BAD_REQUEST
, "Path contains illegal components.".to_string())));
441 components
.push(name
);
444 let comp_len
= components
.len();
446 println
!("REQUEST {} {}", method
, path
);
447 println
!("COMPO {:?}", components
);
449 let env_type
= api
.env_type();
450 let mut rpcenv
= RestEnvironment
::new(env_type
);
452 let delay_unauth_time
= std
::time
::Instant
::now() + std
::time
::Duration
::from_millis(3000);
454 if let Some(raw_cookie
) = parts
.headers
.get("COOKIE") {
455 if let Ok(cookie
) = raw_cookie
.to_str() {
456 if let Some(ticket
) = tools
::extract_auth_cookie(cookie
, "PBSAuthCookie") {
457 if let Ok((_
, Some(username
))) = tools
::ticket
::verify_rsa_ticket(
458 public_auth_key(), "PBS", &ticket
, None
, -300, 3600*2) {
459 rpcenv
.set_user(Some(username
));
466 if comp_len
>= 1 && components
[0] == "api2" {
467 println
!("GOT API REQUEST");
469 let format
= components
[1];
470 let formatter
= match format
{
471 "json" => &JSON_FORMATTER
,
472 "extjs" => &EXTJS_FORMATTER
,
474 return Box
::new(future
::err(http_err
!(BAD_REQUEST
, format
!("Unsupported output format '{}'.", format
))));
478 let mut uri_param
= HashMap
::new();
480 if comp_len
== 4 && components
[2] == "access" && components
[3] == "ticket" {
481 // explicitly allow those calls without auth
483 if let Some(_username
) = rpcenv
.get_user() {
484 // fixme: check permissions
486 // always delay unauthorized calls by 3 seconds (from start of request)
487 let resp
= (formatter
.format_error
)(http_err
!(UNAUTHORIZED
, "permission check failed.".into()));
488 let delayed_response
= tokio
::timer
::Delay
::new(delay_unauth_time
)
489 .map_err(|err
| http_err
!(INTERNAL_SERVER_ERROR
, format
!("tokio timer delay error: {}", err
)))
490 .and_then(|_
| Ok(resp
));
492 return Box
::new(delayed_response
);
496 match api
.find_method(&components
[2..], method
, &mut uri_param
) {
497 MethodDefinition
::None
=> {}
498 MethodDefinition
::Simple(api_method
) => {
499 if api_method
.protected
&& env_type
== RpcEnvironmentType
::PUBLIC
{
500 return proxy_protected_request(api_method
, parts
, body
);
502 return handle_sync_api_request(rpcenv
, api_method
, formatter
, parts
, body
, uri_param
);
505 MethodDefinition
::Async(async_method
) => {
506 return handle_async_api_request(rpcenv
, async_method
, formatter
, parts
, body
, uri_param
);
511 // not Auth for accessing files!
516 let filename
= api
.find_alias(&components
);
517 return handle_static_file_download(filename
);
521 Box
::new(future
::err(http_err
!(NOT_FOUND
, "Path not found.".to_string())))