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 /// Helper [Service] containing the peer Address
144 /// The lower level connection [Service] implementation on
145 /// [RestServer] extracts the peer address and return an [ApiService].
146 pub struct ApiService
{
147 pub peer
: std
::net
::SocketAddr
,
148 pub api_config
: Arc
<ApiConfig
>,
152 logfile
: Option
<&Arc
<Mutex
<FileLogger
>>>,
153 peer
: &std
::net
::SocketAddr
,
154 method
: hyper
::Method
,
156 resp
: &Response
<Body
>,
157 user_agent
: Option
<String
>,
159 if resp
.extensions().get
::<NoLogExtension
>().is_some() {
163 // we also log URL-to-long requests, so avoid message bigger than PIPE_BUF (4k on Linux)
164 // to profit from atomicty guarantees for O_APPEND opened logfiles
165 let path
= &path_query
[..MAX_URI_QUERY_LENGTH
.min(path_query
.len())];
167 let status
= resp
.status();
168 if !(status
.is_success() || status
.is_informational()) {
169 let reason
= status
.canonical_reason().unwrap_or("unknown reason");
171 let message
= match resp
.extensions().get
::<ErrorMessageExtension
>() {
172 Some(data
) => &data
.0,
173 None
=> "request failed",
177 "{} {}: {} {}: [client {}] {}",
186 if let Some(logfile
) = logfile
{
187 let auth_id
= match resp
.extensions().get
::<AuthStringExtension
>() {
188 Some(AuthStringExtension(auth_id
)) => auth_id
.clone(),
189 None
=> "-".to_string(),
191 let now
= proxmox
::tools
::time
::epoch_i64();
192 // time format which apache/nginx use (by default), copied from pve-http-server
193 let datetime
= proxmox
::tools
::time
::strftime_local("%d/%m/%Y:%H:%M:%S %z", now
)
194 .unwrap_or_else(|_
| "-".to_string());
196 logfile
.lock().unwrap().log(format
!(
197 "{} - {} [{}] \"{} {}\" {} {} {}",
204 resp
.body().size_hint().lower(),
205 user_agent
.unwrap_or_else(|| "-".to_string()),
210 fn get_proxied_peer(headers
: &HeaderMap
) -> Option
<std
::net
::SocketAddr
> {
212 static ref RE
: Regex
= Regex
::new(r
#"for="([^"]+)""#).unwrap();
214 let forwarded = headers.get(header::FORWARDED)?.to_str().ok()?;
215 let capture = RE.captures(&forwarded)?;
216 let rhost = capture.get(1)?.as_str();
221 fn get_user_agent(headers: &HeaderMap) -> Option<String> {
222 let agent = headers.get(header::USER_AGENT)?.to_str();
225 let mut s = s.to_owned();
232 impl Service<Request<Body>> for ApiService {
233 type Response = Response<Body>;
235 #[allow(clippy::type_complexity)]
236 type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
238 fn poll_ready(&mut self, _cx: &mut Context) -> Poll<Result<(), Self::Error>> {
242 fn call(&mut self, req: Request<Body>) -> Self::Future {
243 let path = req.uri().path_and_query().unwrap().as_str().to_owned();
244 let method = req.method().clone();
245 let user_agent = get_user_agent(req.headers());
247 let config = Arc::clone(&self.api_config);
248 let peer = match get_proxied_peer(req.headers()) {
249 Some(proxied_peer) => proxied_peer,
253 let response = match handle_request(Arc::clone(&config), req, &peer).await {
254 Ok(response) => response,
256 let (err, code) = match err.downcast_ref::<HttpError>() {
257 Some(apierr) => (apierr.message.clone(), apierr.code),
258 _ => (err.to_string(), StatusCode::BAD_REQUEST),
262 .extension(ErrorMessageExtension(err.to_string()))
266 let logger = config.get_access_log();
267 log_response(logger, &peer, method, &path, &response, user_agent);
274 fn parse_query_parameters<S: 'static + BuildHasher + Send>(
275 param_schema: ParameterSchema,
276 form: &str, // x-www-form-urlencoded body data
278 uri_param: &HashMap<String, String, S>,
279 ) -> Result<Value, Error> {
280 let mut param_list: Vec<(String, String)> = vec![];
282 if !form.is_empty() {
283 for (k, v) in form_urlencoded::parse(form.as_bytes()).into_owned() {
284 param_list.push((k, v));
288 if let Some(query_str) = parts.uri.query() {
289 for (k, v) in form_urlencoded::parse(query_str.as_bytes()).into_owned() {
292 } // skip extjs "disable cache" parameter
293 param_list.push((k, v));
297 for (k, v) in uri_param {
298 param_list.push((k.clone(), v.clone()));
301 let params = parse_parameter_strings(¶m_list, param_schema, true)?;
306 async fn get_request_parameters<S: 'static + BuildHasher + Send>(
307 param_schema: ParameterSchema,
310 uri_param: HashMap<String, String, S>,
311 ) -> Result<Value, Error> {
312 let mut is_json = false;
314 if let Some(value) = parts.headers.get(header::CONTENT_TYPE) {
315 match value.to_str().map(|v| v.split(';').next()) {
316 Ok(Some("application/x-www-form-urlencoded")) => {
319 Ok(Some("application/json")) => {
322 _ => bail!("unsupported content type {:?}", value.to_str()),
326 let body = TryStreamExt::map_err(req_body, |err| {
327 http_err!(BAD_REQUEST, "Problems reading request body: {}", err)
329 .try_fold(Vec::new(), |mut acc, chunk| async move {
330 // FIXME: max request body size?
331 if acc.len() + chunk.len() < 64 * 1024 {
332 acc.extend_from_slice(&*chunk);
335 Err(http_err!(BAD_REQUEST, "Request body too large"))
341 std::str::from_utf8(&body).map_err(|err| format_err!("Request body not uft8: {}", err))?;
344 let mut params: Value = serde_json::from_str(utf8_data)?;
345 for (k, v) in uri_param {
346 if let Some((_optional, prop_schema)) = param_schema.lookup(&k) {
347 params[&k] = parse_simple_value(&v, prop_schema)?;
350 verify_json_object(¶ms, ¶m_schema)?;
353 parse_query_parameters(param_schema, utf8_data, &parts, &uri_param)
357 struct NoLogExtension();
359 async fn proxy_protected_request(
360 info: &'static ApiMethod,
363 peer: &std::net::SocketAddr,
364 ) -> Result<Response<Body>, Error> {
365 let mut uri_parts = parts.uri.clone().into_parts();
367 uri_parts.scheme = Some(http::uri::Scheme::HTTP);
368 uri_parts.authority = Some(http::uri::Authority::from_static("127.0.0.1:82"));
369 let new_uri = http::Uri::from_parts(uri_parts).unwrap();
373 let mut request = Request::from_parts(parts, req_body);
374 request.headers_mut().insert(
376 format!("for=\"{}\";", peer).parse().unwrap(),
379 let reload_timezone = info.reload_timezone;
381 let resp = hyper::client::Client::new()
383 .map_err(Error::from)
385 resp.extensions_mut().insert(NoLogExtension());
399 pub(crate) async fn handle_api_request<Env: RpcEnvironment, S: 'static + BuildHasher + Send>(
401 info: &'static ApiMethod,
402 formatter: &'static dyn OutputFormatter,
405 uri_param: HashMap<String, String, S>,
406 ) -> Result<Response<Body>, Error> {
407 let delay_unauth_time = std::time::Instant::now() + std::time::Duration::from_millis(3000);
408 let compression = extract_compression_method(&parts.headers);
410 let result = match info.handler {
411 ApiHandler::AsyncHttp(handler) => {
412 let params = parse_query_parameters(info.parameters, "", &parts, &uri_param)?;
413 (handler)(parts, req_body, params, info, Box::new(rpcenv)).await
415 ApiHandler::Sync(handler) => {
417 get_request_parameters(info.parameters, parts, req_body, uri_param).await?;
418 (handler)(params, info, &mut rpcenv).map(|data| formatter.format_data(data, &rpcenv))
420 ApiHandler::Async(handler) => {
422 get_request_parameters(info.parameters, parts, req_body, uri_param).await?;
423 (handler)(params, info, &mut rpcenv)
425 .map(|data| formatter.format_data(data, &rpcenv))
429 let mut resp = match result {
432 if let Some(httperr) = err.downcast_ref::<HttpError>() {
433 if httperr.code == StatusCode::UNAUTHORIZED {
434 tokio::time::sleep_until(Instant::from_std(delay_unauth_time)).await;
437 formatter.format_error(err)
441 let resp = match compression {
442 Some(CompressionMethod::Deflate) => {
443 resp.headers_mut().insert(
444 header::CONTENT_ENCODING,
445 CompressionMethod::Deflate.content_encoding(),
448 Body::wrap_stream(DeflateEncoder::with_quality(
449 TryStreamExt::map_err(body, |err| {
450 proxmox::io_format_err!("error during compression: {}", err)
459 if info.reload_timezone {
469 fn extension_to_content_type(filename: &Path) -> (&'static str, bool) {
470 if let Some(ext) = filename.extension().and_then(|osstr| osstr.to_str()) {
472 "css" => ("text/css", false),
473 "html" => ("text/html", false),
474 "js" => ("application/javascript", false),
475 "json" => ("application/json", false),
476 "map" => ("application/json", false),
477 "png" => ("image/png", true),
478 "ico" => ("image/x-icon", true),
479 "gif" => ("image/gif", true),
480 "svg" => ("image/svg+xml", false),
481 "jar" => ("application/java-archive", true),
482 "woff" => ("application/font-woff", true),
483 "woff2" => ("application/font-woff2", true),
484 "ttf" => ("application/font-snft", true),
485 "pdf" => ("application/pdf", true),
486 "epub" => ("application/epub+zip", true),
487 "mp3" => ("audio/mpeg", true),
488 "oga" => ("audio/ogg", true),
489 "tgz" => ("application/x-compressed-tar", true),
490 _ => ("application/octet-stream", false),
494 ("application/octet-stream", false)
497 async fn simple_static_file_download(
499 content_type: &'static str,
500 compression: Option<CompressionMethod>,
501 ) -> Result<Response<Body>, Error> {
502 use tokio::io::AsyncReadExt;
504 let mut file = File::open(filename)
506 .map_err(|err| http_err!(BAD_REQUEST, "File open failed: {}", err))?;
508 let mut data: Vec<u8> = Vec::new();
510 let mut response = match compression {
511 Some(CompressionMethod::Deflate) => {
512 let mut enc = DeflateEncoder::with_quality(data, Level::Default);
513 enc.compress_vec(&mut file, CHUNK_SIZE_LIMIT as usize)
515 let mut response = Response::new(enc.into_inner().into());
516 response.headers_mut().insert(
517 header::CONTENT_ENCODING,
518 CompressionMethod::Deflate.content_encoding(),
523 file.read_to_end(&mut data)
525 .map_err(|err| http_err!(BAD_REQUEST, "File read failed: {}", err))?;
526 Response::new(data.into())
530 response.headers_mut().insert(
531 header::CONTENT_TYPE,
532 header::HeaderValue::from_static(content_type),
538 async fn chuncked_static_file_download(
540 content_type: &'static str,
541 compression: Option<CompressionMethod>,
542 ) -> Result<Response<Body>, Error> {
543 let mut resp = Response::builder()
544 .status(StatusCode::OK)
545 .header(header::CONTENT_TYPE, content_type);
547 let file = File::open(filename)
549 .map_err(|err| http_err!(BAD_REQUEST, "File open failed: {}", err))?;
551 let body = match compression {
552 Some(CompressionMethod::Deflate) => {
554 header::CONTENT_ENCODING,
555 CompressionMethod::Deflate.content_encoding(),
557 Body::wrap_stream(DeflateEncoder::with_quality(
558 AsyncReaderStream::new(file),
562 None => Body::wrap_stream(AsyncReaderStream::new(file)),
565 Ok(resp.body(body).unwrap())
568 async fn handle_static_file_download(
570 compression: Option<CompressionMethod>,
571 ) -> Result<Response<Body>, Error> {
572 let metadata = tokio::fs::metadata(filename.clone())
573 .map_err(|err| http_err!(BAD_REQUEST, "File access problems: {}", err))
576 let (content_type, nocomp) = extension_to_content_type(&filename);
577 let compression = if nocomp { None } else { compression };
579 if metadata.len() < CHUNK_SIZE_LIMIT {
580 simple_static_file_download(filename, content_type, compression).await
582 chuncked_static_file_download(filename, content_type, compression).await
586 fn extract_lang_header(headers: &http::HeaderMap) -> Option<String> {
587 if let Some(Ok(cookie)) = headers.get("COOKIE").map(|v| v.to_str()) {
588 return extract_cookie(cookie, "PBSLangCookie");
593 // FIXME: support handling multiple compression methods
594 fn extract_compression_method(headers: &http::HeaderMap) -> Option<CompressionMethod> {
595 if let Some(Ok(encodings)) = headers.get(header::ACCEPT_ENCODING).map(|v| v.to_str()) {
596 for encoding in encodings.split(&[',', ' '][..]) {
597 if let Ok(method) = encoding.parse() {
605 async fn handle_request(
608 peer: &std::net::SocketAddr,
609 ) -> Result<Response<Body>, Error> {
610 let (parts, body) = req.into_parts();
611 let method = parts.method.clone();
612 let (path, components) = normalize_uri_path(parts.uri.path())?;
614 let comp_len = components.len();
616 let query = parts.uri.query().unwrap_or_default();
617 if path.len() + query.len() > MAX_URI_QUERY_LENGTH {
618 return Ok(Response::builder()
619 .status(StatusCode::URI_TOO_LONG)
624 let env_type = api.env_type();
625 let mut rpcenv = RestEnvironment::new(env_type, Arc::clone(&api));
627 rpcenv.set_client_ip(Some(*peer));
629 let auth = &api.api_auth;
631 let delay_unauth_time = std::time::Instant::now() + std::time::Duration::from_millis(3000);
632 let access_forbidden_time = std::time::Instant::now() + std::time::Duration::from_millis(500);
634 if comp_len >= 1 && components[0] == "api2" {
636 let format = components[1];
638 let formatter: &dyn OutputFormatter = match format {
639 "json" => JSON_FORMATTER,
640 "extjs" => EXTJS_FORMATTER,
641 _ => bail!("Unsupported output format '{}'.", format),
644 let mut uri_param = HashMap::new();
645 let api_method = api.find_method(&components[2..], method.clone(), &mut uri_param);
647 let mut auth_required = true;
648 if let Some(api_method) = api_method {
649 if let Permission::World = *api_method.access.permission {
650 auth_required = false; // no auth for endpoints with World permission
654 let mut user_info: Box<dyn UserInformation + Send + Sync> = Box::new(EmptyUserInformation {});
657 match auth.check_auth(&parts.headers, &method) {
658 Ok((authid, info)) => {
659 rpcenv.set_auth_id(Some(authid));
663 let err = match auth_err {
664 AuthError::Generic(err) => err,
665 AuthError::NoData => {
666 format_err!("no authentication credentials provided.")
669 // fixme: log Username??
670 rpcenv.log_failed_auth(None, &err.to_string());
672 // always delay unauthorized calls by 3 seconds (from start of request)
673 let err = http_err!(UNAUTHORIZED, "authentication failed - {}", err);
674 tokio::time::sleep_until(Instant::from_std(delay_unauth_time)).await;
675 return Ok(formatter.format_error(err));
682 let err = http_err!(NOT_FOUND, "Path '{}' not found.", path);
683 return Ok(formatter.format_error(err));
685 Some(api_method) => {
686 let auth_id = rpcenv.get_auth_id();
687 let user_info = user_info;
689 if !check_api_permission(
690 api_method.access.permission,
695 let err = http_err!(FORBIDDEN, "permission check failed");
696 tokio::time::sleep_until(Instant::from_std(access_forbidden_time)).await;
697 return Ok(formatter.format_error(err));
700 let result = if api_method.protected && env_type == RpcEnvironmentType::PUBLIC {
701 proxy_protected_request(api_method, parts, body, peer).await
703 handle_api_request(rpcenv, api_method, formatter, parts, body, uri_param)
707 let mut response = match result {
709 Err(err) => formatter.format_error(err),
712 if let Some(auth_id) = auth_id {
713 response.extensions_mut().insert(AuthStringExtension(auth_id));
721 // not Auth required for accessing files!
723 if method != hyper::Method::GET {
724 bail!("Unsupported HTTP method {}", method);
728 let language = extract_lang_header(&parts.headers);
729 match auth.check_auth(&parts.headers, &method) {
730 Ok((auth_id, _user_info)) => {
731 return Ok(api.get_index(Some(auth_id), language, parts));
733 Err(AuthError::Generic(_)) => {
734 tokio::time::sleep_until(Instant::from_std(delay_unauth_time)).await;
736 Err(AuthError::NoData) => {}
738 return Ok(api.get_index(None, language, parts));
740 let filename = api.find_alias(&components);
741 let compression = extract_compression_method(&parts.headers);
742 return handle_static_file_download(filename, compression).await;
746 Err(http_err!(NOT_FOUND, "Path '{}' not found.", path))