]> git.proxmox.com Git - proxmox-backup.git/blob - proxmox-rest-server/src/rest.rs
proxmox-rest-server: improve ApiService docs
[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::api::schema::{
25 parse_parameter_strings, parse_simple_value, verify_json_object, ObjectSchemaType,
26 ParameterSchema,
27 };
28 use proxmox::api::{
29 check_api_permission, ApiHandler, ApiMethod, HttpError, Permission, RpcEnvironment,
30 RpcEnvironmentType, UserInformation,
31 };
32 use proxmox::http_err;
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 extract_cookie, 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 pub struct ApiService {
147 pub peer: std::net::SocketAddr,
148 pub api_config: Arc<ApiConfig>,
149 }
150
151 fn log_response(
152 logfile: Option<&Arc<Mutex<FileLogger>>>,
153 peer: &std::net::SocketAddr,
154 method: hyper::Method,
155 path_query: &str,
156 resp: &Response<Body>,
157 user_agent: Option<String>,
158 ) {
159 if resp.extensions().get::<NoLogExtension>().is_some() {
160 return;
161 };
162
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())];
166
167 let status = resp.status();
168 if !(status.is_success() || status.is_informational()) {
169 let reason = status.canonical_reason().unwrap_or("unknown reason");
170
171 let message = match resp.extensions().get::<ErrorMessageExtension>() {
172 Some(data) => &data.0,
173 None => "request failed",
174 };
175
176 log::error!(
177 "{} {}: {} {}: [client {}] {}",
178 method.as_str(),
179 path,
180 status.as_str(),
181 reason,
182 peer,
183 message
184 );
185 }
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(),
190 };
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());
195
196 logfile.lock().unwrap().log(format!(
197 "{} - {} [{}] \"{} {}\" {} {} {}",
198 peer.ip(),
199 auth_id,
200 datetime,
201 method.as_str(),
202 path,
203 status.as_str(),
204 resp.body().size_hint().lower(),
205 user_agent.unwrap_or_else(|| "-".to_string()),
206 ));
207 }
208 }
209
210 fn get_proxied_peer(headers: &HeaderMap) -> Option<std::net::SocketAddr> {
211 lazy_static! {
212 static ref RE: Regex = Regex::new(r#"for="([^"]+)""#).unwrap();
213 }
214 let forwarded = headers.get(header::FORWARDED)?.to_str().ok()?;
215 let capture = RE.captures(&forwarded)?;
216 let rhost = capture.get(1)?.as_str();
217
218 rhost.parse().ok()
219 }
220
221 fn get_user_agent(headers: &HeaderMap) -> Option<String> {
222 let agent = headers.get(header::USER_AGENT)?.to_str();
223 agent
224 .map(|s| {
225 let mut s = s.to_owned();
226 s.truncate(128);
227 s
228 })
229 .ok()
230 }
231
232 impl Service<Request<Body>> for ApiService {
233 type Response = Response<Body>;
234 type Error = Error;
235 #[allow(clippy::type_complexity)]
236 type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
237
238 fn poll_ready(&mut self, _cx: &mut Context) -> Poll<Result<(), Self::Error>> {
239 Poll::Ready(Ok(()))
240 }
241
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());
246
247 let config = Arc::clone(&self.api_config);
248 let peer = match get_proxied_peer(req.headers()) {
249 Some(proxied_peer) => proxied_peer,
250 None => self.peer,
251 };
252 async move {
253 let response = match handle_request(Arc::clone(&config), req, &peer).await {
254 Ok(response) => response,
255 Err(err) => {
256 let (err, code) = match err.downcast_ref::<HttpError>() {
257 Some(apierr) => (apierr.message.clone(), apierr.code),
258 _ => (err.to_string(), StatusCode::BAD_REQUEST),
259 };
260 Response::builder()
261 .status(code)
262 .extension(ErrorMessageExtension(err.to_string()))
263 .body(err.into())?
264 }
265 };
266 let logger = config.get_access_log();
267 log_response(logger, &peer, method, &path, &response, user_agent);
268 Ok(response)
269 }
270 .boxed()
271 }
272 }
273
274 fn parse_query_parameters<S: 'static + BuildHasher + Send>(
275 param_schema: ParameterSchema,
276 form: &str, // x-www-form-urlencoded body data
277 parts: &Parts,
278 uri_param: &HashMap<String, String, S>,
279 ) -> Result<Value, Error> {
280 let mut param_list: Vec<(String, String)> = vec![];
281
282 if !form.is_empty() {
283 for (k, v) in form_urlencoded::parse(form.as_bytes()).into_owned() {
284 param_list.push((k, v));
285 }
286 }
287
288 if let Some(query_str) = parts.uri.query() {
289 for (k, v) in form_urlencoded::parse(query_str.as_bytes()).into_owned() {
290 if k == "_dc" {
291 continue;
292 } // skip extjs "disable cache" parameter
293 param_list.push((k, v));
294 }
295 }
296
297 for (k, v) in uri_param {
298 param_list.push((k.clone(), v.clone()));
299 }
300
301 let params = parse_parameter_strings(&param_list, param_schema, true)?;
302
303 Ok(params)
304 }
305
306 async fn get_request_parameters<S: 'static + BuildHasher + Send>(
307 param_schema: ParameterSchema,
308 parts: Parts,
309 req_body: Body,
310 uri_param: HashMap<String, String, S>,
311 ) -> Result<Value, Error> {
312 let mut is_json = false;
313
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")) => {
317 is_json = false;
318 }
319 Ok(Some("application/json")) => {
320 is_json = true;
321 }
322 _ => bail!("unsupported content type {:?}", value.to_str()),
323 }
324 }
325
326 let body = TryStreamExt::map_err(req_body, |err| {
327 http_err!(BAD_REQUEST, "Problems reading request body: {}", err)
328 })
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);
333 Ok(acc)
334 } else {
335 Err(http_err!(BAD_REQUEST, "Request body too large"))
336 }
337 })
338 .await?;
339
340 let utf8_data =
341 std::str::from_utf8(&body).map_err(|err| format_err!("Request body not uft8: {}", err))?;
342
343 if is_json {
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)?;
348 }
349 }
350 verify_json_object(&params, &param_schema)?;
351 return Ok(params);
352 } else {
353 parse_query_parameters(param_schema, utf8_data, &parts, &uri_param)
354 }
355 }
356
357 struct NoLogExtension();
358
359 async fn proxy_protected_request(
360 info: &'static ApiMethod,
361 mut parts: Parts,
362 req_body: Body,
363 peer: &std::net::SocketAddr,
364 ) -> Result<Response<Body>, Error> {
365 let mut uri_parts = parts.uri.clone().into_parts();
366
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();
370
371 parts.uri = new_uri;
372
373 let mut request = Request::from_parts(parts, req_body);
374 request.headers_mut().insert(
375 header::FORWARDED,
376 format!("for=\"{}\";", peer).parse().unwrap(),
377 );
378
379 let reload_timezone = info.reload_timezone;
380
381 let resp = hyper::client::Client::new()
382 .request(request)
383 .map_err(Error::from)
384 .map_ok(|mut resp| {
385 resp.extensions_mut().insert(NoLogExtension());
386 resp
387 })
388 .await?;
389
390 if reload_timezone {
391 unsafe {
392 tzset();
393 }
394 }
395
396 Ok(resp)
397 }
398
399 pub(crate) async fn handle_api_request<Env: RpcEnvironment, S: 'static + BuildHasher + Send>(
400 mut rpcenv: Env,
401 info: &'static ApiMethod,
402 formatter: &'static dyn OutputFormatter,
403 parts: Parts,
404 req_body: Body,
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);
409
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
414 }
415 ApiHandler::Sync(handler) => {
416 let params =
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))
419 }
420 ApiHandler::Async(handler) => {
421 let params =
422 get_request_parameters(info.parameters, parts, req_body, uri_param).await?;
423 (handler)(params, info, &mut rpcenv)
424 .await
425 .map(|data| formatter.format_data(data, &rpcenv))
426 }
427 };
428
429 let mut resp = match result {
430 Ok(resp) => resp,
431 Err(err) => {
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;
435 }
436 }
437 formatter.format_error(err)
438 }
439 };
440
441 let resp = match compression {
442 Some(CompressionMethod::Deflate) => {
443 resp.headers_mut().insert(
444 header::CONTENT_ENCODING,
445 CompressionMethod::Deflate.content_encoding(),
446 );
447 resp.map(|body| {
448 Body::wrap_stream(DeflateEncoder::with_quality(
449 TryStreamExt::map_err(body, |err| {
450 proxmox::io_format_err!("error during compression: {}", err)
451 }),
452 Level::Default,
453 ))
454 })
455 }
456 None => resp,
457 };
458
459 if info.reload_timezone {
460 unsafe {
461 tzset();
462 }
463 }
464
465 Ok(resp)
466 }
467
468
469 fn extension_to_content_type(filename: &Path) -> (&'static str, bool) {
470 if let Some(ext) = filename.extension().and_then(|osstr| osstr.to_str()) {
471 return match ext {
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),
491 };
492 }
493
494 ("application/octet-stream", false)
495 }
496
497 async fn simple_static_file_download(
498 filename: PathBuf,
499 content_type: &'static str,
500 compression: Option<CompressionMethod>,
501 ) -> Result<Response<Body>, Error> {
502 use tokio::io::AsyncReadExt;
503
504 let mut file = File::open(filename)
505 .await
506 .map_err(|err| http_err!(BAD_REQUEST, "File open failed: {}", err))?;
507
508 let mut data: Vec<u8> = Vec::new();
509
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)
514 .await?;
515 let mut response = Response::new(enc.into_inner().into());
516 response.headers_mut().insert(
517 header::CONTENT_ENCODING,
518 CompressionMethod::Deflate.content_encoding(),
519 );
520 response
521 }
522 None => {
523 file.read_to_end(&mut data)
524 .await
525 .map_err(|err| http_err!(BAD_REQUEST, "File read failed: {}", err))?;
526 Response::new(data.into())
527 }
528 };
529
530 response.headers_mut().insert(
531 header::CONTENT_TYPE,
532 header::HeaderValue::from_static(content_type),
533 );
534
535 Ok(response)
536 }
537
538 async fn chuncked_static_file_download(
539 filename: PathBuf,
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);
546
547 let file = File::open(filename)
548 .await
549 .map_err(|err| http_err!(BAD_REQUEST, "File open failed: {}", err))?;
550
551 let body = match compression {
552 Some(CompressionMethod::Deflate) => {
553 resp = resp.header(
554 header::CONTENT_ENCODING,
555 CompressionMethod::Deflate.content_encoding(),
556 );
557 Body::wrap_stream(DeflateEncoder::with_quality(
558 AsyncReaderStream::new(file),
559 Level::Default,
560 ))
561 }
562 None => Body::wrap_stream(AsyncReaderStream::new(file)),
563 };
564
565 Ok(resp.body(body).unwrap())
566 }
567
568 async fn handle_static_file_download(
569 filename: PathBuf,
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))
574 .await?;
575
576 let (content_type, nocomp) = extension_to_content_type(&filename);
577 let compression = if nocomp { None } else { compression };
578
579 if metadata.len() < CHUNK_SIZE_LIMIT {
580 simple_static_file_download(filename, content_type, compression).await
581 } else {
582 chuncked_static_file_download(filename, content_type, compression).await
583 }
584 }
585
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");
589 }
590 None
591 }
592
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() {
598 return Some(method);
599 }
600 }
601 }
602 None
603 }
604
605 async fn handle_request(
606 api: Arc<ApiConfig>,
607 req: Request<Body>,
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())?;
613
614 let comp_len = components.len();
615
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)
620 .body("".into())
621 .unwrap());
622 }
623
624 let env_type = api.env_type();
625 let mut rpcenv = RestEnvironment::new(env_type, Arc::clone(&api));
626
627 rpcenv.set_client_ip(Some(*peer));
628
629 let auth = &api.api_auth;
630
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);
633
634 if comp_len >= 1 && components[0] == "api2" {
635 if comp_len >= 2 {
636 let format = components[1];
637
638 let formatter: &dyn OutputFormatter = match format {
639 "json" => JSON_FORMATTER,
640 "extjs" => EXTJS_FORMATTER,
641 _ => bail!("Unsupported output format '{}'.", format),
642 };
643
644 let mut uri_param = HashMap::new();
645 let api_method = api.find_method(&components[2..], method.clone(), &mut uri_param);
646
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
651 }
652 }
653
654 let mut user_info: Box<dyn UserInformation + Send + Sync> = Box::new(EmptyUserInformation {});
655
656 if auth_required {
657 match auth.check_auth(&parts.headers, &method) {
658 Ok((authid, info)) => {
659 rpcenv.set_auth_id(Some(authid));
660 user_info = info;
661 }
662 Err(auth_err) => {
663 let err = match auth_err {
664 AuthError::Generic(err) => err,
665 AuthError::NoData => {
666 format_err!("no authentication credentials provided.")
667 }
668 };
669 // fixme: log Username??
670 rpcenv.log_failed_auth(None, &err.to_string());
671
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));
676 }
677 }
678 }
679
680 match api_method {
681 None => {
682 let err = http_err!(NOT_FOUND, "Path '{}' not found.", path);
683 return Ok(formatter.format_error(err));
684 }
685 Some(api_method) => {
686 let auth_id = rpcenv.get_auth_id();
687 let user_info = user_info;
688
689 if !check_api_permission(
690 api_method.access.permission,
691 auth_id.as_deref(),
692 &uri_param,
693 user_info.as_ref(),
694 ) {
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));
698 }
699
700 let result = if api_method.protected && env_type == RpcEnvironmentType::PUBLIC {
701 proxy_protected_request(api_method, parts, body, peer).await
702 } else {
703 handle_api_request(rpcenv, api_method, formatter, parts, body, uri_param)
704 .await
705 };
706
707 let mut response = match result {
708 Ok(resp) => resp,
709 Err(err) => formatter.format_error(err),
710 };
711
712 if let Some(auth_id) = auth_id {
713 response.extensions_mut().insert(AuthStringExtension(auth_id));
714 }
715
716 return Ok(response);
717 }
718 }
719 }
720 } else {
721 // not Auth required for accessing files!
722
723 if method != hyper::Method::GET {
724 bail!("Unsupported HTTP method {}", method);
725 }
726
727 if comp_len == 0 {
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));
732 }
733 Err(AuthError::Generic(_)) => {
734 tokio::time::sleep_until(Instant::from_std(delay_unauth_time)).await;
735 }
736 Err(AuthError::NoData) => {}
737 }
738 return Ok(api.get_index(None, language, parts));
739 } else {
740 let filename = api.find_alias(&components);
741 let compression = extract_compression_method(&parts.headers);
742 return handle_static_file_download(filename, compression).await;
743 }
744 }
745
746 Err(http_err!(NOT_FOUND, "Path '{}' not found.", path))
747 }