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
;
30 use proxmox
::api
::schema
::{
32 parse_parameter_strings
,
37 use super::environment
::RestEnvironment
;
38 use super::formatter
::*;
41 use crate::auth_helpers
::*;
42 use crate::api2
::types
::Userid
;
44 use crate::tools
::ticket
::Ticket
;
45 use crate::config
::cached_user_info
::CachedUserInfo
;
47 extern "C" { fn tzset(); }
49 pub struct RestServer
{
50 pub api_config
: Arc
<ApiConfig
>,
55 pub fn new(api_config
: ApiConfig
) -> Self {
56 Self { api_config: Arc::new(api_config) }
60 impl tower_service
::Service
<&tokio_openssl
::SslStream
<tokio
::net
::TcpStream
>> for RestServer
{
61 type Response
= ApiService
;
63 type Future
= Pin
<Box
<dyn Future
<Output
= Result
<ApiService
, Error
>> + Send
>>;
65 fn poll_ready(&mut self, _cx
: &mut Context
) -> Poll
<Result
<(), Self::Error
>> {
69 fn call(&mut self, ctx
: &tokio_openssl
::SslStream
<tokio
::net
::TcpStream
>) -> Self::Future
{
70 match ctx
.get_ref().peer_addr() {
72 future
::err(format_err
!("unable to get peer address - {}", err
)).boxed()
75 future
::ok(ApiService { peer, api_config: self.api_config.clone() }
).boxed()
81 impl tower_service
::Service
<&tokio
::net
::TcpStream
> for RestServer
{
82 type Response
= ApiService
;
84 type Future
= Pin
<Box
<dyn Future
<Output
= Result
<ApiService
, Error
>> + Send
>>;
86 fn poll_ready(&mut self, _cx
: &mut Context
) -> Poll
<Result
<(), Self::Error
>> {
90 fn call(&mut self, ctx
: &tokio
::net
::TcpStream
) -> Self::Future
{
91 match ctx
.peer_addr() {
93 future
::err(format_err
!("unable to get peer address - {}", err
)).boxed()
96 future
::ok(ApiService { peer, api_config: self.api_config.clone() }
).boxed()
102 pub struct ApiService
{
103 pub peer
: std
::net
::SocketAddr
,
104 pub api_config
: Arc
<ApiConfig
>,
108 peer
: &std
::net
::SocketAddr
,
109 method
: hyper
::Method
,
111 resp
: &Response
<Body
>,
114 if resp
.extensions().get
::<NoLogExtension
>().is_some() { return; }
;
116 let status
= resp
.status();
118 if !(status
.is_success() || status
.is_informational()) {
119 let reason
= status
.canonical_reason().unwrap_or("unknown reason");
121 let mut message
= "request failed";
122 if let Some(data
) = resp
.extensions().get
::<ErrorMessageExtension
>() {
126 log
::error
!("{} {}: {} {}: [client {}] {}", method
.as_str(), path
, status
.as_str(), reason
, peer
, message
);
130 impl tower_service
::Service
<Request
<Body
>> for ApiService
{
131 type Response
= Response
<Body
>;
133 type Future
= Pin
<Box
<dyn Future
<Output
= Result
<Response
<Body
>, Self::Error
>> + Send
>>;
135 fn poll_ready(&mut self, _cx
: &mut Context
) -> Poll
<Result
<(), Self::Error
>> {
139 fn call(&mut self, req
: Request
<Body
>) -> Self::Future
{
140 let path
= req
.uri().path().to_owned();
141 let method
= req
.method().clone();
143 let peer
= self.peer
;
144 handle_request(self.api_config
.clone(), req
)
145 .map(move |result
| match result
{
147 log_response(&peer
, method
, &path
, &res
);
148 Ok
::<_
, Self::Error
>(res
)
151 if let Some(apierr
) = err
.downcast_ref
::<HttpError
>() {
152 let mut resp
= Response
::new(Body
::from(apierr
.message
.clone()));
153 *resp
.status_mut() = apierr
.code
;
154 log_response(&peer
, method
, &path
, &resp
);
157 let mut resp
= Response
::new(Body
::from(err
.to_string()));
158 *resp
.status_mut() = StatusCode
::BAD_REQUEST
;
159 log_response(&peer
, method
, &path
, &resp
);
168 fn parse_query_parameters
<S
: '
static + BuildHasher
+ Send
>(
169 param_schema
: &ObjectSchema
,
170 form
: &str, // x-www-form-urlencoded body data
172 uri_param
: &HashMap
<String
, String
, S
>,
173 ) -> Result
<Value
, Error
> {
175 let mut param_list
: Vec
<(String
, String
)> = vec
![];
177 if !form
.is_empty() {
178 for (k
, v
) in form_urlencoded
::parse(form
.as_bytes()).into_owned() {
179 param_list
.push((k
, v
));
183 if let Some(query_str
) = parts
.uri
.query() {
184 for (k
, v
) in form_urlencoded
::parse(query_str
.as_bytes()).into_owned() {
185 if k
== "_dc" { continue; }
// skip extjs "disable cache" parameter
186 param_list
.push((k
, v
));
190 for (k
, v
) in uri_param
{
191 param_list
.push((k
.clone(), v
.clone()));
194 let params
= parse_parameter_strings(¶m_list
, param_schema
, true)?
;
199 async
fn get_request_parameters
<S
: '
static + BuildHasher
+ Send
>(
200 param_schema
: &ObjectSchema
,
203 uri_param
: HashMap
<String
, String
, S
>,
204 ) -> Result
<Value
, Error
> {
206 let mut is_json
= false;
208 if let Some(value
) = parts
.headers
.get(header
::CONTENT_TYPE
) {
209 match value
.to_str().map(|v
| v
.split('
;'
).next()) {
210 Ok(Some("application/x-www-form-urlencoded")) => {
213 Ok(Some("application/json")) => {
216 _
=> bail
!("unsupported content type {:?}", value
.to_str()),
221 .map_err(|err
| http_err
!(BAD_REQUEST
, "Promlems reading request body: {}", err
))
222 .try_fold(Vec
::new(), |mut acc
, chunk
| async
move {
223 if acc
.len() + chunk
.len() < 64*1024 { //fimxe: max request body size?
224 acc
.extend_from_slice(&*chunk
);
227 Err(http_err
!(BAD_REQUEST
, "Request body too large"))
231 let utf8_data
= std
::str::from_utf8(&body
)
232 .map_err(|err
| format_err
!("Request body not uft8: {}", err
))?
;
235 let mut params
: Value
= serde_json
::from_str(utf8_data
)?
;
236 for (k
, v
) in uri_param
{
237 if let Some((_optional
, prop_schema
)) = param_schema
.lookup(&k
) {
238 params
[&k
] = parse_simple_value(&v
, prop_schema
)?
;
241 verify_json_object(¶ms
, param_schema
)?
;
244 parse_query_parameters(param_schema
, utf8_data
, &parts
, &uri_param
)
248 struct NoLogExtension();
250 async
fn proxy_protected_request(
251 info
: &'
static ApiMethod
,
254 ) -> Result
<Response
<Body
>, Error
> {
256 let mut uri_parts
= parts
.uri
.clone().into_parts();
258 uri_parts
.scheme
= Some(http
::uri
::Scheme
::HTTP
);
259 uri_parts
.authority
= Some(http
::uri
::Authority
::from_static("127.0.0.1:82"));
260 let new_uri
= http
::Uri
::from_parts(uri_parts
).unwrap();
264 let request
= Request
::from_parts(parts
, req_body
);
266 let reload_timezone
= info
.reload_timezone
;
268 let resp
= hyper
::client
::Client
::new()
270 .map_err(Error
::from
)
272 resp
.extensions_mut().insert(NoLogExtension());
277 if reload_timezone { unsafe { tzset(); }
}
282 pub async
fn handle_api_request
<Env
: RpcEnvironment
, S
: '
static + BuildHasher
+ Send
>(
284 info
: &'
static ApiMethod
,
285 formatter
: &'
static OutputFormatter
,
288 uri_param
: HashMap
<String
, String
, S
>,
289 ) -> Result
<Response
<Body
>, Error
> {
291 let delay_unauth_time
= std
::time
::Instant
::now() + std
::time
::Duration
::from_millis(3000);
293 let result
= match info
.handler
{
294 ApiHandler
::AsyncHttp(handler
) => {
295 let params
= parse_query_parameters(info
.parameters
, "", &parts
, &uri_param
)?
;
296 (handler
)(parts
, req_body
, params
, info
, Box
::new(rpcenv
)).await
298 ApiHandler
::Sync(handler
) => {
299 let params
= get_request_parameters(info
.parameters
, parts
, req_body
, uri_param
).await?
;
300 (handler
)(params
, info
, &mut rpcenv
)
301 .map(|data
| (formatter
.format_data
)(data
, &rpcenv
))
303 ApiHandler
::Async(handler
) => {
304 let params
= get_request_parameters(info
.parameters
, parts
, req_body
, uri_param
).await?
;
305 (handler
)(params
, info
, &mut rpcenv
)
307 .map(|data
| (formatter
.format_data
)(data
, &rpcenv
))
311 let resp
= match result
{
314 if let Some(httperr
) = err
.downcast_ref
::<HttpError
>() {
315 if httperr
.code
== StatusCode
::UNAUTHORIZED
{
316 tokio
::time
::delay_until(Instant
::from_std(delay_unauth_time
)).await
;
319 (formatter
.format_error
)(err
)
323 if info
.reload_timezone { unsafe { tzset(); }
}
329 userid
: Option
<Userid
>,
330 token
: Option
<String
>,
331 language
: Option
<String
>,
332 api
: &Arc
<ApiConfig
>,
334 ) -> Response
<Body
> {
336 let nodename
= proxmox
::tools
::nodename();
337 let userid
= userid
.as_ref().map(|u
| u
.as_str()).unwrap_or("");
339 let token
= token
.unwrap_or_else(|| String
::from(""));
341 let mut debug
= false;
342 let mut template_file
= "index";
344 if let Some(query_str
) = parts
.uri
.query() {
345 for (k
, v
) in form_urlencoded
::parse(query_str
.as_bytes()).into_owned() {
346 if k
== "debug" && v
!= "0" && v
!= "false" {
348 } else if k
== "console" {
349 template_file
= "console";
354 let mut lang
= String
::from("");
355 if let Some(language
) = language
{
356 if Path
::new(&format
!("/usr/share/pbs-i18n/pbs-lang-{}.js", language
)).exists() {
362 "NodeName": nodename
,
364 "CSRFPreventionToken": token
,
369 let mut ct
= "text/html";
371 let index
= match api
.render_template(template_file
, &data
) {
375 format
!("Error rendering template: {}", err
)
380 .status(StatusCode
::OK
)
381 .header(header
::CONTENT_TYPE
, ct
)
386 fn extension_to_content_type(filename
: &Path
) -> (&'
static str, bool
) {
388 if let Some(ext
) = filename
.extension().and_then(|osstr
| osstr
.to_str()) {
390 "css" => ("text/css", false),
391 "html" => ("text/html", false),
392 "js" => ("application/javascript", false),
393 "json" => ("application/json", false),
394 "map" => ("application/json", false),
395 "png" => ("image/png", true),
396 "ico" => ("image/x-icon", true),
397 "gif" => ("image/gif", true),
398 "svg" => ("image/svg+xml", false),
399 "jar" => ("application/java-archive", true),
400 "woff" => ("application/font-woff", true),
401 "woff2" => ("application/font-woff2", true),
402 "ttf" => ("application/font-snft", true),
403 "pdf" => ("application/pdf", true),
404 "epub" => ("application/epub+zip", true),
405 "mp3" => ("audio/mpeg", true),
406 "oga" => ("audio/ogg", true),
407 "tgz" => ("application/x-compressed-tar", true),
408 _
=> ("application/octet-stream", false),
412 ("application/octet-stream", false)
415 async
fn simple_static_file_download(filename
: PathBuf
) -> Result
<Response
<Body
>, Error
> {
417 let (content_type
, _nocomp
) = extension_to_content_type(&filename
);
419 use tokio
::io
::AsyncReadExt
;
421 let mut file
= File
::open(filename
)
423 .map_err(|err
| http_err
!(BAD_REQUEST
, "File open failed: {}", err
))?
;
425 let mut data
: Vec
<u8> = Vec
::new();
426 file
.read_to_end(&mut data
)
428 .map_err(|err
| http_err
!(BAD_REQUEST
, "File read failed: {}", err
))?
;
430 let mut response
= Response
::new(data
.into());
431 response
.headers_mut().insert(
432 header
::CONTENT_TYPE
,
433 header
::HeaderValue
::from_static(content_type
));
437 async
fn chuncked_static_file_download(filename
: PathBuf
) -> Result
<Response
<Body
>, Error
> {
438 let (content_type
, _nocomp
) = extension_to_content_type(&filename
);
440 let file
= File
::open(filename
)
442 .map_err(|err
| http_err
!(BAD_REQUEST
, "File open failed: {}", err
))?
;
444 let payload
= tokio_util
::codec
::FramedRead
::new(file
, tokio_util
::codec
::BytesCodec
::new())
445 .map_ok(|bytes
| hyper
::body
::Bytes
::from(bytes
.freeze()));
446 let body
= Body
::wrap_stream(payload
);
448 // fixme: set other headers ?
449 Ok(Response
::builder()
450 .status(StatusCode
::OK
)
451 .header(header
::CONTENT_TYPE
, content_type
)
457 async
fn handle_static_file_download(filename
: PathBuf
) -> Result
<Response
<Body
>, Error
> {
459 let metadata
= tokio
::fs
::metadata(filename
.clone())
460 .map_err(|err
| http_err
!(BAD_REQUEST
, "File access problems: {}", err
))
463 if metadata
.len() < 1024*32 {
464 simple_static_file_download(filename
).await
466 chuncked_static_file_download(filename
).await
470 fn extract_auth_data(headers
: &http
::HeaderMap
) -> (Option
<String
>, Option
<String
>, Option
<String
>) {
472 let mut ticket
= None
;
473 let mut language
= None
;
474 if let Some(raw_cookie
) = headers
.get("COOKIE") {
475 if let Ok(cookie
) = raw_cookie
.to_str() {
476 ticket
= tools
::extract_cookie(cookie
, "PBSAuthCookie");
477 language
= tools
::extract_cookie(cookie
, "PBSLangCookie");
481 let token
= match headers
.get("CSRFPreventionToken").map(|v
| v
.to_str()) {
482 Some(Ok(v
)) => Some(v
.to_owned()),
486 (ticket
, token
, language
)
490 method
: &hyper
::Method
,
491 ticket
: &Option
<String
>,
492 token
: &Option
<String
>,
493 user_info
: &CachedUserInfo
,
494 ) -> Result
<Userid
, Error
> {
495 let ticket_lifetime
= tools
::ticket
::TICKET_LIFETIME
;
497 let ticket
= ticket
.as_ref().map(String
::as_str
);
498 let userid
: Userid
= Ticket
::parse(&ticket
.ok_or_else(|| format_err
!("missing ticket"))?
)?
499 .verify_with_time_frame(public_auth_key(), "PBS", None
, -300..ticket_lifetime
)?
;
501 if !user_info
.is_active_user(&userid
) {
502 bail
!("user account disabled or expired.");
505 if method
!= hyper
::Method
::GET
{
506 if let Some(token
) = token
{
507 println
!("CSRF prevention token: {:?}", token
);
508 verify_csrf_prevention_token(csrf_secret(), &userid
, &token
, -300, ticket_lifetime
)?
;
510 bail
!("missing CSRF prevention token");
517 pub async
fn handle_request(api
: Arc
<ApiConfig
>, req
: Request
<Body
>) -> Result
<Response
<Body
>, Error
> {
519 let (parts
, body
) = req
.into_parts();
521 let method
= parts
.method
.clone();
522 let (path
, components
) = tools
::normalize_uri_path(parts
.uri
.path())?
;
524 let comp_len
= components
.len();
526 //println!("REQUEST {} {}", method, path);
527 //println!("COMPO {:?}", components);
529 let env_type
= api
.env_type();
530 let mut rpcenv
= RestEnvironment
::new(env_type
);
532 let user_info
= CachedUserInfo
::new()?
;
534 let delay_unauth_time
= std
::time
::Instant
::now() + std
::time
::Duration
::from_millis(3000);
535 let access_forbidden_time
= std
::time
::Instant
::now() + std
::time
::Duration
::from_millis(500);
537 if comp_len
>= 1 && components
[0] == "api2" {
541 let format
= components
[1];
543 let formatter
= match format
{
544 "json" => &JSON_FORMATTER
,
545 "extjs" => &EXTJS_FORMATTER
,
546 _
=> bail
!("Unsupported output format '{}'.", format
),
549 let mut uri_param
= HashMap
::new();
550 let api_method
= api
.find_method(&components
[2..], method
.clone(), &mut uri_param
);
552 let mut auth_required
= true;
553 if let Some(api_method
) = api_method
{
554 if let Permission
::World
= *api_method
.access
.permission
{
555 auth_required
= false; // no auth for endpoints with World permission
560 let (ticket
, token
, _
) = extract_auth_data(&parts
.headers
);
561 match check_auth(&method
, &ticket
, &token
, &user_info
) {
562 Ok(userid
) => rpcenv
.set_user(Some(userid
.to_string())),
564 // always delay unauthorized calls by 3 seconds (from start of request)
565 let err
= http_err
!(UNAUTHORIZED
, "authentication failed - {}", err
);
566 tokio
::time
::delay_until(Instant
::from_std(delay_unauth_time
)).await
;
567 return Ok((formatter
.format_error
)(err
));
574 let err
= http_err
!(NOT_FOUND
, "Path '{}' not found.", path
);
575 return Ok((formatter
.format_error
)(err
));
577 Some(api_method
) => {
578 let user
= rpcenv
.get_user();
579 if !check_api_permission(api_method
.access
.permission
, user
.as_deref(), &uri_param
, user_info
.as_ref()) {
580 let err
= http_err
!(FORBIDDEN
, "permission check failed");
581 tokio
::time
::delay_until(Instant
::from_std(access_forbidden_time
)).await
;
582 return Ok((formatter
.format_error
)(err
));
585 let result
= if api_method
.protected
&& env_type
== RpcEnvironmentType
::PUBLIC
{
586 proxy_protected_request(api_method
, parts
, body
).await
588 handle_api_request(rpcenv
, api_method
, formatter
, parts
, body
, uri_param
).await
591 if let Err(err
) = result
{
592 return Ok((formatter
.format_error
)(err
));
600 // not Auth required for accessing files!
602 if method
!= hyper
::Method
::GET
{
603 bail
!("Unsupported HTTP method {}", method
);
607 let (ticket
, token
, language
) = extract_auth_data(&parts
.headers
);
609 match check_auth(&method
, &ticket
, &token
, &user_info
) {
611 let new_token
= assemble_csrf_prevention_token(csrf_secret(), &userid
);
612 return Ok(get_index(Some(userid
), Some(new_token
), language
, &api
, parts
));
615 tokio
::time
::delay_until(Instant
::from_std(delay_unauth_time
)).await
;
616 return Ok(get_index(None
, None
, language
, &api
, parts
));
620 return Ok(get_index(None
, None
, language
, &api
, parts
));
623 let filename
= api
.find_alias(&components
);
624 return handle_static_file_download(filename
).await
;
628 Err(http_err
!(NOT_FOUND
, "Path '{}' not found.", path
))