]> git.proxmox.com Git - proxmox-backup.git/blob - proxmox-rest-server/src/rest.rs
update to first proxmox crate split
[proxmox-backup.git] / proxmox-rest-server / src / rest.rs
1 use std::collections::HashMap;
2 use std::future::Future;
3 use std::hash::BuildHasher;
4 use std::path::{Path, PathBuf};
5 use std::pin::Pin;
6 use std::sync::{Arc, Mutex};
7 use std::task::{Context, Poll};
8
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;
17 use regex::Regex;
18 use serde_json::Value;
19 use tokio::fs::File;
20 use tokio::time::Instant;
21 use url::form_urlencoded;
22 use tower_service::Service;
23
24 use proxmox_router::{
25 check_api_permission, ApiHandler, ApiMethod, HttpError, Permission, RpcEnvironment,
26 RpcEnvironmentType, UserInformation,
27 };
28 use proxmox_router::http_err;
29 use proxmox_schema::{
30 parse_parameter_strings, parse_simple_value, verify_json_object, ObjectSchemaType,
31 ParameterSchema,
32 };
33
34 use pbs_tools::compression::{DeflateEncoder, Level};
35 use pbs_tools::stream::AsyncReaderStream;
36
37 use crate::{
38 ApiConfig, FileLogger, AuthError, RestEnvironment, CompressionMethod,
39 normalize_uri_path, formatter::*,
40 };
41
42 extern "C" {
43 fn tzset();
44 }
45
46 struct AuthStringExtension(String);
47
48 struct EmptyUserInformation {}
49
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 }
54 }
55
56 /// REST server implementation (configured with [ApiConfig])
57 ///
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>,
62 }
63
64 const MAX_URI_QUERY_LENGTH: usize = 3072;
65 const CHUNK_SIZE_LIMIT: u64 = 32 * 1024;
66
67 impl RestServer {
68 /// Creates a new instance.
69 pub fn new(api_config: ApiConfig) -> Self {
70 Self {
71 api_config: Arc::new(api_config),
72 }
73 }
74 }
75
76 impl Service<&Pin<Box<tokio_openssl::SslStream<tokio::net::TcpStream>>>>
77 for RestServer
78 {
79 type Response = ApiService;
80 type Error = Error;
81 type Future = Pin<Box<dyn Future<Output = Result<ApiService, Error>> + Send>>;
82
83 fn poll_ready(&mut self, _cx: &mut Context) -> Poll<Result<(), Self::Error>> {
84 Poll::Ready(Ok(()))
85 }
86
87 fn call(
88 &mut self,
89 ctx: &Pin<Box<tokio_openssl::SslStream<tokio::net::TcpStream>>>,
90 ) -> Self::Future {
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 {
94 peer,
95 api_config: self.api_config.clone(),
96 })
97 .boxed(),
98 }
99 }
100 }
101
102 impl Service<&hyper::server::conn::AddrStream> for RestServer {
103 type Response = ApiService;
104 type Error = Error;
105 type Future = Pin<Box<dyn Future<Output = Result<ApiService, Error>> + Send>>;
106
107 fn poll_ready(&mut self, _cx: &mut Context) -> Poll<Result<(), Self::Error>> {
108 Poll::Ready(Ok(()))
109 }
110
111 fn call(&mut self, ctx: &hyper::server::conn::AddrStream) -> Self::Future {
112 let peer = ctx.remote_addr();
113 future::ok(ApiService {
114 peer,
115 api_config: self.api_config.clone(),
116 })
117 .boxed()
118 }
119 }
120
121 impl Service<&tokio::net::UnixStream> for RestServer {
122 type Response = ApiService;
123 type Error = Error;
124 type Future = Pin<Box<dyn Future<Output = Result<ApiService, Error>> + Send>>;
125
126 fn poll_ready(&mut self, _cx: &mut Context) -> Poll<Result<(), Self::Error>> {
127 Poll::Ready(Ok(()))
128 }
129
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 {
135 peer: fake_peer,
136 api_config: self.api_config.clone(),
137 })
138 .boxed()
139 }
140 }
141
142 // Helper [Service] containing the peer Address
143 //
144 // The lower level connection [Service] implementation on
145 // [RestServer] extracts the peer address and return an [ApiService].
146 //
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
149 // not export it.
150 pub struct ApiService {
151 pub peer: std::net::SocketAddr,
152 pub api_config: Arc<ApiConfig>,
153 }
154
155 fn log_response(
156 logfile: Option<&Arc<Mutex<FileLogger>>>,
157 peer: &std::net::SocketAddr,
158 method: hyper::Method,
159 path_query: &str,
160 resp: &Response<Body>,
161 user_agent: Option<String>,
162 ) {
163 if resp.extensions().get::<NoLogExtension>().is_some() {
164 return;
165 };
166
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())];
170
171 let status = resp.status();
172 if !(status.is_success() || status.is_informational()) {
173 let reason = status.canonical_reason().unwrap_or("unknown reason");
174
175 let message = match resp.extensions().get::<ErrorMessageExtension>() {
176 Some(data) => &data.0,
177 None => "request failed",
178 };
179
180 log::error!(
181 "{} {}: {} {}: [client {}] {}",
182 method.as_str(),
183 path,
184 status.as_str(),
185 reason,
186 peer,
187 message
188 );
189 }
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(),
194 };
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());
199
200 logfile.lock().unwrap().log(format!(
201 "{} - {} [{}] \"{} {}\" {} {} {}",
202 peer.ip(),
203 auth_id,
204 datetime,
205 method.as_str(),
206 path,
207 status.as_str(),
208 resp.body().size_hint().lower(),
209 user_agent.unwrap_or_else(|| "-".to_string()),
210 ));
211 }
212 }
213
214 fn get_proxied_peer(headers: &HeaderMap) -> Option<std::net::SocketAddr> {
215 lazy_static! {
216 static ref RE: Regex = Regex::new(r#"for="([^"]+)""#).unwrap();
217 }
218 let forwarded = headers.get(header::FORWARDED)?.to_str().ok()?;
219 let capture = RE.captures(&forwarded)?;
220 let rhost = capture.get(1)?.as_str();
221
222 rhost.parse().ok()
223 }
224
225 fn get_user_agent(headers: &HeaderMap) -> Option<String> {
226 let agent = headers.get(header::USER_AGENT)?.to_str();
227 agent
228 .map(|s| {
229 let mut s = s.to_owned();
230 s.truncate(128);
231 s
232 })
233 .ok()
234 }
235
236 impl Service<Request<Body>> for ApiService {
237 type Response = Response<Body>;
238 type Error = Error;
239 #[allow(clippy::type_complexity)]
240 type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
241
242 fn poll_ready(&mut self, _cx: &mut Context) -> Poll<Result<(), Self::Error>> {
243 Poll::Ready(Ok(()))
244 }
245
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());
250
251 let config = Arc::clone(&self.api_config);
252 let peer = match get_proxied_peer(req.headers()) {
253 Some(proxied_peer) => proxied_peer,
254 None => self.peer,
255 };
256 async move {
257 let response = match handle_request(Arc::clone(&config), req, &peer).await {
258 Ok(response) => response,
259 Err(err) => {
260 let (err, code) = match err.downcast_ref::<HttpError>() {
261 Some(apierr) => (apierr.message.clone(), apierr.code),
262 _ => (err.to_string(), StatusCode::BAD_REQUEST),
263 };
264 Response::builder()
265 .status(code)
266 .extension(ErrorMessageExtension(err.to_string()))
267 .body(err.into())?
268 }
269 };
270 let logger = config.get_access_log();
271 log_response(logger, &peer, method, &path, &response, user_agent);
272 Ok(response)
273 }
274 .boxed()
275 }
276 }
277
278 fn parse_query_parameters<S: 'static + BuildHasher + Send>(
279 param_schema: ParameterSchema,
280 form: &str, // x-www-form-urlencoded body data
281 parts: &Parts,
282 uri_param: &HashMap<String, String, S>,
283 ) -> Result<Value, Error> {
284 let mut param_list: Vec<(String, String)> = vec![];
285
286 if !form.is_empty() {
287 for (k, v) in form_urlencoded::parse(form.as_bytes()).into_owned() {
288 param_list.push((k, v));
289 }
290 }
291
292 if let Some(query_str) = parts.uri.query() {
293 for (k, v) in form_urlencoded::parse(query_str.as_bytes()).into_owned() {
294 if k == "_dc" {
295 continue;
296 } // skip extjs "disable cache" parameter
297 param_list.push((k, v));
298 }
299 }
300
301 for (k, v) in uri_param {
302 param_list.push((k.clone(), v.clone()));
303 }
304
305 let params = parse_parameter_strings(&param_list, param_schema, true)?;
306
307 Ok(params)
308 }
309
310 async fn get_request_parameters<S: 'static + BuildHasher + Send>(
311 param_schema: ParameterSchema,
312 parts: Parts,
313 req_body: Body,
314 uri_param: HashMap<String, String, S>,
315 ) -> Result<Value, Error> {
316 let mut is_json = false;
317
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")) => {
321 is_json = false;
322 }
323 Ok(Some("application/json")) => {
324 is_json = true;
325 }
326 _ => bail!("unsupported content type {:?}", value.to_str()),
327 }
328 }
329
330 let body = TryStreamExt::map_err(req_body, |err| {
331 http_err!(BAD_REQUEST, "Problems reading request body: {}", err)
332 })
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);
337 Ok(acc)
338 } else {
339 Err(http_err!(BAD_REQUEST, "Request body too large"))
340 }
341 })
342 .await?;
343
344 let utf8_data =
345 std::str::from_utf8(&body).map_err(|err| format_err!("Request body not uft8: {}", err))?;
346
347 if is_json {
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)?;
352 }
353 }
354 verify_json_object(&params, &param_schema)?;
355 return Ok(params);
356 } else {
357 parse_query_parameters(param_schema, utf8_data, &parts, &uri_param)
358 }
359 }
360
361 struct NoLogExtension();
362
363 async fn proxy_protected_request(
364 info: &'static ApiMethod,
365 mut parts: Parts,
366 req_body: Body,
367 peer: &std::net::SocketAddr,
368 ) -> Result<Response<Body>, Error> {
369 let mut uri_parts = parts.uri.clone().into_parts();
370
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();
374
375 parts.uri = new_uri;
376
377 let mut request = Request::from_parts(parts, req_body);
378 request.headers_mut().insert(
379 header::FORWARDED,
380 format!("for=\"{}\";", peer).parse().unwrap(),
381 );
382
383 let reload_timezone = info.reload_timezone;
384
385 let resp = hyper::client::Client::new()
386 .request(request)
387 .map_err(Error::from)
388 .map_ok(|mut resp| {
389 resp.extensions_mut().insert(NoLogExtension());
390 resp
391 })
392 .await?;
393
394 if reload_timezone {
395 unsafe {
396 tzset();
397 }
398 }
399
400 Ok(resp)
401 }
402
403 pub(crate) async fn handle_api_request<Env: RpcEnvironment, S: 'static + BuildHasher + Send>(
404 mut rpcenv: Env,
405 info: &'static ApiMethod,
406 formatter: &'static dyn OutputFormatter,
407 parts: Parts,
408 req_body: Body,
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);
413
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
418 }
419 ApiHandler::Sync(handler) => {
420 let params =
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))
423 }
424 ApiHandler::Async(handler) => {
425 let params =
426 get_request_parameters(info.parameters, parts, req_body, uri_param).await?;
427 (handler)(params, info, &mut rpcenv)
428 .await
429 .map(|data| formatter.format_data(data, &rpcenv))
430 }
431 };
432
433 let mut resp = match result {
434 Ok(resp) => resp,
435 Err(err) => {
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;
439 }
440 }
441 formatter.format_error(err)
442 }
443 };
444
445 let resp = match compression {
446 Some(CompressionMethod::Deflate) => {
447 resp.headers_mut().insert(
448 header::CONTENT_ENCODING,
449 CompressionMethod::Deflate.content_encoding(),
450 );
451 resp.map(|body| {
452 Body::wrap_stream(DeflateEncoder::with_quality(
453 TryStreamExt::map_err(body, |err| {
454 proxmox::io_format_err!("error during compression: {}", err)
455 }),
456 Level::Default,
457 ))
458 })
459 }
460 None => resp,
461 };
462
463 if info.reload_timezone {
464 unsafe {
465 tzset();
466 }
467 }
468
469 Ok(resp)
470 }
471
472
473 fn extension_to_content_type(filename: &Path) -> (&'static str, bool) {
474 if let Some(ext) = filename.extension().and_then(|osstr| osstr.to_str()) {
475 return match ext {
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),
495 };
496 }
497
498 ("application/octet-stream", false)
499 }
500
501 async fn simple_static_file_download(
502 filename: PathBuf,
503 content_type: &'static str,
504 compression: Option<CompressionMethod>,
505 ) -> Result<Response<Body>, Error> {
506 use tokio::io::AsyncReadExt;
507
508 let mut file = File::open(filename)
509 .await
510 .map_err(|err| http_err!(BAD_REQUEST, "File open failed: {}", err))?;
511
512 let mut data: Vec<u8> = Vec::new();
513
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)
518 .await?;
519 let mut response = Response::new(enc.into_inner().into());
520 response.headers_mut().insert(
521 header::CONTENT_ENCODING,
522 CompressionMethod::Deflate.content_encoding(),
523 );
524 response
525 }
526 None => {
527 file.read_to_end(&mut data)
528 .await
529 .map_err(|err| http_err!(BAD_REQUEST, "File read failed: {}", err))?;
530 Response::new(data.into())
531 }
532 };
533
534 response.headers_mut().insert(
535 header::CONTENT_TYPE,
536 header::HeaderValue::from_static(content_type),
537 );
538
539 Ok(response)
540 }
541
542 async fn chuncked_static_file_download(
543 filename: PathBuf,
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);
550
551 let file = File::open(filename)
552 .await
553 .map_err(|err| http_err!(BAD_REQUEST, "File open failed: {}", err))?;
554
555 let body = match compression {
556 Some(CompressionMethod::Deflate) => {
557 resp = resp.header(
558 header::CONTENT_ENCODING,
559 CompressionMethod::Deflate.content_encoding(),
560 );
561 Body::wrap_stream(DeflateEncoder::with_quality(
562 AsyncReaderStream::new(file),
563 Level::Default,
564 ))
565 }
566 None => Body::wrap_stream(AsyncReaderStream::new(file)),
567 };
568
569 Ok(resp.body(body).unwrap())
570 }
571
572 async fn handle_static_file_download(
573 filename: PathBuf,
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))
578 .await?;
579
580 let (content_type, nocomp) = extension_to_content_type(&filename);
581 let compression = if nocomp { None } else { compression };
582
583 if metadata.len() < CHUNK_SIZE_LIMIT {
584 simple_static_file_download(filename, content_type, compression).await
585 } else {
586 chuncked_static_file_download(filename, content_type, compression).await
587 }
588 }
589
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() {
595 return Some(method);
596 }
597 }
598 }
599 None
600 }
601
602 async fn handle_request(
603 api: Arc<ApiConfig>,
604 req: Request<Body>,
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())?;
610
611 let comp_len = components.len();
612
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)
617 .body("".into())
618 .unwrap());
619 }
620
621 let env_type = api.env_type();
622 let mut rpcenv = RestEnvironment::new(env_type, Arc::clone(&api));
623
624 rpcenv.set_client_ip(Some(*peer));
625
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);
628
629 if comp_len >= 1 && components[0] == "api2" {
630 if comp_len >= 2 {
631 let format = components[1];
632
633 let formatter: &dyn OutputFormatter = match format {
634 "json" => JSON_FORMATTER,
635 "extjs" => EXTJS_FORMATTER,
636 _ => bail!("Unsupported output format '{}'.", format),
637 };
638
639 let mut uri_param = HashMap::new();
640 let api_method = api.find_method(&components[2..], method.clone(), &mut uri_param);
641
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
646 }
647 }
648
649 let mut user_info: Box<dyn UserInformation + Send + Sync> = Box::new(EmptyUserInformation {});
650
651 if auth_required {
652 match api.check_auth(&parts.headers, &method).await {
653 Ok((authid, info)) => {
654 rpcenv.set_auth_id(Some(authid));
655 user_info = info;
656 }
657 Err(auth_err) => {
658 let err = match auth_err {
659 AuthError::Generic(err) => err,
660 AuthError::NoData => {
661 format_err!("no authentication credentials provided.")
662 }
663 };
664 // fixme: log Username??
665 rpcenv.log_failed_auth(None, &err.to_string());
666
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));
671 }
672 }
673 }
674
675 match api_method {
676 None => {
677 let err = http_err!(NOT_FOUND, "Path '{}' not found.", path);
678 return Ok(formatter.format_error(err));
679 }
680 Some(api_method) => {
681 let auth_id = rpcenv.get_auth_id();
682 let user_info = user_info;
683
684 if !check_api_permission(
685 api_method.access.permission,
686 auth_id.as_deref(),
687 &uri_param,
688 user_info.as_ref(),
689 ) {
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));
693 }
694
695 let result = if api_method.protected && env_type == RpcEnvironmentType::PUBLIC {
696 proxy_protected_request(api_method, parts, body, peer).await
697 } else {
698 handle_api_request(rpcenv, api_method, formatter, parts, body, uri_param)
699 .await
700 };
701
702 let mut response = match result {
703 Ok(resp) => resp,
704 Err(err) => formatter.format_error(err),
705 };
706
707 if let Some(auth_id) = auth_id {
708 response.extensions_mut().insert(AuthStringExtension(auth_id));
709 }
710
711 return Ok(response);
712 }
713 }
714 }
715 } else {
716 // not Auth required for accessing files!
717
718 if method != hyper::Method::GET {
719 bail!("Unsupported HTTP method {}", method);
720 }
721
722 if comp_len == 0 {
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);
727 }
728 Err(AuthError::Generic(_)) => {
729 tokio::time::sleep_until(Instant::from_std(delay_unauth_time)).await;
730 }
731 Err(AuthError::NoData) => {}
732 }
733 return Ok(api.get_index(rpcenv, parts).await);
734 } else {
735 let filename = api.find_alias(&components);
736 let compression = extract_compression_method(&parts.headers);
737 return handle_static_file_download(filename, compression).await;
738 }
739 }
740
741 Err(http_err!(NOT_FOUND, "Path '{}' not found.", path))
742 }