1 use std
::collections
::HashMap
;
2 use std
::future
::Future
;
3 use std
::hash
::BuildHasher
;
4 use std
::path
::{Path, PathBuf}
;
7 use std
::task
::{Context, Poll}
;
9 use anyhow
::{bail, format_err, Error}
;
10 use futures
::future
::{self, FutureExt, TryFutureExt}
;
11 use futures
::stream
::TryStreamExt
;
13 use hyper
::http
::request
::Parts
;
14 use hyper
::{Body, Request, Response, StatusCode}
;
15 use serde_json
::{json, Value}
;
17 use tokio
::time
::Instant
;
18 use url
::form_urlencoded
;
20 use proxmox
::http_err
;
21 use proxmox
::api
::{ApiHandler, ApiMethod, HttpError}
;
22 use proxmox
::api
::{RpcEnvironment, RpcEnvironmentType, check_api_permission}
;
23 use proxmox
::api
::schema
::{ObjectSchema, parse_simple_value, verify_json_object, parse_parameter_strings}
;
25 use super::environment
::RestEnvironment
;
26 use super::formatter
::*;
29 use crate::auth_helpers
::*;
31 use crate::config
::cached_user_info
::CachedUserInfo
;
33 extern "C" { fn tzset(); }
35 pub struct RestServer
{
36 pub api_config
: Arc
<ApiConfig
>,
41 pub fn new(api_config
: ApiConfig
) -> Self {
42 Self { api_config: Arc::new(api_config) }
46 impl tower_service
::Service
<&tokio_openssl
::SslStream
<tokio
::net
::TcpStream
>> for RestServer
{
47 type Response
= ApiService
;
49 type Future
= Pin
<Box
<dyn Future
<Output
= Result
<ApiService
, Error
>> + Send
>>;
51 fn poll_ready(&mut self, _cx
: &mut Context
) -> Poll
<Result
<(), Self::Error
>> {
55 fn call(&mut self, ctx
: &tokio_openssl
::SslStream
<tokio
::net
::TcpStream
>) -> Self::Future
{
56 match ctx
.get_ref().peer_addr() {
58 future
::err(format_err
!("unable to get peer address - {}", err
)).boxed()
61 future
::ok(ApiService { peer, api_config: self.api_config.clone() }
).boxed()
67 impl tower_service
::Service
<&tokio
::net
::TcpStream
> for RestServer
{
68 type Response
= ApiService
;
70 type Future
= Pin
<Box
<dyn Future
<Output
= Result
<ApiService
, Error
>> + Send
>>;
72 fn poll_ready(&mut self, _cx
: &mut Context
) -> Poll
<Result
<(), Self::Error
>> {
76 fn call(&mut self, ctx
: &tokio
::net
::TcpStream
) -> Self::Future
{
77 match ctx
.peer_addr() {
79 future
::err(format_err
!("unable to get peer address - {}", err
)).boxed()
82 future
::ok(ApiService { peer, api_config: self.api_config.clone() }
).boxed()
88 pub struct ApiService
{
89 pub peer
: std
::net
::SocketAddr
,
90 pub api_config
: Arc
<ApiConfig
>,
94 peer
: &std
::net
::SocketAddr
,
95 method
: hyper
::Method
,
97 resp
: &Response
<Body
>,
100 if resp
.extensions().get
::<NoLogExtension
>().is_some() { return; }
;
102 let status
= resp
.status();
104 if !(status
.is_success() || status
.is_informational()) {
105 let reason
= status
.canonical_reason().unwrap_or("unknown reason");
107 let mut message
= "request failed";
108 if let Some(data
) = resp
.extensions().get
::<ErrorMessageExtension
>() {
112 log
::error
!("{} {}: {} {}: [client {}] {}", method
.as_str(), path
, status
.as_str(), reason
, peer
, message
);
116 impl tower_service
::Service
<Request
<Body
>> for ApiService
{
117 type Response
= Response
<Body
>;
119 type Future
= Pin
<Box
<dyn Future
<Output
= Result
<Response
<Body
>, Self::Error
>> + Send
>>;
121 fn poll_ready(&mut self, _cx
: &mut Context
) -> Poll
<Result
<(), Self::Error
>> {
125 fn call(&mut self, req
: Request
<Body
>) -> Self::Future
{
126 let path
= req
.uri().path().to_owned();
127 let method
= req
.method().clone();
129 let peer
= self.peer
;
130 handle_request(self.api_config
.clone(), req
)
131 .map(move |result
| match result
{
133 log_response(&peer
, method
, &path
, &res
);
134 Ok
::<_
, Self::Error
>(res
)
137 if let Some(apierr
) = err
.downcast_ref
::<HttpError
>() {
138 let mut resp
= Response
::new(Body
::from(apierr
.message
.clone()));
139 *resp
.status_mut() = apierr
.code
;
140 log_response(&peer
, method
, &path
, &resp
);
143 let mut resp
= Response
::new(Body
::from(err
.to_string()));
144 *resp
.status_mut() = StatusCode
::BAD_REQUEST
;
145 log_response(&peer
, method
, &path
, &resp
);
154 fn parse_query_parameters
<S
: '
static + BuildHasher
+ Send
>(
155 param_schema
: &ObjectSchema
,
156 form
: &str, // x-www-form-urlencoded body data
158 uri_param
: &HashMap
<String
, String
, S
>,
159 ) -> Result
<Value
, Error
> {
161 let mut param_list
: Vec
<(String
, String
)> = vec
![];
163 if !form
.is_empty() {
164 for (k
, v
) in form_urlencoded
::parse(form
.as_bytes()).into_owned() {
165 param_list
.push((k
, v
));
169 if let Some(query_str
) = parts
.uri
.query() {
170 for (k
, v
) in form_urlencoded
::parse(query_str
.as_bytes()).into_owned() {
171 if k
== "_dc" { continue; }
// skip extjs "disable cache" parameter
172 param_list
.push((k
, v
));
176 for (k
, v
) in uri_param
{
177 param_list
.push((k
.clone(), v
.clone()));
180 let params
= parse_parameter_strings(¶m_list
, param_schema
, true)?
;
185 async
fn get_request_parameters
<S
: '
static + BuildHasher
+ Send
>(
186 param_schema
: &ObjectSchema
,
189 uri_param
: HashMap
<String
, String
, S
>,
190 ) -> Result
<Value
, Error
> {
192 let mut is_json
= false;
194 if let Some(value
) = parts
.headers
.get(header
::CONTENT_TYPE
) {
195 match value
.to_str().map(|v
| v
.split('
;'
).next()) {
196 Ok(Some("application/x-www-form-urlencoded")) => {
199 Ok(Some("application/json")) => {
202 _
=> bail
!("unsupported content type {:?}", value
.to_str()),
207 .map_err(|err
| http_err
!(BAD_REQUEST
, format
!("Promlems reading request body: {}", err
)))
208 .try_fold(Vec
::new(), |mut acc
, chunk
| async
move {
209 if acc
.len() + chunk
.len() < 64*1024 { //fimxe: max request body size?
210 acc
.extend_from_slice(&*chunk
);
213 Err(http_err
!(BAD_REQUEST
, "Request body too large".to_string()))
217 let utf8_data
= std
::str::from_utf8(&body
)
218 .map_err(|err
| format_err
!("Request body not uft8: {}", err
))?
;
221 let mut params
: Value
= serde_json
::from_str(utf8_data
)?
;
222 for (k
, v
) in uri_param
{
223 if let Some((_optional
, prop_schema
)) = param_schema
.lookup(&k
) {
224 params
[&k
] = parse_simple_value(&v
, prop_schema
)?
;
227 verify_json_object(¶ms
, param_schema
)?
;
230 parse_query_parameters(param_schema
, utf8_data
, &parts
, &uri_param
)
234 struct NoLogExtension();
236 async
fn proxy_protected_request(
237 info
: &'
static ApiMethod
,
240 ) -> Result
<Response
<Body
>, Error
> {
242 let mut uri_parts
= parts
.uri
.clone().into_parts();
244 uri_parts
.scheme
= Some(http
::uri
::Scheme
::HTTP
);
245 uri_parts
.authority
= Some(http
::uri
::Authority
::from_static("127.0.0.1:82"));
246 let new_uri
= http
::Uri
::from_parts(uri_parts
).unwrap();
250 let request
= Request
::from_parts(parts
, req_body
);
252 let reload_timezone
= info
.reload_timezone
;
254 let resp
= hyper
::client
::Client
::new()
256 .map_err(Error
::from
)
258 resp
.extensions_mut().insert(NoLogExtension());
263 if reload_timezone { unsafe { tzset(); }
}
268 pub async
fn handle_api_request
<Env
: RpcEnvironment
, S
: '
static + BuildHasher
+ Send
>(
270 info
: &'
static ApiMethod
,
271 formatter
: &'
static OutputFormatter
,
274 uri_param
: HashMap
<String
, String
, S
>,
275 ) -> Result
<Response
<Body
>, Error
> {
277 let delay_unauth_time
= std
::time
::Instant
::now() + std
::time
::Duration
::from_millis(3000);
279 let result
= match info
.handler
{
280 ApiHandler
::AsyncHttp(handler
) => {
281 let params
= parse_query_parameters(info
.parameters
, "", &parts
, &uri_param
)?
;
282 (handler
)(parts
, req_body
, params
, info
, Box
::new(rpcenv
)).await
284 ApiHandler
::Sync(handler
) => {
285 let params
= get_request_parameters(info
.parameters
, parts
, req_body
, uri_param
).await?
;
286 (handler
)(params
, info
, &mut rpcenv
)
287 .map(|data
| (formatter
.format_data
)(data
, &rpcenv
))
289 ApiHandler
::Async(handler
) => {
290 let params
= get_request_parameters(info
.parameters
, parts
, req_body
, uri_param
).await?
;
291 (handler
)(params
, info
, &mut rpcenv
)
293 .map(|data
| (formatter
.format_data
)(data
, &rpcenv
))
297 let resp
= match result
{
300 if let Some(httperr
) = err
.downcast_ref
::<HttpError
>() {
301 if httperr
.code
== StatusCode
::UNAUTHORIZED
{
302 tokio
::time
::delay_until(Instant
::from_std(delay_unauth_time
)).await
;
305 (formatter
.format_error
)(err
)
309 if info
.reload_timezone { unsafe { tzset(); }
}
314 fn get_index(username
: Option
<String
>, token
: Option
<String
>) -> Response
<Body
> {
316 let nodename
= proxmox
::tools
::nodename();
317 let username
= username
.unwrap_or_else(|| String
::from(""));
319 let token
= token
.unwrap_or_else(|| String
::from(""));
322 "Setup": { "auth_cookie_name": "PBSAuthCookie" }
,
323 "NodeName": nodename
,
324 "UserName": username
,
325 "CSRFPreventionToken": token
,
328 let index
= format
!(r
###"
332 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
333 <meta http-equiv="X-UA-Compatible" content="IE=edge">
334 <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
335 <title>Proxmox Backup Server</title>
336 <link rel="icon" sizes="128x128" href="/images/logo-128.png" />
337 <link rel="apple-touch-icon" sizes="128x128" href="/pve2/images/logo-128.png" />
338 <link rel="stylesheet" type="text/css" href="/extjs/theme-crisp/resources/theme-crisp-all.css" />
339 <link rel="stylesheet" type="text/css" href="/extjs/crisp/resources/charts-all.css" />
340 <link rel="stylesheet" type="text/css" href="/fontawesome/css/font-awesome.css" />
341 <link rel="stylesheet" type="text/css" href="/css/ext6-pbs.css" />
342 <script type='text/javascript'> function gettext(buf) {{ return buf; }} </script>
343 <script type="text/javascript" src="/extjs/ext-all-debug.js"></script>
344 <script type="text/javascript" src="/extjs/charts-debug.js"></script>
345 <script type="text/javascript">
348 <script type="text/javascript" src="/widgettoolkit/proxmoxlib.js"></script>
349 <script type="text/javascript" src="/extjs/locale/locale-en.js"></script>
350 <script type="text/javascript">
351 Ext.History.fieldid = 'x-history-field';
353 <script type="text/javascript" src="/js/proxmox-backup-gui.js"></script>
356 <!-- Fields required for history management -->
357 <form id="history-form" class="x-hidden">
358 <input type="hidden" id="x-history-field"/>
362 "###, setup.to_string());
365 .status(StatusCode
::OK
)
366 .header(header
::CONTENT_TYPE
, "text/html")
371 fn extension_to_content_type(filename
: &Path
) -> (&'
static str, bool
) {
373 if let Some(ext
) = filename
.extension().and_then(|osstr
| osstr
.to_str()) {
375 "css" => ("text/css", false),
376 "html" => ("text/html", false),
377 "js" => ("application/javascript", false),
378 "json" => ("application/json", false),
379 "map" => ("application/json", false),
380 "png" => ("image/png", true),
381 "ico" => ("image/x-icon", true),
382 "gif" => ("image/gif", true),
383 "svg" => ("image/svg+xml", false),
384 "jar" => ("application/java-archive", true),
385 "woff" => ("application/font-woff", true),
386 "woff2" => ("application/font-woff2", true),
387 "ttf" => ("application/font-snft", true),
388 "pdf" => ("application/pdf", true),
389 "epub" => ("application/epub+zip", true),
390 "mp3" => ("audio/mpeg", true),
391 "oga" => ("audio/ogg", true),
392 "tgz" => ("application/x-compressed-tar", true),
393 _
=> ("application/octet-stream", false),
397 ("application/octet-stream", false)
400 async
fn simple_static_file_download(filename
: PathBuf
) -> Result
<Response
<Body
>, Error
> {
402 let (content_type
, _nocomp
) = extension_to_content_type(&filename
);
404 use tokio
::io
::AsyncReadExt
;
406 let mut file
= File
::open(filename
)
408 .map_err(|err
| http_err
!(BAD_REQUEST
, format
!("File open failed: {}", err
)))?
;
410 let mut data
: Vec
<u8> = Vec
::new();
411 file
.read_to_end(&mut data
)
413 .map_err(|err
| http_err
!(BAD_REQUEST
, format
!("File read failed: {}", err
)))?
;
415 let mut response
= Response
::new(data
.into());
416 response
.headers_mut().insert(
417 header
::CONTENT_TYPE
,
418 header
::HeaderValue
::from_static(content_type
));
422 async
fn chuncked_static_file_download(filename
: PathBuf
) -> Result
<Response
<Body
>, Error
> {
423 let (content_type
, _nocomp
) = extension_to_content_type(&filename
);
425 let file
= File
::open(filename
)
427 .map_err(|err
| http_err
!(BAD_REQUEST
, format
!("File open failed: {}", err
)))?
;
429 let payload
= tokio_util
::codec
::FramedRead
::new(file
, tokio_util
::codec
::BytesCodec
::new())
430 .map_ok(|bytes
| hyper
::body
::Bytes
::from(bytes
.freeze()));
431 let body
= Body
::wrap_stream(payload
);
433 // fixme: set other headers ?
434 Ok(Response
::builder()
435 .status(StatusCode
::OK
)
436 .header(header
::CONTENT_TYPE
, content_type
)
442 async
fn handle_static_file_download(filename
: PathBuf
) -> Result
<Response
<Body
>, Error
> {
444 let metadata
= tokio
::fs
::metadata(filename
.clone())
445 .map_err(|err
| http_err
!(BAD_REQUEST
, format
!("File access problems: {}", err
)))
448 if metadata
.len() < 1024*32 {
449 simple_static_file_download(filename
).await
451 chuncked_static_file_download(filename
).await
455 fn extract_auth_data(headers
: &http
::HeaderMap
) -> (Option
<String
>, Option
<String
>) {
457 let mut ticket
= None
;
458 if let Some(raw_cookie
) = headers
.get("COOKIE") {
459 if let Ok(cookie
) = raw_cookie
.to_str() {
460 ticket
= tools
::extract_auth_cookie(cookie
, "PBSAuthCookie");
464 let token
= match headers
.get("CSRFPreventionToken").map(|v
| v
.to_str()) {
465 Some(Ok(v
)) => Some(v
.to_owned()),
473 method
: &hyper
::Method
,
474 ticket
: &Option
<String
>,
475 token
: &Option
<String
>,
476 user_info
: &CachedUserInfo
,
477 ) -> Result
<String
, Error
> {
479 let ticket_lifetime
= tools
::ticket
::TICKET_LIFETIME
;
481 let username
= match ticket
{
482 Some(ticket
) => match tools
::ticket
::verify_rsa_ticket(public_auth_key(), "PBS", &ticket
, None
, -300, ticket_lifetime
) {
483 Ok((_age
, Some(username
))) => username
.to_owned(),
484 Ok((_
, None
)) => bail
!("ticket without username."),
485 Err(err
) => return Err(err
),
487 None
=> bail
!("missing ticket"),
490 if !user_info
.is_active_user(&username
) {
491 bail
!("user account disabled or expired.");
494 if method
!= hyper
::Method
::GET
{
495 if let Some(token
) = token
{
496 println
!("CSRF prevention token: {:?}", token
);
497 verify_csrf_prevention_token(csrf_secret(), &username
, &token
, -300, ticket_lifetime
)?
;
499 bail
!("missing CSRF prevention token");
506 pub async
fn handle_request(api
: Arc
<ApiConfig
>, req
: Request
<Body
>) -> Result
<Response
<Body
>, Error
> {
508 let (parts
, body
) = req
.into_parts();
510 let method
= parts
.method
.clone();
511 let (path
, components
) = tools
::normalize_uri_path(parts
.uri
.path())?
;
513 let comp_len
= components
.len();
515 println
!("REQUEST {} {}", method
, path
);
516 println
!("COMPO {:?}", components
);
518 let env_type
= api
.env_type();
519 let mut rpcenv
= RestEnvironment
::new(env_type
);
521 let user_info
= CachedUserInfo
::new()?
;
523 let delay_unauth_time
= std
::time
::Instant
::now() + std
::time
::Duration
::from_millis(3000);
524 let access_forbidden_time
= std
::time
::Instant
::now() + std
::time
::Duration
::from_millis(500);
526 if comp_len
>= 1 && components
[0] == "api2" {
530 let format
= components
[1];
532 let formatter
= match format
{
533 "json" => &JSON_FORMATTER
,
534 "extjs" => &EXTJS_FORMATTER
,
535 _
=> bail
!("Unsupported output format '{}'.", format
),
538 let mut uri_param
= HashMap
::new();
540 if comp_len
== 4 && components
[2] == "access" && (
541 (components
[3] == "ticket" && method
== hyper
::Method
::POST
) ||
542 (components
[3] == "domains" && method
== hyper
::Method
::GET
)
544 // explicitly allow those calls without auth
546 let (ticket
, token
) = extract_auth_data(&parts
.headers
);
547 match check_auth(&method
, &ticket
, &token
, &user_info
) {
548 Ok(username
) => rpcenv
.set_user(Some(username
)),
550 // always delay unauthorized calls by 3 seconds (from start of request)
551 let err
= http_err
!(UNAUTHORIZED
, format
!("authentication failed - {}", err
));
552 tokio
::time
::delay_until(Instant
::from_std(delay_unauth_time
)).await
;
553 return Ok((formatter
.format_error
)(err
));
558 match api
.find_method(&components
[2..], method
, &mut uri_param
) {
560 let err
= http_err
!(NOT_FOUND
, "Path not found.".to_string());
561 return Ok((formatter
.format_error
)(err
));
563 Some(api_method
) => {
564 let user
= rpcenv
.get_user();
565 if !check_api_permission(api_method
.access
.permission
, user
.as_deref(), &uri_param
, &user_info
) {
566 let err
= http_err
!(FORBIDDEN
, format
!("permission check failed"));
567 tokio
::time
::delay_until(Instant
::from_std(access_forbidden_time
)).await
;
568 return Ok((formatter
.format_error
)(err
));
571 let result
= if api_method
.protected
&& env_type
== RpcEnvironmentType
::PUBLIC
{
572 proxy_protected_request(api_method
, parts
, body
).await
574 handle_api_request(rpcenv
, api_method
, formatter
, parts
, body
, uri_param
).await
577 if let Err(err
) = result
{
578 return Ok((formatter
.format_error
)(err
));
586 // not Auth required for accessing files!
588 if method
!= hyper
::Method
::GET
{
589 bail
!("Unsupported HTTP method {}", method
);
593 let (ticket
, token
) = extract_auth_data(&parts
.headers
);
595 match check_auth(&method
, &ticket
, &token
, &user_info
) {
597 let new_token
= assemble_csrf_prevention_token(csrf_secret(), &username
);
598 return Ok(get_index(Some(username
), Some(new_token
)));
601 tokio
::time
::delay_until(Instant
::from_std(delay_unauth_time
)).await
;
602 return Ok(get_index(None
, None
));
606 return Ok(get_index(None
, None
));
609 let filename
= api
.find_alias(&components
);
610 return handle_static_file_download(filename
).await
;
614 Err(http_err
!(NOT_FOUND
, "Path not found.".to_string()))