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
;
25 check_api_permission
, ApiHandler
, ApiMethod
, HttpError
, Permission
, RpcEnvironment
,
26 RpcEnvironmentType
, UserInformation
,
28 use proxmox_router
::http_err
;
30 parse_parameter_strings
, parse_simple_value
, verify_json_object
, ObjectSchemaType
,
34 use pbs_tools
::compression
::{DeflateEncoder, Level}
;
35 use pbs_tools
::stream
::AsyncReaderStream
;
38 ApiConfig
, FileLogger
, AuthError
, RestEnvironment
, CompressionMethod
,
39 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 // Helper [Service] containing the peer Address
144 // The lower level connection [Service] implementation on
145 // [RestServer] extracts the peer address and return an [ApiService].
147 // Rust wants this type 'pub' here (else we get 'private type `ApiService`
148 // in public interface'). The type is still private because the crate does
150 pub struct ApiService
{
151 pub peer
: std
::net
::SocketAddr
,
152 pub api_config
: Arc
<ApiConfig
>,
156 logfile
: Option
<&Arc
<Mutex
<FileLogger
>>>,
157 peer
: &std
::net
::SocketAddr
,
158 method
: hyper
::Method
,
160 resp
: &Response
<Body
>,
161 user_agent
: Option
<String
>,
163 if resp
.extensions().get
::<NoLogExtension
>().is_some() {
167 // we also log URL-to-long requests, so avoid message bigger than PIPE_BUF (4k on Linux)
168 // to profit from atomicty guarantees for O_APPEND opened logfiles
169 let path
= &path_query
[..MAX_URI_QUERY_LENGTH
.min(path_query
.len())];
171 let status
= resp
.status();
172 if !(status
.is_success() || status
.is_informational()) {
173 let reason
= status
.canonical_reason().unwrap_or("unknown reason");
175 let message
= match resp
.extensions().get
::<ErrorMessageExtension
>() {
176 Some(data
) => &data
.0,
177 None
=> "request failed",
181 "{} {}: {} {}: [client {}] {}",
190 if let Some(logfile
) = logfile
{
191 let auth_id
= match resp
.extensions().get
::<AuthStringExtension
>() {
192 Some(AuthStringExtension(auth_id
)) => auth_id
.clone(),
193 None
=> "-".to_string(),
195 let now
= proxmox_time
::epoch_i64();
196 // time format which apache/nginx use (by default), copied from pve-http-server
197 let datetime
= proxmox_time
::strftime_local("%d/%m/%Y:%H:%M:%S %z", now
)
198 .unwrap_or_else(|_
| "-".to_string());
200 logfile
.lock().unwrap().log(format
!(
201 "{} - {} [{}] \"{} {}\" {} {} {}",
208 resp
.body().size_hint().lower(),
209 user_agent
.unwrap_or_else(|| "-".to_string()),
214 fn get_proxied_peer(headers
: &HeaderMap
) -> Option
<std
::net
::SocketAddr
> {
216 static ref RE
: Regex
= Regex
::new(r
#"for="([^"]+)""#).unwrap();
218 let forwarded = headers.get(header::FORWARDED)?.to_str().ok()?;
219 let capture = RE.captures(&forwarded)?;
220 let rhost = capture.get(1)?.as_str();
225 fn get_user_agent(headers: &HeaderMap) -> Option<String> {
226 let agent = headers.get(header::USER_AGENT)?.to_str();
229 let mut s = s.to_owned();
236 impl Service<Request<Body>> for ApiService {
237 type Response = Response<Body>;
239 #[allow(clippy::type_complexity)]
240 type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
242 fn poll_ready(&mut self, _cx: &mut Context) -> Poll<Result<(), Self::Error>> {
246 fn call(&mut self, req: Request<Body>) -> Self::Future {
247 let path = req.uri().path_and_query().unwrap().as_str().to_owned();
248 let method = req.method().clone();
249 let user_agent = get_user_agent(req.headers());
251 let config = Arc::clone(&self.api_config);
252 let peer = match get_proxied_peer(req.headers()) {
253 Some(proxied_peer) => proxied_peer,
257 let response = match handle_request(Arc::clone(&config), req, &peer).await {
258 Ok(response) => response,
260 let (err, code) = match err.downcast_ref::<HttpError>() {
261 Some(apierr) => (apierr.message.clone(), apierr.code),
262 _ => (err.to_string(), StatusCode::BAD_REQUEST),
266 .extension(ErrorMessageExtension(err.to_string()))
270 let logger = config.get_access_log();
271 log_response(logger, &peer, method, &path, &response, user_agent);
278 fn parse_query_parameters<S: 'static + BuildHasher + Send>(
279 param_schema: ParameterSchema,
280 form: &str, // x-www-form-urlencoded body data
282 uri_param: &HashMap<String, String, S>,
283 ) -> Result<Value, Error> {
284 let mut param_list: Vec<(String, String)> = vec![];
286 if !form.is_empty() {
287 for (k, v) in form_urlencoded::parse(form.as_bytes()).into_owned() {
288 param_list.push((k, v));
292 if let Some(query_str) = parts.uri.query() {
293 for (k, v) in form_urlencoded::parse(query_str.as_bytes()).into_owned() {
296 } // skip extjs "disable cache" parameter
297 param_list.push((k, v));
301 for (k, v) in uri_param {
302 param_list.push((k.clone(), v.clone()));
305 let params = parse_parameter_strings(¶m_list, param_schema, true)?;
310 async fn get_request_parameters<S: 'static + BuildHasher + Send>(
311 param_schema: ParameterSchema,
314 uri_param: HashMap<String, String, S>,
315 ) -> Result<Value, Error> {
316 let mut is_json = false;
318 if let Some(value) = parts.headers.get(header::CONTENT_TYPE) {
319 match value.to_str().map(|v| v.split(';').next()) {
320 Ok(Some("application/x-www-form-urlencoded")) => {
323 Ok(Some("application/json")) => {
326 _ => bail!("unsupported content type {:?}", value.to_str()),
330 let body = TryStreamExt::map_err(req_body, |err| {
331 http_err!(BAD_REQUEST, "Problems reading request body: {}", err)
333 .try_fold(Vec::new(), |mut acc, chunk| async move {
334 // FIXME: max request body size?
335 if acc.len() + chunk.len() < 64 * 1024 {
336 acc.extend_from_slice(&*chunk);
339 Err(http_err!(BAD_REQUEST, "Request body too large"))
345 std::str::from_utf8(&body).map_err(|err| format_err!("Request body not uft8: {}", err))?;
348 let mut params: Value = serde_json::from_str(utf8_data)?;
349 for (k, v) in uri_param {
350 if let Some((_optional, prop_schema)) = param_schema.lookup(&k) {
351 params[&k] = parse_simple_value(&v, prop_schema)?;
354 verify_json_object(¶ms, ¶m_schema)?;
357 parse_query_parameters(param_schema, utf8_data, &parts, &uri_param)
361 struct NoLogExtension();
363 async fn proxy_protected_request(
364 info: &'static ApiMethod,
367 peer: &std::net::SocketAddr,
368 ) -> Result<Response<Body>, Error> {
369 let mut uri_parts = parts.uri.clone().into_parts();
371 uri_parts.scheme = Some(http::uri::Scheme::HTTP);
372 uri_parts.authority = Some(http::uri::Authority::from_static("127.0.0.1:82"));
373 let new_uri = http::Uri::from_parts(uri_parts).unwrap();
377 let mut request = Request::from_parts(parts, req_body);
378 request.headers_mut().insert(
380 format!("for=\"{}\";", peer).parse().unwrap(),
383 let reload_timezone = info.reload_timezone;
385 let resp = hyper::client::Client::new()
387 .map_err(Error::from)
389 resp.extensions_mut().insert(NoLogExtension());
403 pub(crate) async fn handle_api_request<Env: RpcEnvironment, S: 'static + BuildHasher + Send>(
405 info: &'static ApiMethod,
406 formatter: &'static dyn OutputFormatter,
409 uri_param: HashMap<String, String, S>,
410 ) -> Result<Response<Body>, Error> {
411 let delay_unauth_time = std::time::Instant::now() + std::time::Duration::from_millis(3000);
412 let compression = extract_compression_method(&parts.headers);
414 let result = match info.handler {
415 ApiHandler::AsyncHttp(handler) => {
416 let params = parse_query_parameters(info.parameters, "", &parts, &uri_param)?;
417 (handler)(parts, req_body, params, info, Box::new(rpcenv)).await
419 ApiHandler::Sync(handler) => {
421 get_request_parameters(info.parameters, parts, req_body, uri_param).await?;
422 (handler)(params, info, &mut rpcenv).map(|data| formatter.format_data(data, &rpcenv))
424 ApiHandler::Async(handler) => {
426 get_request_parameters(info.parameters, parts, req_body, uri_param).await?;
427 (handler)(params, info, &mut rpcenv)
429 .map(|data| formatter.format_data(data, &rpcenv))
433 let mut resp = match result {
436 if let Some(httperr) = err.downcast_ref::<HttpError>() {
437 if httperr.code == StatusCode::UNAUTHORIZED {
438 tokio::time::sleep_until(Instant::from_std(delay_unauth_time)).await;
441 formatter.format_error(err)
445 let resp = match compression {
446 Some(CompressionMethod::Deflate) => {
447 resp.headers_mut().insert(
448 header::CONTENT_ENCODING,
449 CompressionMethod::Deflate.content_encoding(),
452 Body::wrap_stream(DeflateEncoder::with_quality(
453 TryStreamExt::map_err(body, |err| {
454 proxmox::io_format_err!("error during compression: {}", err)
463 if info.reload_timezone {
473 fn extension_to_content_type(filename: &Path) -> (&'static str, bool) {
474 if let Some(ext) = filename.extension().and_then(|osstr| osstr.to_str()) {
476 "css" => ("text/css", false),
477 "html" => ("text/html", false),
478 "js" => ("application/javascript", false),
479 "json" => ("application/json", false),
480 "map" => ("application/json", false),
481 "png" => ("image/png", true),
482 "ico" => ("image/x-icon", true),
483 "gif" => ("image/gif", true),
484 "svg" => ("image/svg+xml", false),
485 "jar" => ("application/java-archive", true),
486 "woff" => ("application/font-woff", true),
487 "woff2" => ("application/font-woff2", true),
488 "ttf" => ("application/font-snft", true),
489 "pdf" => ("application/pdf", true),
490 "epub" => ("application/epub+zip", true),
491 "mp3" => ("audio/mpeg", true),
492 "oga" => ("audio/ogg", true),
493 "tgz" => ("application/x-compressed-tar", true),
494 _ => ("application/octet-stream", false),
498 ("application/octet-stream", false)
501 async fn simple_static_file_download(
503 content_type: &'static str,
504 compression: Option<CompressionMethod>,
505 ) -> Result<Response<Body>, Error> {
506 use tokio::io::AsyncReadExt;
508 let mut file = File::open(filename)
510 .map_err(|err| http_err!(BAD_REQUEST, "File open failed: {}", err))?;
512 let mut data: Vec<u8> = Vec::new();
514 let mut response = match compression {
515 Some(CompressionMethod::Deflate) => {
516 let mut enc = DeflateEncoder::with_quality(data, Level::Default);
517 enc.compress_vec(&mut file, CHUNK_SIZE_LIMIT as usize)
519 let mut response = Response::new(enc.into_inner().into());
520 response.headers_mut().insert(
521 header::CONTENT_ENCODING,
522 CompressionMethod::Deflate.content_encoding(),
527 file.read_to_end(&mut data)
529 .map_err(|err| http_err!(BAD_REQUEST, "File read failed: {}", err))?;
530 Response::new(data.into())
534 response.headers_mut().insert(
535 header::CONTENT_TYPE,
536 header::HeaderValue::from_static(content_type),
542 async fn chuncked_static_file_download(
544 content_type: &'static str,
545 compression: Option<CompressionMethod>,
546 ) -> Result<Response<Body>, Error> {
547 let mut resp = Response::builder()
548 .status(StatusCode::OK)
549 .header(header::CONTENT_TYPE, content_type);
551 let file = File::open(filename)
553 .map_err(|err| http_err!(BAD_REQUEST, "File open failed: {}", err))?;
555 let body = match compression {
556 Some(CompressionMethod::Deflate) => {
558 header::CONTENT_ENCODING,
559 CompressionMethod::Deflate.content_encoding(),
561 Body::wrap_stream(DeflateEncoder::with_quality(
562 AsyncReaderStream::new(file),
566 None => Body::wrap_stream(AsyncReaderStream::new(file)),
569 Ok(resp.body(body).unwrap())
572 async fn handle_static_file_download(
574 compression: Option<CompressionMethod>,
575 ) -> Result<Response<Body>, Error> {
576 let metadata = tokio::fs::metadata(filename.clone())
577 .map_err(|err| http_err!(BAD_REQUEST, "File access problems: {}", err))
580 let (content_type, nocomp) = extension_to_content_type(&filename);
581 let compression = if nocomp { None } else { compression };
583 if metadata.len() < CHUNK_SIZE_LIMIT {
584 simple_static_file_download(filename, content_type, compression).await
586 chuncked_static_file_download(filename, content_type, compression).await
590 // FIXME: support handling multiple compression methods
591 fn extract_compression_method(headers: &http::HeaderMap) -> Option<CompressionMethod> {
592 if let Some(Ok(encodings)) = headers.get(header::ACCEPT_ENCODING).map(|v| v.to_str()) {
593 for encoding in encodings.split(&[',', ' '][..]) {
594 if let Ok(method) = encoding.parse() {
602 async fn handle_request(
605 peer: &std::net::SocketAddr,
606 ) -> Result<Response<Body>, Error> {
607 let (parts, body) = req.into_parts();
608 let method = parts.method.clone();
609 let (path, components) = normalize_uri_path(parts.uri.path())?;
611 let comp_len = components.len();
613 let query = parts.uri.query().unwrap_or_default();
614 if path.len() + query.len() > MAX_URI_QUERY_LENGTH {
615 return Ok(Response::builder()
616 .status(StatusCode::URI_TOO_LONG)
621 let env_type = api.env_type();
622 let mut rpcenv = RestEnvironment::new(env_type, Arc::clone(&api));
624 rpcenv.set_client_ip(Some(*peer));
626 let delay_unauth_time = std::time::Instant::now() + std::time::Duration::from_millis(3000);
627 let access_forbidden_time = std::time::Instant::now() + std::time::Duration::from_millis(500);
629 if comp_len >= 1 && components[0] == "api2" {
631 let format = components[1];
633 let formatter: &dyn OutputFormatter = match format {
634 "json" => JSON_FORMATTER,
635 "extjs" => EXTJS_FORMATTER,
636 _ => bail!("Unsupported output format '{}'.", format),
639 let mut uri_param = HashMap::new();
640 let api_method = api.find_method(&components[2..], method.clone(), &mut uri_param);
642 let mut auth_required = true;
643 if let Some(api_method) = api_method {
644 if let Permission::World = *api_method.access.permission {
645 auth_required = false; // no auth for endpoints with World permission
649 let mut user_info: Box<dyn UserInformation + Send + Sync> = Box::new(EmptyUserInformation {});
652 match api.check_auth(&parts.headers, &method).await {
653 Ok((authid, info)) => {
654 rpcenv.set_auth_id(Some(authid));
658 let err = match auth_err {
659 AuthError::Generic(err) => err,
660 AuthError::NoData => {
661 format_err!("no authentication credentials provided.")
664 // fixme: log Username??
665 rpcenv.log_failed_auth(None, &err.to_string());
667 // always delay unauthorized calls by 3 seconds (from start of request)
668 let err = http_err!(UNAUTHORIZED, "authentication failed - {}", err);
669 tokio::time::sleep_until(Instant::from_std(delay_unauth_time)).await;
670 return Ok(formatter.format_error(err));
677 let err = http_err!(NOT_FOUND, "Path '{}' not found.", path);
678 return Ok(formatter.format_error(err));
680 Some(api_method) => {
681 let auth_id = rpcenv.get_auth_id();
682 let user_info = user_info;
684 if !check_api_permission(
685 api_method.access.permission,
690 let err = http_err!(FORBIDDEN, "permission check failed");
691 tokio::time::sleep_until(Instant::from_std(access_forbidden_time)).await;
692 return Ok(formatter.format_error(err));
695 let result = if api_method.protected && env_type == RpcEnvironmentType::PUBLIC {
696 proxy_protected_request(api_method, parts, body, peer).await
698 handle_api_request(rpcenv, api_method, formatter, parts, body, uri_param)
702 let mut response = match result {
704 Err(err) => formatter.format_error(err),
707 if let Some(auth_id) = auth_id {
708 response.extensions_mut().insert(AuthStringExtension(auth_id));
716 // not Auth required for accessing files!
718 if method != hyper::Method::GET {
719 bail!("Unsupported HTTP method {}", method);
723 match api.check_auth(&parts.headers, &method).await {
724 Ok((auth_id, _user_info)) => {
725 rpcenv.set_auth_id(Some(auth_id));
726 return Ok(api.get_index(rpcenv, parts).await);
728 Err(AuthError::Generic(_)) => {
729 tokio::time::sleep_until(Instant::from_std(delay_unauth_time)).await;
731 Err(AuthError::NoData) => {}
733 return Ok(api.get_index(rpcenv, parts).await);
735 let filename = api.find_alias(&components);
736 let compression = extract_compression_method(&parts.headers);
737 return handle_static_file_download(filename, compression).await;
741 Err(http_err!(NOT_FOUND, "Path '{}' not found.", path))