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
::Value
;
20 use tokio
::time
::Instant
;
21 use url
::form_urlencoded
;
22 use tower_service
::Service
;
24 use proxmox
::api
::schema
::{
25 parse_parameter_strings
, parse_simple_value
, verify_json_object
, ObjectSchemaType
,
29 check_api_permission
, ApiHandler
, ApiMethod
, HttpError
, Permission
, RpcEnvironment
,
30 RpcEnvironmentType
, UserInformation
,
32 use proxmox
::http_err
;
34 use pbs_tools
::compression
::{DeflateEncoder, Level}
;
35 use pbs_tools
::stream
::AsyncReaderStream
;
38 ApiConfig
, FileLogger
, AuthError
, RestEnvironment
, CompressionMethod
,
39 extract_cookie
, normalize_uri_path
, formatter
::*,
46 struct AuthStringExtension(String
);
48 struct EmptyUserInformation {}
50 impl UserInformation
for EmptyUserInformation
{
51 fn is_superuser(&self, _userid
: &str) -> bool { false }
52 fn is_group_member(&self, _userid
: &str, _group
: &str) -> bool { false }
53 fn lookup_privs(&self, _userid
: &str, _path
: &[&str]) -> u64 { 0 }
56 /// REST server implementation (configured with [ApiConfig])
58 /// This struct implements the [Service] trait in order to use it with
59 /// [hyper::server::Builder::serve].
60 pub struct RestServer
{
61 api_config
: Arc
<ApiConfig
>,
64 const MAX_URI_QUERY_LENGTH
: usize = 3072;
65 const CHUNK_SIZE_LIMIT
: u64 = 32 * 1024;
68 /// Creates a new instance.
69 pub fn new(api_config
: ApiConfig
) -> Self {
71 api_config
: Arc
::new(api_config
),
76 impl Service
<&Pin
<Box
<tokio_openssl
::SslStream
<tokio
::net
::TcpStream
>>>>
79 type Response
= ApiService
;
81 type Future
= Pin
<Box
<dyn Future
<Output
= Result
<ApiService
, Error
>> + Send
>>;
83 fn poll_ready(&mut self, _cx
: &mut Context
) -> Poll
<Result
<(), Self::Error
>> {
89 ctx
: &Pin
<Box
<tokio_openssl
::SslStream
<tokio
::net
::TcpStream
>>>,
91 match ctx
.get_ref().peer_addr() {
92 Err(err
) => future
::err(format_err
!("unable to get peer address - {}", err
)).boxed(),
93 Ok(peer
) => future
::ok(ApiService
{
95 api_config
: self.api_config
.clone(),
102 impl Service
<&hyper
::server
::conn
::AddrStream
> for RestServer
{
103 type Response
= ApiService
;
105 type Future
= Pin
<Box
<dyn Future
<Output
= Result
<ApiService
, Error
>> + Send
>>;
107 fn poll_ready(&mut self, _cx
: &mut Context
) -> Poll
<Result
<(), Self::Error
>> {
111 fn call(&mut self, ctx
: &hyper
::server
::conn
::AddrStream
) -> Self::Future
{
112 let peer
= ctx
.remote_addr();
113 future
::ok(ApiService
{
115 api_config
: self.api_config
.clone(),
121 impl Service
<&tokio
::net
::UnixStream
> for RestServer
{
122 type Response
= ApiService
;
124 type Future
= Pin
<Box
<dyn Future
<Output
= Result
<ApiService
, Error
>> + Send
>>;
126 fn poll_ready(&mut self, _cx
: &mut Context
) -> Poll
<Result
<(), Self::Error
>> {
130 fn call(&mut self, _ctx
: &tokio
::net
::UnixStream
) -> Self::Future
{
131 // TODO: Find a way to actually represent the vsock peer in the ApiService struct - for now
132 // it doesn't really matter, so just use a fake IP address
133 let fake_peer
= "0.0.0.0:807".parse().unwrap();
134 future
::ok(ApiService
{
136 api_config
: self.api_config
.clone(),
142 pub struct ApiService
{
143 pub peer
: std
::net
::SocketAddr
,
144 pub api_config
: Arc
<ApiConfig
>,
148 logfile
: Option
<&Arc
<Mutex
<FileLogger
>>>,
149 peer
: &std
::net
::SocketAddr
,
150 method
: hyper
::Method
,
152 resp
: &Response
<Body
>,
153 user_agent
: Option
<String
>,
155 if resp
.extensions().get
::<NoLogExtension
>().is_some() {
159 // we also log URL-to-long requests, so avoid message bigger than PIPE_BUF (4k on Linux)
160 // to profit from atomicty guarantees for O_APPEND opened logfiles
161 let path
= &path_query
[..MAX_URI_QUERY_LENGTH
.min(path_query
.len())];
163 let status
= resp
.status();
164 if !(status
.is_success() || status
.is_informational()) {
165 let reason
= status
.canonical_reason().unwrap_or("unknown reason");
167 let message
= match resp
.extensions().get
::<ErrorMessageExtension
>() {
168 Some(data
) => &data
.0,
169 None
=> "request failed",
173 "{} {}: {} {}: [client {}] {}",
182 if let Some(logfile
) = logfile
{
183 let auth_id
= match resp
.extensions().get
::<AuthStringExtension
>() {
184 Some(AuthStringExtension(auth_id
)) => auth_id
.clone(),
185 None
=> "-".to_string(),
187 let now
= proxmox
::tools
::time
::epoch_i64();
188 // time format which apache/nginx use (by default), copied from pve-http-server
189 let datetime
= proxmox
::tools
::time
::strftime_local("%d/%m/%Y:%H:%M:%S %z", now
)
190 .unwrap_or_else(|_
| "-".to_string());
192 logfile
.lock().unwrap().log(format
!(
193 "{} - {} [{}] \"{} {}\" {} {} {}",
200 resp
.body().size_hint().lower(),
201 user_agent
.unwrap_or_else(|| "-".to_string()),
206 fn get_proxied_peer(headers
: &HeaderMap
) -> Option
<std
::net
::SocketAddr
> {
208 static ref RE
: Regex
= Regex
::new(r
#"for="([^"]+)""#).unwrap();
210 let forwarded = headers.get(header::FORWARDED)?.to_str().ok()?;
211 let capture = RE.captures(&forwarded)?;
212 let rhost = capture.get(1)?.as_str();
217 fn get_user_agent(headers: &HeaderMap) -> Option<String> {
218 let agent = headers.get(header::USER_AGENT)?.to_str();
221 let mut s = s.to_owned();
228 impl Service<Request<Body>> for ApiService {
229 type Response = Response<Body>;
231 #[allow(clippy::type_complexity)]
232 type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
234 fn poll_ready(&mut self, _cx: &mut Context) -> Poll<Result<(), Self::Error>> {
238 fn call(&mut self, req: Request<Body>) -> Self::Future {
239 let path = req.uri().path_and_query().unwrap().as_str().to_owned();
240 let method = req.method().clone();
241 let user_agent = get_user_agent(req.headers());
243 let config = Arc::clone(&self.api_config);
244 let peer = match get_proxied_peer(req.headers()) {
245 Some(proxied_peer) => proxied_peer,
249 let response = match handle_request(Arc::clone(&config), req, &peer).await {
250 Ok(response) => response,
252 let (err, code) = match err.downcast_ref::<HttpError>() {
253 Some(apierr) => (apierr.message.clone(), apierr.code),
254 _ => (err.to_string(), StatusCode::BAD_REQUEST),
258 .extension(ErrorMessageExtension(err.to_string()))
262 let logger = config.get_access_log();
263 log_response(logger, &peer, method, &path, &response, user_agent);
270 fn parse_query_parameters<S: 'static + BuildHasher + Send>(
271 param_schema: ParameterSchema,
272 form: &str, // x-www-form-urlencoded body data
274 uri_param: &HashMap<String, String, S>,
275 ) -> Result<Value, Error> {
276 let mut param_list: Vec<(String, String)> = vec![];
278 if !form.is_empty() {
279 for (k, v) in form_urlencoded::parse(form.as_bytes()).into_owned() {
280 param_list.push((k, v));
284 if let Some(query_str) = parts.uri.query() {
285 for (k, v) in form_urlencoded::parse(query_str.as_bytes()).into_owned() {
288 } // skip extjs "disable cache" parameter
289 param_list.push((k, v));
293 for (k, v) in uri_param {
294 param_list.push((k.clone(), v.clone()));
297 let params = parse_parameter_strings(¶m_list, param_schema, true)?;
302 async fn get_request_parameters<S: 'static + BuildHasher + Send>(
303 param_schema: ParameterSchema,
306 uri_param: HashMap<String, String, S>,
307 ) -> Result<Value, Error> {
308 let mut is_json = false;
310 if let Some(value) = parts.headers.get(header::CONTENT_TYPE) {
311 match value.to_str().map(|v| v.split(';').next()) {
312 Ok(Some("application/x-www-form-urlencoded")) => {
315 Ok(Some("application/json")) => {
318 _ => bail!("unsupported content type {:?}", value.to_str()),
322 let body = TryStreamExt::map_err(req_body, |err| {
323 http_err!(BAD_REQUEST, "Problems reading request body: {}", err)
325 .try_fold(Vec::new(), |mut acc, chunk| async move {
326 // FIXME: max request body size?
327 if acc.len() + chunk.len() < 64 * 1024 {
328 acc.extend_from_slice(&*chunk);
331 Err(http_err!(BAD_REQUEST, "Request body too large"))
337 std::str::from_utf8(&body).map_err(|err| format_err!("Request body not uft8: {}", err))?;
340 let mut params: Value = serde_json::from_str(utf8_data)?;
341 for (k, v) in uri_param {
342 if let Some((_optional, prop_schema)) = param_schema.lookup(&k) {
343 params[&k] = parse_simple_value(&v, prop_schema)?;
346 verify_json_object(¶ms, ¶m_schema)?;
349 parse_query_parameters(param_schema, utf8_data, &parts, &uri_param)
353 struct NoLogExtension();
355 async fn proxy_protected_request(
356 info: &'static ApiMethod,
359 peer: &std::net::SocketAddr,
360 ) -> Result<Response<Body>, Error> {
361 let mut uri_parts = parts.uri.clone().into_parts();
363 uri_parts.scheme = Some(http::uri::Scheme::HTTP);
364 uri_parts.authority = Some(http::uri::Authority::from_static("127.0.0.1:82"));
365 let new_uri = http::Uri::from_parts(uri_parts).unwrap();
369 let mut request = Request::from_parts(parts, req_body);
370 request.headers_mut().insert(
372 format!("for=\"{}\";", peer).parse().unwrap(),
375 let reload_timezone = info.reload_timezone;
377 let resp = hyper::client::Client::new()
379 .map_err(Error::from)
381 resp.extensions_mut().insert(NoLogExtension());
395 pub(crate) async fn handle_api_request<Env: RpcEnvironment, S: 'static + BuildHasher + Send>(
397 info: &'static ApiMethod,
398 formatter: &'static dyn OutputFormatter,
401 uri_param: HashMap<String, String, S>,
402 ) -> Result<Response<Body>, Error> {
403 let delay_unauth_time = std::time::Instant::now() + std::time::Duration::from_millis(3000);
404 let compression = extract_compression_method(&parts.headers);
406 let result = match info.handler {
407 ApiHandler::AsyncHttp(handler) => {
408 let params = parse_query_parameters(info.parameters, "", &parts, &uri_param)?;
409 (handler)(parts, req_body, params, info, Box::new(rpcenv)).await
411 ApiHandler::Sync(handler) => {
413 get_request_parameters(info.parameters, parts, req_body, uri_param).await?;
414 (handler)(params, info, &mut rpcenv).map(|data| formatter.format_data(data, &rpcenv))
416 ApiHandler::Async(handler) => {
418 get_request_parameters(info.parameters, parts, req_body, uri_param).await?;
419 (handler)(params, info, &mut rpcenv)
421 .map(|data| formatter.format_data(data, &rpcenv))
425 let mut resp = match result {
428 if let Some(httperr) = err.downcast_ref::<HttpError>() {
429 if httperr.code == StatusCode::UNAUTHORIZED {
430 tokio::time::sleep_until(Instant::from_std(delay_unauth_time)).await;
433 formatter.format_error(err)
437 let resp = match compression {
438 Some(CompressionMethod::Deflate) => {
439 resp.headers_mut().insert(
440 header::CONTENT_ENCODING,
441 CompressionMethod::Deflate.content_encoding(),
444 Body::wrap_stream(DeflateEncoder::with_quality(
445 TryStreamExt::map_err(body, |err| {
446 proxmox::io_format_err!("error during compression: {}", err)
455 if info.reload_timezone {
465 fn extension_to_content_type(filename: &Path) -> (&'static str, bool) {
466 if let Some(ext) = filename.extension().and_then(|osstr| osstr.to_str()) {
468 "css" => ("text/css", false),
469 "html" => ("text/html", false),
470 "js" => ("application/javascript", false),
471 "json" => ("application/json", false),
472 "map" => ("application/json", false),
473 "png" => ("image/png", true),
474 "ico" => ("image/x-icon", true),
475 "gif" => ("image/gif", true),
476 "svg" => ("image/svg+xml", false),
477 "jar" => ("application/java-archive", true),
478 "woff" => ("application/font-woff", true),
479 "woff2" => ("application/font-woff2", true),
480 "ttf" => ("application/font-snft", true),
481 "pdf" => ("application/pdf", true),
482 "epub" => ("application/epub+zip", true),
483 "mp3" => ("audio/mpeg", true),
484 "oga" => ("audio/ogg", true),
485 "tgz" => ("application/x-compressed-tar", true),
486 _ => ("application/octet-stream", false),
490 ("application/octet-stream", false)
493 async fn simple_static_file_download(
495 content_type: &'static str,
496 compression: Option<CompressionMethod>,
497 ) -> Result<Response<Body>, Error> {
498 use tokio::io::AsyncReadExt;
500 let mut file = File::open(filename)
502 .map_err(|err| http_err!(BAD_REQUEST, "File open failed: {}", err))?;
504 let mut data: Vec<u8> = Vec::new();
506 let mut response = match compression {
507 Some(CompressionMethod::Deflate) => {
508 let mut enc = DeflateEncoder::with_quality(data, Level::Default);
509 enc.compress_vec(&mut file, CHUNK_SIZE_LIMIT as usize)
511 let mut response = Response::new(enc.into_inner().into());
512 response.headers_mut().insert(
513 header::CONTENT_ENCODING,
514 CompressionMethod::Deflate.content_encoding(),
519 file.read_to_end(&mut data)
521 .map_err(|err| http_err!(BAD_REQUEST, "File read failed: {}", err))?;
522 Response::new(data.into())
526 response.headers_mut().insert(
527 header::CONTENT_TYPE,
528 header::HeaderValue::from_static(content_type),
534 async fn chuncked_static_file_download(
536 content_type: &'static str,
537 compression: Option<CompressionMethod>,
538 ) -> Result<Response<Body>, Error> {
539 let mut resp = Response::builder()
540 .status(StatusCode::OK)
541 .header(header::CONTENT_TYPE, content_type);
543 let file = File::open(filename)
545 .map_err(|err| http_err!(BAD_REQUEST, "File open failed: {}", err))?;
547 let body = match compression {
548 Some(CompressionMethod::Deflate) => {
550 header::CONTENT_ENCODING,
551 CompressionMethod::Deflate.content_encoding(),
553 Body::wrap_stream(DeflateEncoder::with_quality(
554 AsyncReaderStream::new(file),
558 None => Body::wrap_stream(AsyncReaderStream::new(file)),
561 Ok(resp.body(body).unwrap())
564 async fn handle_static_file_download(
566 compression: Option<CompressionMethod>,
567 ) -> Result<Response<Body>, Error> {
568 let metadata = tokio::fs::metadata(filename.clone())
569 .map_err(|err| http_err!(BAD_REQUEST, "File access problems: {}", err))
572 let (content_type, nocomp) = extension_to_content_type(&filename);
573 let compression = if nocomp { None } else { compression };
575 if metadata.len() < CHUNK_SIZE_LIMIT {
576 simple_static_file_download(filename, content_type, compression).await
578 chuncked_static_file_download(filename, content_type, compression).await
582 fn extract_lang_header(headers: &http::HeaderMap) -> Option<String> {
583 if let Some(Ok(cookie)) = headers.get("COOKIE").map(|v| v.to_str()) {
584 return extract_cookie(cookie, "PBSLangCookie");
589 // FIXME: support handling multiple compression methods
590 fn extract_compression_method(headers: &http::HeaderMap) -> Option<CompressionMethod> {
591 if let Some(Ok(encodings)) = headers.get(header::ACCEPT_ENCODING).map(|v| v.to_str()) {
592 for encoding in encodings.split(&[',', ' '][..]) {
593 if let Ok(method) = encoding.parse() {
601 async fn handle_request(
604 peer: &std::net::SocketAddr,
605 ) -> Result<Response<Body>, Error> {
606 let (parts, body) = req.into_parts();
607 let method = parts.method.clone();
608 let (path, components) = normalize_uri_path(parts.uri.path())?;
610 let comp_len = components.len();
612 let query = parts.uri.query().unwrap_or_default();
613 if path.len() + query.len() > MAX_URI_QUERY_LENGTH {
614 return Ok(Response::builder()
615 .status(StatusCode::URI_TOO_LONG)
620 let env_type = api.env_type();
621 let mut rpcenv = RestEnvironment::new(env_type, Arc::clone(&api));
623 rpcenv.set_client_ip(Some(*peer));
625 let auth = &api.api_auth;
627 let delay_unauth_time = std::time::Instant::now() + std::time::Duration::from_millis(3000);
628 let access_forbidden_time = std::time::Instant::now() + std::time::Duration::from_millis(500);
630 if comp_len >= 1 && components[0] == "api2" {
632 let format = components[1];
634 let formatter: &dyn OutputFormatter = match format {
635 "json" => JSON_FORMATTER,
636 "extjs" => EXTJS_FORMATTER,
637 _ => bail!("Unsupported output format '{}'.", format),
640 let mut uri_param = HashMap::new();
641 let api_method = api.find_method(&components[2..], method.clone(), &mut uri_param);
643 let mut auth_required = true;
644 if let Some(api_method) = api_method {
645 if let Permission::World = *api_method.access.permission {
646 auth_required = false; // no auth for endpoints with World permission
650 let mut user_info: Box<dyn UserInformation + Send + Sync> = Box::new(EmptyUserInformation {});
653 match auth.check_auth(&parts.headers, &method) {
654 Ok((authid, info)) => {
655 rpcenv.set_auth_id(Some(authid));
659 let err = match auth_err {
660 AuthError::Generic(err) => err,
661 AuthError::NoData => {
662 format_err!("no authentication credentials provided.")
665 // fixme: log Username??
666 rpcenv.log_failed_auth(None, &err.to_string());
668 // always delay unauthorized calls by 3 seconds (from start of request)
669 let err = http_err!(UNAUTHORIZED, "authentication failed - {}", err);
670 tokio::time::sleep_until(Instant::from_std(delay_unauth_time)).await;
671 return Ok(formatter.format_error(err));
678 let err = http_err!(NOT_FOUND, "Path '{}' not found.", path);
679 return Ok(formatter.format_error(err));
681 Some(api_method) => {
682 let auth_id = rpcenv.get_auth_id();
683 let user_info = user_info;
685 if !check_api_permission(
686 api_method.access.permission,
691 let err = http_err!(FORBIDDEN, "permission check failed");
692 tokio::time::sleep_until(Instant::from_std(access_forbidden_time)).await;
693 return Ok(formatter.format_error(err));
696 let result = if api_method.protected && env_type == RpcEnvironmentType::PUBLIC {
697 proxy_protected_request(api_method, parts, body, peer).await
699 handle_api_request(rpcenv, api_method, formatter, parts, body, uri_param)
703 let mut response = match result {
705 Err(err) => formatter.format_error(err),
708 if let Some(auth_id) = auth_id {
709 response.extensions_mut().insert(AuthStringExtension(auth_id));
717 // not Auth required for accessing files!
719 if method != hyper::Method::GET {
720 bail!("Unsupported HTTP method {}", method);
724 let language = extract_lang_header(&parts.headers);
725 match auth.check_auth(&parts.headers, &method) {
726 Ok((auth_id, _user_info)) => {
727 return Ok(api.get_index(Some(auth_id), language, parts));
729 Err(AuthError::Generic(_)) => {
730 tokio::time::sleep_until(Instant::from_std(delay_unauth_time)).await;
732 Err(AuthError::NoData) => {}
734 return Ok(api.get_index(None, language, parts));
736 let filename = api.find_alias(&components);
737 let compression = extract_compression_method(&parts.headers);
738 return handle_static_file_download(filename, compression).await;
742 Err(http_err!(NOT_FOUND, "Path '{}' not found.", path))