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
;
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
,
29 RpcEnvironmentType
, UserInformation
,
31 use proxmox
::http_err
;
33 use pbs_tools
::compression
::{DeflateEncoder, Level}
;
34 use pbs_tools
::stream
::AsyncReaderStream
;
37 ApiConfig
, FileLogger
, AuthError
, RestEnvironment
, CompressionMethod
,
38 extract_cookie
, normalize_uri_path
, formatter
::*,
45 struct AuthStringExtension(String
);
47 struct EmptyUserInformation {}
49 impl UserInformation
for EmptyUserInformation
{
50 fn is_superuser(&self, _userid
: &str) -> bool { false }
51 fn is_group_member(&self, _userid
: &str, _group
: &str) -> bool { false }
52 fn lookup_privs(&self, _userid
: &str, _path
: &[&str]) -> u64 { 0 }
55 pub struct RestServer
{
56 pub api_config
: Arc
<ApiConfig
>,
59 const MAX_URI_QUERY_LENGTH
: usize = 3072;
60 const CHUNK_SIZE_LIMIT
: u64 = 32 * 1024;
63 pub fn new(api_config
: ApiConfig
) -> Self {
65 api_config
: Arc
::new(api_config
),
70 impl tower_service
::Service
<&Pin
<Box
<tokio_openssl
::SslStream
<tokio
::net
::TcpStream
>>>>
73 type Response
= ApiService
;
75 type Future
= Pin
<Box
<dyn Future
<Output
= Result
<ApiService
, Error
>> + Send
>>;
77 fn poll_ready(&mut self, _cx
: &mut Context
) -> Poll
<Result
<(), Self::Error
>> {
83 ctx
: &Pin
<Box
<tokio_openssl
::SslStream
<tokio
::net
::TcpStream
>>>,
85 match ctx
.get_ref().peer_addr() {
86 Err(err
) => future
::err(format_err
!("unable to get peer address - {}", err
)).boxed(),
87 Ok(peer
) => future
::ok(ApiService
{
89 api_config
: self.api_config
.clone(),
96 impl tower_service
::Service
<&hyper
::server
::conn
::AddrStream
> for RestServer
{
97 type Response
= ApiService
;
99 type Future
= Pin
<Box
<dyn Future
<Output
= Result
<ApiService
, Error
>> + Send
>>;
101 fn poll_ready(&mut self, _cx
: &mut Context
) -> Poll
<Result
<(), Self::Error
>> {
105 fn call(&mut self, ctx
: &hyper
::server
::conn
::AddrStream
) -> Self::Future
{
106 let peer
= ctx
.remote_addr();
107 future
::ok(ApiService
{
109 api_config
: self.api_config
.clone(),
115 impl tower_service
::Service
<&tokio
::net
::UnixStream
> for RestServer
{
116 type Response
= ApiService
;
118 type Future
= Pin
<Box
<dyn Future
<Output
= Result
<ApiService
, Error
>> + Send
>>;
120 fn poll_ready(&mut self, _cx
: &mut Context
) -> Poll
<Result
<(), Self::Error
>> {
124 fn call(&mut self, _ctx
: &tokio
::net
::UnixStream
) -> Self::Future
{
125 // TODO: Find a way to actually represent the vsock peer in the ApiService struct - for now
126 // it doesn't really matter, so just use a fake IP address
127 let fake_peer
= "0.0.0.0:807".parse().unwrap();
128 future
::ok(ApiService
{
130 api_config
: self.api_config
.clone(),
136 pub struct ApiService
{
137 pub peer
: std
::net
::SocketAddr
,
138 pub api_config
: Arc
<ApiConfig
>,
142 logfile
: Option
<&Arc
<Mutex
<FileLogger
>>>,
143 peer
: &std
::net
::SocketAddr
,
144 method
: hyper
::Method
,
146 resp
: &Response
<Body
>,
147 user_agent
: Option
<String
>,
149 if resp
.extensions().get
::<NoLogExtension
>().is_some() {
153 // we also log URL-to-long requests, so avoid message bigger than PIPE_BUF (4k on Linux)
154 // to profit from atomicty guarantees for O_APPEND opened logfiles
155 let path
= &path_query
[..MAX_URI_QUERY_LENGTH
.min(path_query
.len())];
157 let status
= resp
.status();
158 if !(status
.is_success() || status
.is_informational()) {
159 let reason
= status
.canonical_reason().unwrap_or("unknown reason");
161 let message
= match resp
.extensions().get
::<ErrorMessageExtension
>() {
162 Some(data
) => &data
.0,
163 None
=> "request failed",
167 "{} {}: {} {}: [client {}] {}",
176 if let Some(logfile
) = logfile
{
177 let auth_id
= match resp
.extensions().get
::<AuthStringExtension
>() {
178 Some(AuthStringExtension(auth_id
)) => auth_id
.clone(),
179 None
=> "-".to_string(),
181 let now
= proxmox
::tools
::time
::epoch_i64();
182 // time format which apache/nginx use (by default), copied from pve-http-server
183 let datetime
= proxmox
::tools
::time
::strftime_local("%d/%m/%Y:%H:%M:%S %z", now
)
184 .unwrap_or_else(|_
| "-".to_string());
186 logfile
.lock().unwrap().log(format
!(
187 "{} - {} [{}] \"{} {}\" {} {} {}",
194 resp
.body().size_hint().lower(),
195 user_agent
.unwrap_or_else(|| "-".to_string()),
200 fn get_proxied_peer(headers
: &HeaderMap
) -> Option
<std
::net
::SocketAddr
> {
202 static ref RE
: Regex
= Regex
::new(r
#"for="([^"]+)""#).unwrap();
204 let forwarded = headers.get(header::FORWARDED)?.to_str().ok()?;
205 let capture = RE.captures(&forwarded)?;
206 let rhost = capture.get(1)?.as_str();
211 fn get_user_agent(headers: &HeaderMap) -> Option<String> {
212 let agent = headers.get(header::USER_AGENT)?.to_str();
215 let mut s = s.to_owned();
222 impl tower_service::Service<Request<Body>> for ApiService {
223 type Response = Response<Body>;
225 #[allow(clippy::type_complexity)]
226 type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
228 fn poll_ready(&mut self, _cx: &mut Context) -> Poll<Result<(), Self::Error>> {
232 fn call(&mut self, req: Request<Body>) -> Self::Future {
233 let path = req.uri().path_and_query().unwrap().as_str().to_owned();
234 let method = req.method().clone();
235 let user_agent = get_user_agent(req.headers());
237 let config = Arc::clone(&self.api_config);
238 let peer = match get_proxied_peer(req.headers()) {
239 Some(proxied_peer) => proxied_peer,
243 let response = match handle_request(Arc::clone(&config), req, &peer).await {
244 Ok(response) => response,
246 let (err, code) = match err.downcast_ref::<HttpError>() {
247 Some(apierr) => (apierr.message.clone(), apierr.code),
248 _ => (err.to_string(), StatusCode::BAD_REQUEST),
252 .extension(ErrorMessageExtension(err.to_string()))
256 let logger = config.get_access_log();
257 log_response(logger, &peer, method, &path, &response, user_agent);
264 fn parse_query_parameters<S: 'static + BuildHasher + Send>(
265 param_schema: ParameterSchema,
266 form: &str, // x-www-form-urlencoded body data
268 uri_param: &HashMap<String, String, S>,
269 ) -> Result<Value, Error> {
270 let mut param_list: Vec<(String, String)> = vec![];
272 if !form.is_empty() {
273 for (k, v) in form_urlencoded::parse(form.as_bytes()).into_owned() {
274 param_list.push((k, v));
278 if let Some(query_str) = parts.uri.query() {
279 for (k, v) in form_urlencoded::parse(query_str.as_bytes()).into_owned() {
282 } // skip extjs "disable cache" parameter
283 param_list.push((k, v));
287 for (k, v) in uri_param {
288 param_list.push((k.clone(), v.clone()));
291 let params = parse_parameter_strings(¶m_list, param_schema, true)?;
296 async fn get_request_parameters<S: 'static + BuildHasher + Send>(
297 param_schema: ParameterSchema,
300 uri_param: HashMap<String, String, S>,
301 ) -> Result<Value, Error> {
302 let mut is_json = false;
304 if let Some(value) = parts.headers.get(header::CONTENT_TYPE) {
305 match value.to_str().map(|v| v.split(';').next()) {
306 Ok(Some("application/x-www-form-urlencoded")) => {
309 Ok(Some("application/json")) => {
312 _ => bail!("unsupported content type {:?}", value.to_str()),
316 let body = TryStreamExt::map_err(req_body, |err| {
317 http_err!(BAD_REQUEST, "Problems reading request body: {}", err)
319 .try_fold(Vec::new(), |mut acc, chunk| async move {
320 // FIXME: max request body size?
321 if acc.len() + chunk.len() < 64 * 1024 {
322 acc.extend_from_slice(&*chunk);
325 Err(http_err!(BAD_REQUEST, "Request body too large"))
331 std::str::from_utf8(&body).map_err(|err| format_err!("Request body not uft8: {}", err))?;
334 let mut params: Value = serde_json::from_str(utf8_data)?;
335 for (k, v) in uri_param {
336 if let Some((_optional, prop_schema)) = param_schema.lookup(&k) {
337 params[&k] = parse_simple_value(&v, prop_schema)?;
340 verify_json_object(¶ms, ¶m_schema)?;
343 parse_query_parameters(param_schema, utf8_data, &parts, &uri_param)
347 struct NoLogExtension();
349 async fn proxy_protected_request(
350 info: &'static ApiMethod,
353 peer: &std::net::SocketAddr,
354 ) -> Result<Response<Body>, Error> {
355 let mut uri_parts = parts.uri.clone().into_parts();
357 uri_parts.scheme = Some(http::uri::Scheme::HTTP);
358 uri_parts.authority = Some(http::uri::Authority::from_static("127.0.0.1:82"));
359 let new_uri = http::Uri::from_parts(uri_parts).unwrap();
363 let mut request = Request::from_parts(parts, req_body);
364 request.headers_mut().insert(
366 format!("for=\"{}\";", peer).parse().unwrap(),
369 let reload_timezone = info.reload_timezone;
371 let resp = hyper::client::Client::new()
373 .map_err(Error::from)
375 resp.extensions_mut().insert(NoLogExtension());
389 pub(crate) async fn handle_api_request<Env: RpcEnvironment, S: 'static + BuildHasher + Send>(
391 info: &'static ApiMethod,
392 formatter: &'static dyn OutputFormatter,
395 uri_param: HashMap<String, String, S>,
396 ) -> Result<Response<Body>, Error> {
397 let delay_unauth_time = std::time::Instant::now() + std::time::Duration::from_millis(3000);
398 let compression = extract_compression_method(&parts.headers);
400 let result = match info.handler {
401 ApiHandler::AsyncHttp(handler) => {
402 let params = parse_query_parameters(info.parameters, "", &parts, &uri_param)?;
403 (handler)(parts, req_body, params, info, Box::new(rpcenv)).await
405 ApiHandler::Sync(handler) => {
407 get_request_parameters(info.parameters, parts, req_body, uri_param).await?;
408 (handler)(params, info, &mut rpcenv).map(|data| formatter.format_data(data, &rpcenv))
410 ApiHandler::Async(handler) => {
412 get_request_parameters(info.parameters, parts, req_body, uri_param).await?;
413 (handler)(params, info, &mut rpcenv)
415 .map(|data| formatter.format_data(data, &rpcenv))
419 let mut resp = match result {
422 if let Some(httperr) = err.downcast_ref::<HttpError>() {
423 if httperr.code == StatusCode::UNAUTHORIZED {
424 tokio::time::sleep_until(Instant::from_std(delay_unauth_time)).await;
427 formatter.format_error(err)
431 let resp = match compression {
432 Some(CompressionMethod::Deflate) => {
433 resp.headers_mut().insert(
434 header::CONTENT_ENCODING,
435 CompressionMethod::Deflate.content_encoding(),
438 Body::wrap_stream(DeflateEncoder::with_quality(
439 TryStreamExt::map_err(body, |err| {
440 proxmox::io_format_err!("error during compression: {}", err)
449 if info.reload_timezone {
459 fn extension_to_content_type(filename: &Path) -> (&'static str, bool) {
460 if let Some(ext) = filename.extension().and_then(|osstr| osstr.to_str()) {
462 "css" => ("text/css", false),
463 "html" => ("text/html", false),
464 "js" => ("application/javascript", false),
465 "json" => ("application/json", false),
466 "map" => ("application/json", false),
467 "png" => ("image/png", true),
468 "ico" => ("image/x-icon", true),
469 "gif" => ("image/gif", true),
470 "svg" => ("image/svg+xml", false),
471 "jar" => ("application/java-archive", true),
472 "woff" => ("application/font-woff", true),
473 "woff2" => ("application/font-woff2", true),
474 "ttf" => ("application/font-snft", true),
475 "pdf" => ("application/pdf", true),
476 "epub" => ("application/epub+zip", true),
477 "mp3" => ("audio/mpeg", true),
478 "oga" => ("audio/ogg", true),
479 "tgz" => ("application/x-compressed-tar", true),
480 _ => ("application/octet-stream", false),
484 ("application/octet-stream", false)
487 async fn simple_static_file_download(
489 content_type: &'static str,
490 compression: Option<CompressionMethod>,
491 ) -> Result<Response<Body>, Error> {
492 use tokio::io::AsyncReadExt;
494 let mut file = File::open(filename)
496 .map_err(|err| http_err!(BAD_REQUEST, "File open failed: {}", err))?;
498 let mut data: Vec<u8> = Vec::new();
500 let mut response = match compression {
501 Some(CompressionMethod::Deflate) => {
502 let mut enc = DeflateEncoder::with_quality(data, Level::Default);
503 enc.compress_vec(&mut file, CHUNK_SIZE_LIMIT as usize)
505 let mut response = Response::new(enc.into_inner().into());
506 response.headers_mut().insert(
507 header::CONTENT_ENCODING,
508 CompressionMethod::Deflate.content_encoding(),
513 file.read_to_end(&mut data)
515 .map_err(|err| http_err!(BAD_REQUEST, "File read failed: {}", err))?;
516 Response::new(data.into())
520 response.headers_mut().insert(
521 header::CONTENT_TYPE,
522 header::HeaderValue::from_static(content_type),
528 async fn chuncked_static_file_download(
530 content_type: &'static str,
531 compression: Option<CompressionMethod>,
532 ) -> Result<Response<Body>, Error> {
533 let mut resp = Response::builder()
534 .status(StatusCode::OK)
535 .header(header::CONTENT_TYPE, content_type);
537 let file = File::open(filename)
539 .map_err(|err| http_err!(BAD_REQUEST, "File open failed: {}", err))?;
541 let body = match compression {
542 Some(CompressionMethod::Deflate) => {
544 header::CONTENT_ENCODING,
545 CompressionMethod::Deflate.content_encoding(),
547 Body::wrap_stream(DeflateEncoder::with_quality(
548 AsyncReaderStream::new(file),
552 None => Body::wrap_stream(AsyncReaderStream::new(file)),
555 Ok(resp.body(body).unwrap())
558 async fn handle_static_file_download(
560 compression: Option<CompressionMethod>,
561 ) -> Result<Response<Body>, Error> {
562 let metadata = tokio::fs::metadata(filename.clone())
563 .map_err(|err| http_err!(BAD_REQUEST, "File access problems: {}", err))
566 let (content_type, nocomp) = extension_to_content_type(&filename);
567 let compression = if nocomp { None } else { compression };
569 if metadata.len() < CHUNK_SIZE_LIMIT {
570 simple_static_file_download(filename, content_type, compression).await
572 chuncked_static_file_download(filename, content_type, compression).await
576 fn extract_lang_header(headers: &http::HeaderMap) -> Option<String> {
577 if let Some(Ok(cookie)) = headers.get("COOKIE").map(|v| v.to_str()) {
578 return extract_cookie(cookie, "PBSLangCookie");
583 // FIXME: support handling multiple compression methods
584 fn extract_compression_method(headers: &http::HeaderMap) -> Option<CompressionMethod> {
585 if let Some(Ok(encodings)) = headers.get(header::ACCEPT_ENCODING).map(|v| v.to_str()) {
586 for encoding in encodings.split(&[',', ' '][..]) {
587 if let Ok(method) = encoding.parse() {
595 async fn handle_request(
598 peer: &std::net::SocketAddr,
599 ) -> Result<Response<Body>, Error> {
600 let (parts, body) = req.into_parts();
601 let method = parts.method.clone();
602 let (path, components) = normalize_uri_path(parts.uri.path())?;
604 let comp_len = components.len();
606 let query = parts.uri.query().unwrap_or_default();
607 if path.len() + query.len() > MAX_URI_QUERY_LENGTH {
608 return Ok(Response::builder()
609 .status(StatusCode::URI_TOO_LONG)
614 let env_type = api.env_type();
615 let mut rpcenv = RestEnvironment::new(env_type, Arc::clone(&api));
617 rpcenv.set_client_ip(Some(*peer));
619 let auth = &api.api_auth;
621 let delay_unauth_time = std::time::Instant::now() + std::time::Duration::from_millis(3000);
622 let access_forbidden_time = std::time::Instant::now() + std::time::Duration::from_millis(500);
624 if comp_len >= 1 && components[0] == "api2" {
626 let format = components[1];
628 let formatter: &dyn OutputFormatter = match format {
629 "json" => JSON_FORMATTER,
630 "extjs" => EXTJS_FORMATTER,
631 _ => bail!("Unsupported output format '{}'.", format),
634 let mut uri_param = HashMap::new();
635 let api_method = api.find_method(&components[2..], method.clone(), &mut uri_param);
637 let mut auth_required = true;
638 if let Some(api_method) = api_method {
639 if let Permission::World = *api_method.access.permission {
640 auth_required = false; // no auth for endpoints with World permission
644 let mut user_info: Box<dyn UserInformation + Send + Sync> = Box::new(EmptyUserInformation {});
647 match auth.check_auth(&parts.headers, &method) {
648 Ok((authid, info)) => {
649 rpcenv.set_auth_id(Some(authid));
653 let err = match auth_err {
654 AuthError::Generic(err) => err,
655 AuthError::NoData => {
656 format_err!("no authentication credentials provided.")
659 // fixme: log Username??
660 rpcenv.log_failed_auth(None, &err.to_string());
662 // always delay unauthorized calls by 3 seconds (from start of request)
663 let err = http_err!(UNAUTHORIZED, "authentication failed - {}", err);
664 tokio::time::sleep_until(Instant::from_std(delay_unauth_time)).await;
665 return Ok(formatter.format_error(err));
672 let err = http_err!(NOT_FOUND, "Path '{}' not found.", path);
673 return Ok(formatter.format_error(err));
675 Some(api_method) => {
676 let auth_id = rpcenv.get_auth_id();
677 let user_info = user_info;
679 if !check_api_permission(
680 api_method.access.permission,
685 let err = http_err!(FORBIDDEN, "permission check failed");
686 tokio::time::sleep_until(Instant::from_std(access_forbidden_time)).await;
687 return Ok(formatter.format_error(err));
690 let result = if api_method.protected && env_type == RpcEnvironmentType::PUBLIC {
691 proxy_protected_request(api_method, parts, body, peer).await
693 handle_api_request(rpcenv, api_method, formatter, parts, body, uri_param)
697 let mut response = match result {
699 Err(err) => formatter.format_error(err),
702 if let Some(auth_id) = auth_id {
703 response.extensions_mut().insert(AuthStringExtension(auth_id));
711 // not Auth required for accessing files!
713 if method != hyper::Method::GET {
714 bail!("Unsupported HTTP method {}", method);
718 let language = extract_lang_header(&parts.headers);
719 match auth.check_auth(&parts.headers, &method) {
720 Ok((auth_id, _user_info)) => {
721 return Ok(api.get_index(Some(auth_id), language, parts));
723 Err(AuthError::Generic(_)) => {
724 tokio::time::sleep_until(Instant::from_std(delay_unauth_time)).await;
726 Err(AuthError::NoData) => {}
728 return Ok(api.get_index(None, language, parts));
730 let filename = api.find_alias(&components);
731 let compression = extract_compression_method(&parts.headers);
732 return handle_static_file_download(filename, compression).await;
736 Err(http_err!(NOT_FOUND, "Path '{}' not found.", path))