1 use std
::collections
::HashMap
;
2 use std
::future
::Future
;
3 use std
::hash
::BuildHasher
;
4 use std
::path
::{Path, PathBuf}
;
6 use std
::sync
::{Arc, Mutex}
;
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
;
12 use hyper
::body
::HttpBody
;
13 use hyper
::header
::{self, HeaderMap}
;
14 use hyper
::http
::request
::Parts
;
15 use hyper
::{Body, Request, Response, StatusCode}
;
16 use lazy_static
::lazy_static
;
18 use serde_json
::{json, Value}
;
20 use tokio
::time
::Instant
;
21 use url
::form_urlencoded
;
23 use proxmox
::api
::schema
::{
24 parse_parameter_strings
, parse_simple_value
, verify_json_object
, ObjectSchemaType
,
28 check_api_permission
, ApiHandler
, ApiMethod
, HttpError
, Permission
, RpcEnvironment
,
31 use proxmox
::http_err
;
32 use proxmox
::tools
::fs
::CreateOptions
;
34 use pbs_tools
::compression
::{DeflateEncoder, Level}
;
35 use pbs_tools
::stream
::AsyncReaderStream
;
36 use pbs_api_types
::{Authid, Userid}
;
37 use proxmox_rest_server
::{ApiConfig, FileLogger, FileLogOptions, AuthError}
;
39 use super::environment
::RestEnvironment
;
40 use super::formatter
::*;
42 use crate::auth_helpers
::*;
43 use pbs_config
::CachedUserInfo
;
45 use crate::tools
::compression
::CompressionMethod
;
51 pub struct RestServer
{
52 pub api_config
: Arc
<ApiConfig
>,
55 const MAX_URI_QUERY_LENGTH
: usize = 3072;
56 const CHUNK_SIZE_LIMIT
: u64 = 32 * 1024;
59 pub fn new(api_config
: ApiConfig
) -> Self {
61 api_config
: Arc
::new(api_config
),
66 impl tower_service
::Service
<&Pin
<Box
<tokio_openssl
::SslStream
<tokio
::net
::TcpStream
>>>>
69 type Response
= ApiService
;
71 type Future
= Pin
<Box
<dyn Future
<Output
= Result
<ApiService
, Error
>> + Send
>>;
73 fn poll_ready(&mut self, _cx
: &mut Context
) -> Poll
<Result
<(), Self::Error
>> {
79 ctx
: &Pin
<Box
<tokio_openssl
::SslStream
<tokio
::net
::TcpStream
>>>,
81 match ctx
.get_ref().peer_addr() {
82 Err(err
) => future
::err(format_err
!("unable to get peer address - {}", err
)).boxed(),
83 Ok(peer
) => future
::ok(ApiService
{
85 api_config
: self.api_config
.clone(),
92 impl tower_service
::Service
<&tokio
::net
::TcpStream
> for RestServer
{
93 type Response
= ApiService
;
95 type Future
= Pin
<Box
<dyn Future
<Output
= Result
<ApiService
, Error
>> + Send
>>;
97 fn poll_ready(&mut self, _cx
: &mut Context
) -> Poll
<Result
<(), Self::Error
>> {
101 fn call(&mut self, ctx
: &tokio
::net
::TcpStream
) -> Self::Future
{
102 match ctx
.peer_addr() {
103 Err(err
) => future
::err(format_err
!("unable to get peer address - {}", err
)).boxed(),
104 Ok(peer
) => future
::ok(ApiService
{
106 api_config
: self.api_config
.clone(),
113 impl tower_service
::Service
<&tokio
::net
::UnixStream
> for RestServer
{
114 type Response
= ApiService
;
116 type Future
= Pin
<Box
<dyn Future
<Output
= Result
<ApiService
, Error
>> + Send
>>;
118 fn poll_ready(&mut self, _cx
: &mut Context
) -> Poll
<Result
<(), Self::Error
>> {
122 fn call(&mut self, _ctx
: &tokio
::net
::UnixStream
) -> Self::Future
{
123 // TODO: Find a way to actually represent the vsock peer in the ApiService struct - for now
124 // it doesn't really matter, so just use a fake IP address
125 let fake_peer
= "0.0.0.0:807".parse().unwrap();
126 future
::ok(ApiService
{
128 api_config
: self.api_config
.clone(),
134 pub struct ApiService
{
135 pub peer
: std
::net
::SocketAddr
,
136 pub api_config
: Arc
<ApiConfig
>,
140 logfile
: Option
<&Arc
<Mutex
<FileLogger
>>>,
141 peer
: &std
::net
::SocketAddr
,
142 method
: hyper
::Method
,
144 resp
: &Response
<Body
>,
145 user_agent
: Option
<String
>,
147 if resp
.extensions().get
::<NoLogExtension
>().is_some() {
151 // we also log URL-to-long requests, so avoid message bigger than PIPE_BUF (4k on Linux)
152 // to profit from atomicty guarantees for O_APPEND opened logfiles
153 let path
= &path_query
[..MAX_URI_QUERY_LENGTH
.min(path_query
.len())];
155 let status
= resp
.status();
156 if !(status
.is_success() || status
.is_informational()) {
157 let reason
= status
.canonical_reason().unwrap_or("unknown reason");
159 let message
= match resp
.extensions().get
::<ErrorMessageExtension
>() {
160 Some(data
) => &data
.0,
161 None
=> "request failed",
165 "{} {}: {} {}: [client {}] {}",
174 if let Some(logfile
) = logfile
{
175 let auth_id
= match resp
.extensions().get
::<Authid
>() {
176 Some(auth_id
) => auth_id
.to_string(),
177 None
=> "-".to_string(),
179 let now
= proxmox
::tools
::time
::epoch_i64();
180 // time format which apache/nginx use (by default), copied from pve-http-server
181 let datetime
= proxmox
::tools
::time
::strftime_local("%d/%m/%Y:%H:%M:%S %z", now
)
182 .unwrap_or_else(|_
| "-".to_string());
184 logfile
.lock().unwrap().log(format
!(
185 "{} - {} [{}] \"{} {}\" {} {} {}",
192 resp
.body().size_hint().lower(),
193 user_agent
.unwrap_or_else(|| "-".to_string()),
197 pub fn auth_logger() -> Result
<FileLogger
, Error
> {
198 let backup_user
= pbs_config
::backup_user()?
;
200 let file_opts
= CreateOptions
::new()
201 .owner(backup_user
.uid
)
202 .group(backup_user
.gid
);
204 let logger_options
= FileLogOptions
{
210 FileLogger
::new(pbs_buildcfg
::API_AUTH_LOG_FN
, logger_options
)
213 fn get_proxied_peer(headers
: &HeaderMap
) -> Option
<std
::net
::SocketAddr
> {
215 static ref RE
: Regex
= Regex
::new(r
#"for="([^"]+)""#).unwrap();
217 let forwarded = headers.get(header::FORWARDED)?.to_str().ok()?;
218 let capture = RE.captures(&forwarded)?;
219 let rhost = capture.get(1)?.as_str();
224 fn get_user_agent(headers: &HeaderMap) -> Option<String> {
225 let agent = headers.get(header::USER_AGENT)?.to_str();
228 let mut s = s.to_owned();
235 impl tower_service::Service<Request<Body>> for ApiService {
236 type Response = Response<Body>;
238 #[allow(clippy::type_complexity)]
239 type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
241 fn poll_ready(&mut self, _cx: &mut Context) -> Poll<Result<(), Self::Error>> {
245 fn call(&mut self, req: Request<Body>) -> Self::Future {
246 let path = req.uri().path_and_query().unwrap().as_str().to_owned();
247 let method = req.method().clone();
248 let user_agent = get_user_agent(req.headers());
250 let config = Arc::clone(&self.api_config);
251 let peer = match get_proxied_peer(req.headers()) {
252 Some(proxied_peer) => proxied_peer,
256 let response = match handle_request(Arc::clone(&config), req, &peer).await {
257 Ok(response) => response,
259 let (err, code) = match err.downcast_ref::<HttpError>() {
260 Some(apierr) => (apierr.message.clone(), apierr.code),
261 _ => (err.to_string(), StatusCode::BAD_REQUEST),
265 .extension(ErrorMessageExtension(err.to_string()))
269 let logger = config.get_file_log();
270 log_response(logger, &peer, method, &path, &response, user_agent);
277 fn parse_query_parameters<S: 'static + BuildHasher + Send>(
278 param_schema: ParameterSchema,
279 form: &str, // x-www-form-urlencoded body data
281 uri_param: &HashMap<String, String, S>,
282 ) -> Result<Value, Error> {
283 let mut param_list: Vec<(String, String)> = vec![];
285 if !form.is_empty() {
286 for (k, v) in form_urlencoded::parse(form.as_bytes()).into_owned() {
287 param_list.push((k, v));
291 if let Some(query_str) = parts.uri.query() {
292 for (k, v) in form_urlencoded::parse(query_str.as_bytes()).into_owned() {
295 } // skip extjs "disable cache" parameter
296 param_list.push((k, v));
300 for (k, v) in uri_param {
301 param_list.push((k.clone(), v.clone()));
304 let params = parse_parameter_strings(¶m_list, param_schema, true)?;
309 async fn get_request_parameters<S: 'static + BuildHasher + Send>(
310 param_schema: ParameterSchema,
313 uri_param: HashMap<String, String, S>,
314 ) -> Result<Value, Error> {
315 let mut is_json = false;
317 if let Some(value) = parts.headers.get(header::CONTENT_TYPE) {
318 match value.to_str().map(|v| v.split(';').next()) {
319 Ok(Some("application/x-www-form-urlencoded")) => {
322 Ok(Some("application/json")) => {
325 _ => bail!("unsupported content type {:?}", value.to_str()),
329 let body = TryStreamExt::map_err(req_body, |err| {
330 http_err!(BAD_REQUEST, "Problems reading request body: {}", err)
332 .try_fold(Vec::new(), |mut acc, chunk| async move {
333 // FIXME: max request body size?
334 if acc.len() + chunk.len() < 64 * 1024 {
335 acc.extend_from_slice(&*chunk);
338 Err(http_err!(BAD_REQUEST, "Request body too large"))
344 std::str::from_utf8(&body).map_err(|err| format_err!("Request body not uft8: {}", err))?;
347 let mut params: Value = serde_json::from_str(utf8_data)?;
348 for (k, v) in uri_param {
349 if let Some((_optional, prop_schema)) = param_schema.lookup(&k) {
350 params[&k] = parse_simple_value(&v, prop_schema)?;
353 verify_json_object(¶ms, ¶m_schema)?;
356 parse_query_parameters(param_schema, utf8_data, &parts, &uri_param)
360 struct NoLogExtension();
362 async fn proxy_protected_request(
363 info: &'static ApiMethod,
366 peer: &std::net::SocketAddr,
367 ) -> Result<Response<Body>, Error> {
368 let mut uri_parts = parts.uri.clone().into_parts();
370 uri_parts.scheme = Some(http::uri::Scheme::HTTP);
371 uri_parts.authority = Some(http::uri::Authority::from_static("127.0.0.1:82"));
372 let new_uri = http::Uri::from_parts(uri_parts).unwrap();
376 let mut request = Request::from_parts(parts, req_body);
377 request.headers_mut().insert(
379 format!("for=\"{}\";", peer).parse().unwrap(),
382 let reload_timezone = info.reload_timezone;
384 let resp = hyper::client::Client::new()
386 .map_err(Error::from)
388 resp.extensions_mut().insert(NoLogExtension());
402 pub async fn handle_api_request<Env: RpcEnvironment, S: 'static + BuildHasher + Send>(
404 info: &'static ApiMethod,
405 formatter: &'static OutputFormatter,
408 uri_param: HashMap<String, String, S>,
409 ) -> Result<Response<Body>, Error> {
410 let delay_unauth_time = std::time::Instant::now() + std::time::Duration::from_millis(3000);
411 let compression = extract_compression_method(&parts.headers);
413 let result = match info.handler {
414 ApiHandler::AsyncHttp(handler) => {
415 let params = parse_query_parameters(info.parameters, "", &parts, &uri_param)?;
416 (handler)(parts, req_body, params, info, Box::new(rpcenv)).await
418 ApiHandler::Sync(handler) => {
420 get_request_parameters(info.parameters, parts, req_body, uri_param).await?;
421 (handler)(params, info, &mut rpcenv).map(|data| (formatter.format_data)(data, &rpcenv))
423 ApiHandler::Async(handler) => {
425 get_request_parameters(info.parameters, parts, req_body, uri_param).await?;
426 (handler)(params, info, &mut rpcenv)
428 .map(|data| (formatter.format_data)(data, &rpcenv))
432 let mut resp = match result {
435 if let Some(httperr) = err.downcast_ref::<HttpError>() {
436 if httperr.code == StatusCode::UNAUTHORIZED {
437 tokio::time::sleep_until(Instant::from_std(delay_unauth_time)).await;
440 (formatter.format_error)(err)
444 let resp = match compression {
445 Some(CompressionMethod::Deflate) => {
446 resp.headers_mut().insert(
447 header::CONTENT_ENCODING,
448 CompressionMethod::Deflate.content_encoding(),
451 Body::wrap_stream(DeflateEncoder::with_quality(
452 TryStreamExt::map_err(body, |err| {
453 proxmox::io_format_err!("error during compression: {}", err)
462 if info.reload_timezone {
472 userid: Option<Userid>,
473 csrf_token: Option<String>,
474 language: Option<String>,
475 api: &Arc<ApiConfig>,
477 ) -> Response<Body> {
478 let nodename = proxmox::tools::nodename();
479 let user = userid.as_ref().map(|u| u.as_str()).unwrap_or("");
481 let csrf_token = csrf_token.unwrap_or_else(|| String::from(""));
483 let mut debug = false;
484 let mut template_file = "index";
486 if let Some(query_str) = parts.uri.query() {
487 for (k, v) in form_urlencoded::parse(query_str.as_bytes()).into_owned() {
488 if k == "debug" && v != "0" && v != "false" {
490 } else if k == "console" {
491 template_file = "console";
496 let mut lang = String::from("");
497 if let Some(language) = language {
498 if Path::new(&format!("/usr/share/pbs-i18n/pbs-lang-{}.js", language)).exists() {
504 "NodeName": nodename,
506 "CSRFPreventionToken": csrf_token,
511 let (ct, index) = match api.render_template(template_file, &data) {
512 Ok(index) => ("text/html", index),
513 Err(err) => ("text/plain", format!("Error rendering template: {}", err)),
516 let mut resp = Response::builder()
517 .status(StatusCode::OK)
518 .header(header::CONTENT_TYPE, ct)
522 if let Some(userid) = userid {
523 resp.extensions_mut().insert(Authid::from((userid, None)));
529 fn extension_to_content_type(filename: &Path) -> (&'static str, bool) {
530 if let Some(ext) = filename.extension().and_then(|osstr| osstr.to_str()) {
532 "css" => ("text/css", false),
533 "html" => ("text/html", false),
534 "js" => ("application/javascript", false),
535 "json" => ("application/json", false),
536 "map" => ("application/json", false),
537 "png" => ("image/png", true),
538 "ico" => ("image/x-icon", true),
539 "gif" => ("image/gif", true),
540 "svg" => ("image/svg+xml", false),
541 "jar" => ("application/java-archive", true),
542 "woff" => ("application/font-woff", true),
543 "woff2" => ("application/font-woff2", true),
544 "ttf" => ("application/font-snft", true),
545 "pdf" => ("application/pdf", true),
546 "epub" => ("application/epub+zip", true),
547 "mp3" => ("audio/mpeg", true),
548 "oga" => ("audio/ogg", true),
549 "tgz" => ("application/x-compressed-tar", true),
550 _ => ("application/octet-stream", false),
554 ("application/octet-stream", false)
557 async fn simple_static_file_download(
559 content_type: &'static str,
560 compression: Option<CompressionMethod>,
561 ) -> Result<Response<Body>, Error> {
562 use tokio::io::AsyncReadExt;
564 let mut file = File::open(filename)
566 .map_err(|err| http_err!(BAD_REQUEST, "File open failed: {}", err))?;
568 let mut data: Vec<u8> = Vec::new();
570 let mut response = match compression {
571 Some(CompressionMethod::Deflate) => {
572 let mut enc = DeflateEncoder::with_quality(data, Level::Default);
573 enc.compress_vec(&mut file, CHUNK_SIZE_LIMIT as usize)
575 let mut response = Response::new(enc.into_inner().into());
576 response.headers_mut().insert(
577 header::CONTENT_ENCODING,
578 CompressionMethod::Deflate.content_encoding(),
583 file.read_to_end(&mut data)
585 .map_err(|err| http_err!(BAD_REQUEST, "File read failed: {}", err))?;
586 Response::new(data.into())
590 response.headers_mut().insert(
591 header::CONTENT_TYPE,
592 header::HeaderValue::from_static(content_type),
598 async fn chuncked_static_file_download(
600 content_type: &'static str,
601 compression: Option<CompressionMethod>,
602 ) -> Result<Response<Body>, Error> {
603 let mut resp = Response::builder()
604 .status(StatusCode::OK)
605 .header(header::CONTENT_TYPE, content_type);
607 let file = File::open(filename)
609 .map_err(|err| http_err!(BAD_REQUEST, "File open failed: {}", err))?;
611 let body = match compression {
612 Some(CompressionMethod::Deflate) => {
614 header::CONTENT_ENCODING,
615 CompressionMethod::Deflate.content_encoding(),
617 Body::wrap_stream(DeflateEncoder::with_quality(
618 AsyncReaderStream::new(file),
622 None => Body::wrap_stream(AsyncReaderStream::new(file)),
625 Ok(resp.body(body).unwrap())
628 async fn handle_static_file_download(
630 compression: Option<CompressionMethod>,
631 ) -> Result<Response<Body>, Error> {
632 let metadata = tokio::fs::metadata(filename.clone())
633 .map_err(|err| http_err!(BAD_REQUEST, "File access problems: {}", err))
636 let (content_type, nocomp) = extension_to_content_type(&filename);
637 let compression = if nocomp { None } else { compression };
639 if metadata.len() < CHUNK_SIZE_LIMIT {
640 simple_static_file_download(filename, content_type, compression).await
642 chuncked_static_file_download(filename, content_type, compression).await
646 fn extract_lang_header(headers: &http::HeaderMap) -> Option<String> {
647 if let Some(Ok(cookie)) = headers.get("COOKIE").map(|v| v.to_str()) {
648 return tools::extract_cookie(cookie, "PBSLangCookie");
653 // FIXME: support handling multiple compression methods
654 fn extract_compression_method(headers: &http::HeaderMap) -> Option<CompressionMethod> {
655 if let Some(Ok(encodings)) = headers.get(header::ACCEPT_ENCODING).map(|v| v.to_str()) {
656 for encoding in encodings.split(&[',', ' '][..]) {
657 if let Ok(method) = encoding.parse() {
665 async fn handle_request(
668 peer: &std::net::SocketAddr,
669 ) -> Result<Response<Body>, Error> {
670 let (parts, body) = req.into_parts();
671 let method = parts.method.clone();
672 let (path, components) = tools::normalize_uri_path(parts.uri.path())?;
674 let comp_len = components.len();
676 let query = parts.uri.query().unwrap_or_default();
677 if path.len() + query.len() > MAX_URI_QUERY_LENGTH {
678 return Ok(Response::builder()
679 .status(StatusCode::URI_TOO_LONG)
684 let env_type = api.env_type();
685 let mut rpcenv = RestEnvironment::new(env_type);
687 rpcenv.set_client_ip(Some(*peer));
689 let auth = &api.api_auth;
691 let delay_unauth_time = std::time::Instant::now() + std::time::Duration::from_millis(3000);
692 let access_forbidden_time = std::time::Instant::now() + std::time::Duration::from_millis(500);
694 if comp_len >= 1 && components[0] == "api2" {
696 let format = components[1];
698 let formatter = match format {
699 "json" => &JSON_FORMATTER,
700 "extjs" => &EXTJS_FORMATTER,
701 _ => bail!("Unsupported output format '{}'.", format),
704 let mut uri_param = HashMap::new();
705 let api_method = api.find_method(&components[2..], method.clone(), &mut uri_param);
707 let mut auth_required = true;
708 if let Some(api_method) = api_method {
709 if let Permission::World = *api_method.access.permission {
710 auth_required = false; // no auth for endpoints with World permission
715 match auth.check_auth(&parts.headers, &method) {
716 Ok(authid) => rpcenv.set_auth_id(Some(authid)),
718 let err = match auth_err {
719 AuthError::Generic(err) => err,
720 AuthError::NoData => {
721 format_err!("no authentication credentials provided.")
724 let peer = peer.ip();
725 auth_logger()?.log(format!(
726 "authentication failure; rhost={} msg={}",
730 // always delay unauthorized calls by 3 seconds (from start of request)
731 let err = http_err!(UNAUTHORIZED, "authentication failed - {}", err);
732 tokio::time::sleep_until(Instant::from_std(delay_unauth_time)).await;
733 return Ok((formatter.format_error)(err));
740 let err = http_err!(NOT_FOUND, "Path '{}' not found.", path);
741 return Ok((formatter.format_error)(err));
743 Some(api_method) => {
744 let auth_id = rpcenv.get_auth_id();
745 let user_info = CachedUserInfo::new()?;
747 if !check_api_permission(
748 api_method.access.permission,
753 let err = http_err!(FORBIDDEN, "permission check failed");
754 tokio::time::sleep_until(Instant::from_std(access_forbidden_time)).await;
755 return Ok((formatter.format_error)(err));
758 let result = if api_method.protected && env_type == RpcEnvironmentType::PUBLIC {
759 proxy_protected_request(api_method, parts, body, peer).await
761 handle_api_request(rpcenv, api_method, formatter, parts, body, uri_param)
765 let mut response = match result {
767 Err(err) => (formatter.format_error)(err),
770 if let Some(auth_id) = auth_id {
771 let auth_id: Authid = auth_id.parse()?;
772 response.extensions_mut().insert(auth_id);
780 // not Auth required for accessing files!
782 if method != hyper::Method::GET {
783 bail!("Unsupported HTTP method {}", method);
787 let language = extract_lang_header(&parts.headers);
788 match auth.check_auth(&parts.headers, &method) {
790 let auth_id: Authid = auth_id.parse()?;
791 if !auth_id.is_token() {
792 let userid = auth_id.user();
793 let new_csrf_token = assemble_csrf_prevention_token(csrf_secret(), userid);
795 Some(userid.clone()),
796 Some(new_csrf_token),
803 Err(AuthError::Generic(_)) => {
804 tokio::time::sleep_until(Instant::from_std(delay_unauth_time)).await;
806 Err(AuthError::NoData) => {}
808 return Ok(get_index(None, None, language, &api, parts));
810 let filename = api.find_alias(&components);
811 let compression = extract_compression_method(&parts.headers);
812 return handle_static_file_download(filename, compression).await;
816 Err(http_err!(NOT_FOUND, "Path '{}' not found.", path))