]> git.proxmox.com Git - proxmox-backup.git/blob - proxmox-rest-server/src/rest.rs
rest-server: use hypers AddrIncoming for proxmox-backup-api
[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
23 use proxmox::api::schema::{
24 parse_parameter_strings, parse_simple_value, verify_json_object, ObjectSchemaType,
25 ParameterSchema,
26 };
27 use proxmox::api::{
28 check_api_permission, ApiHandler, ApiMethod, HttpError, Permission, RpcEnvironment,
29 RpcEnvironmentType, UserInformation,
30 };
31 use proxmox::http_err;
32
33 use pbs_tools::compression::{DeflateEncoder, Level};
34 use pbs_tools::stream::AsyncReaderStream;
35
36 use crate::{
37 ApiConfig, FileLogger, AuthError, RestEnvironment, CompressionMethod,
38 extract_cookie, normalize_uri_path, formatter::*,
39 };
40
41 extern "C" {
42 fn tzset();
43 }
44
45 struct AuthStringExtension(String);
46
47 struct EmptyUserInformation {}
48
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 }
53 }
54
55 pub struct RestServer {
56 pub api_config: Arc<ApiConfig>,
57 }
58
59 const MAX_URI_QUERY_LENGTH: usize = 3072;
60 const CHUNK_SIZE_LIMIT: u64 = 32 * 1024;
61
62 impl RestServer {
63 pub fn new(api_config: ApiConfig) -> Self {
64 Self {
65 api_config: Arc::new(api_config),
66 }
67 }
68 }
69
70 impl tower_service::Service<&Pin<Box<tokio_openssl::SslStream<tokio::net::TcpStream>>>>
71 for RestServer
72 {
73 type Response = ApiService;
74 type Error = Error;
75 type Future = Pin<Box<dyn Future<Output = Result<ApiService, Error>> + Send>>;
76
77 fn poll_ready(&mut self, _cx: &mut Context) -> Poll<Result<(), Self::Error>> {
78 Poll::Ready(Ok(()))
79 }
80
81 fn call(
82 &mut self,
83 ctx: &Pin<Box<tokio_openssl::SslStream<tokio::net::TcpStream>>>,
84 ) -> Self::Future {
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 {
88 peer,
89 api_config: self.api_config.clone(),
90 })
91 .boxed(),
92 }
93 }
94 }
95
96 impl tower_service::Service<&hyper::server::conn::AddrStream> for RestServer {
97 type Response = ApiService;
98 type Error = Error;
99 type Future = Pin<Box<dyn Future<Output = Result<ApiService, Error>> + Send>>;
100
101 fn poll_ready(&mut self, _cx: &mut Context) -> Poll<Result<(), Self::Error>> {
102 Poll::Ready(Ok(()))
103 }
104
105 fn call(&mut self, ctx: &hyper::server::conn::AddrStream) -> Self::Future {
106 let peer = ctx.remote_addr();
107 future::ok(ApiService {
108 peer,
109 api_config: self.api_config.clone(),
110 })
111 .boxed()
112 }
113 }
114
115 impl tower_service::Service<&tokio::net::UnixStream> for RestServer {
116 type Response = ApiService;
117 type Error = Error;
118 type Future = Pin<Box<dyn Future<Output = Result<ApiService, Error>> + Send>>;
119
120 fn poll_ready(&mut self, _cx: &mut Context) -> Poll<Result<(), Self::Error>> {
121 Poll::Ready(Ok(()))
122 }
123
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 {
129 peer: fake_peer,
130 api_config: self.api_config.clone(),
131 })
132 .boxed()
133 }
134 }
135
136 pub struct ApiService {
137 pub peer: std::net::SocketAddr,
138 pub api_config: Arc<ApiConfig>,
139 }
140
141 fn log_response(
142 logfile: Option<&Arc<Mutex<FileLogger>>>,
143 peer: &std::net::SocketAddr,
144 method: hyper::Method,
145 path_query: &str,
146 resp: &Response<Body>,
147 user_agent: Option<String>,
148 ) {
149 if resp.extensions().get::<NoLogExtension>().is_some() {
150 return;
151 };
152
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())];
156
157 let status = resp.status();
158 if !(status.is_success() || status.is_informational()) {
159 let reason = status.canonical_reason().unwrap_or("unknown reason");
160
161 let message = match resp.extensions().get::<ErrorMessageExtension>() {
162 Some(data) => &data.0,
163 None => "request failed",
164 };
165
166 log::error!(
167 "{} {}: {} {}: [client {}] {}",
168 method.as_str(),
169 path,
170 status.as_str(),
171 reason,
172 peer,
173 message
174 );
175 }
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(),
180 };
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());
185
186 logfile.lock().unwrap().log(format!(
187 "{} - {} [{}] \"{} {}\" {} {} {}",
188 peer.ip(),
189 auth_id,
190 datetime,
191 method.as_str(),
192 path,
193 status.as_str(),
194 resp.body().size_hint().lower(),
195 user_agent.unwrap_or_else(|| "-".to_string()),
196 ));
197 }
198 }
199
200 fn get_proxied_peer(headers: &HeaderMap) -> Option<std::net::SocketAddr> {
201 lazy_static! {
202 static ref RE: Regex = Regex::new(r#"for="([^"]+)""#).unwrap();
203 }
204 let forwarded = headers.get(header::FORWARDED)?.to_str().ok()?;
205 let capture = RE.captures(&forwarded)?;
206 let rhost = capture.get(1)?.as_str();
207
208 rhost.parse().ok()
209 }
210
211 fn get_user_agent(headers: &HeaderMap) -> Option<String> {
212 let agent = headers.get(header::USER_AGENT)?.to_str();
213 agent
214 .map(|s| {
215 let mut s = s.to_owned();
216 s.truncate(128);
217 s
218 })
219 .ok()
220 }
221
222 impl tower_service::Service<Request<Body>> for ApiService {
223 type Response = Response<Body>;
224 type Error = Error;
225 #[allow(clippy::type_complexity)]
226 type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
227
228 fn poll_ready(&mut self, _cx: &mut Context) -> Poll<Result<(), Self::Error>> {
229 Poll::Ready(Ok(()))
230 }
231
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());
236
237 let config = Arc::clone(&self.api_config);
238 let peer = match get_proxied_peer(req.headers()) {
239 Some(proxied_peer) => proxied_peer,
240 None => self.peer,
241 };
242 async move {
243 let response = match handle_request(Arc::clone(&config), req, &peer).await {
244 Ok(response) => response,
245 Err(err) => {
246 let (err, code) = match err.downcast_ref::<HttpError>() {
247 Some(apierr) => (apierr.message.clone(), apierr.code),
248 _ => (err.to_string(), StatusCode::BAD_REQUEST),
249 };
250 Response::builder()
251 .status(code)
252 .extension(ErrorMessageExtension(err.to_string()))
253 .body(err.into())?
254 }
255 };
256 let logger = config.get_access_log();
257 log_response(logger, &peer, method, &path, &response, user_agent);
258 Ok(response)
259 }
260 .boxed()
261 }
262 }
263
264 fn parse_query_parameters<S: 'static + BuildHasher + Send>(
265 param_schema: ParameterSchema,
266 form: &str, // x-www-form-urlencoded body data
267 parts: &Parts,
268 uri_param: &HashMap<String, String, S>,
269 ) -> Result<Value, Error> {
270 let mut param_list: Vec<(String, String)> = vec![];
271
272 if !form.is_empty() {
273 for (k, v) in form_urlencoded::parse(form.as_bytes()).into_owned() {
274 param_list.push((k, v));
275 }
276 }
277
278 if let Some(query_str) = parts.uri.query() {
279 for (k, v) in form_urlencoded::parse(query_str.as_bytes()).into_owned() {
280 if k == "_dc" {
281 continue;
282 } // skip extjs "disable cache" parameter
283 param_list.push((k, v));
284 }
285 }
286
287 for (k, v) in uri_param {
288 param_list.push((k.clone(), v.clone()));
289 }
290
291 let params = parse_parameter_strings(&param_list, param_schema, true)?;
292
293 Ok(params)
294 }
295
296 async fn get_request_parameters<S: 'static + BuildHasher + Send>(
297 param_schema: ParameterSchema,
298 parts: Parts,
299 req_body: Body,
300 uri_param: HashMap<String, String, S>,
301 ) -> Result<Value, Error> {
302 let mut is_json = false;
303
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")) => {
307 is_json = false;
308 }
309 Ok(Some("application/json")) => {
310 is_json = true;
311 }
312 _ => bail!("unsupported content type {:?}", value.to_str()),
313 }
314 }
315
316 let body = TryStreamExt::map_err(req_body, |err| {
317 http_err!(BAD_REQUEST, "Problems reading request body: {}", err)
318 })
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);
323 Ok(acc)
324 } else {
325 Err(http_err!(BAD_REQUEST, "Request body too large"))
326 }
327 })
328 .await?;
329
330 let utf8_data =
331 std::str::from_utf8(&body).map_err(|err| format_err!("Request body not uft8: {}", err))?;
332
333 if is_json {
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)?;
338 }
339 }
340 verify_json_object(&params, &param_schema)?;
341 return Ok(params);
342 } else {
343 parse_query_parameters(param_schema, utf8_data, &parts, &uri_param)
344 }
345 }
346
347 struct NoLogExtension();
348
349 async fn proxy_protected_request(
350 info: &'static ApiMethod,
351 mut parts: Parts,
352 req_body: Body,
353 peer: &std::net::SocketAddr,
354 ) -> Result<Response<Body>, Error> {
355 let mut uri_parts = parts.uri.clone().into_parts();
356
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();
360
361 parts.uri = new_uri;
362
363 let mut request = Request::from_parts(parts, req_body);
364 request.headers_mut().insert(
365 header::FORWARDED,
366 format!("for=\"{}\";", peer).parse().unwrap(),
367 );
368
369 let reload_timezone = info.reload_timezone;
370
371 let resp = hyper::client::Client::new()
372 .request(request)
373 .map_err(Error::from)
374 .map_ok(|mut resp| {
375 resp.extensions_mut().insert(NoLogExtension());
376 resp
377 })
378 .await?;
379
380 if reload_timezone {
381 unsafe {
382 tzset();
383 }
384 }
385
386 Ok(resp)
387 }
388
389 pub(crate) async fn handle_api_request<Env: RpcEnvironment, S: 'static + BuildHasher + Send>(
390 mut rpcenv: Env,
391 info: &'static ApiMethod,
392 formatter: &'static dyn OutputFormatter,
393 parts: Parts,
394 req_body: Body,
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);
399
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
404 }
405 ApiHandler::Sync(handler) => {
406 let params =
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))
409 }
410 ApiHandler::Async(handler) => {
411 let params =
412 get_request_parameters(info.parameters, parts, req_body, uri_param).await?;
413 (handler)(params, info, &mut rpcenv)
414 .await
415 .map(|data| formatter.format_data(data, &rpcenv))
416 }
417 };
418
419 let mut resp = match result {
420 Ok(resp) => resp,
421 Err(err) => {
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;
425 }
426 }
427 formatter.format_error(err)
428 }
429 };
430
431 let resp = match compression {
432 Some(CompressionMethod::Deflate) => {
433 resp.headers_mut().insert(
434 header::CONTENT_ENCODING,
435 CompressionMethod::Deflate.content_encoding(),
436 );
437 resp.map(|body| {
438 Body::wrap_stream(DeflateEncoder::with_quality(
439 TryStreamExt::map_err(body, |err| {
440 proxmox::io_format_err!("error during compression: {}", err)
441 }),
442 Level::Default,
443 ))
444 })
445 }
446 None => resp,
447 };
448
449 if info.reload_timezone {
450 unsafe {
451 tzset();
452 }
453 }
454
455 Ok(resp)
456 }
457
458
459 fn extension_to_content_type(filename: &Path) -> (&'static str, bool) {
460 if let Some(ext) = filename.extension().and_then(|osstr| osstr.to_str()) {
461 return match ext {
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),
481 };
482 }
483
484 ("application/octet-stream", false)
485 }
486
487 async fn simple_static_file_download(
488 filename: PathBuf,
489 content_type: &'static str,
490 compression: Option<CompressionMethod>,
491 ) -> Result<Response<Body>, Error> {
492 use tokio::io::AsyncReadExt;
493
494 let mut file = File::open(filename)
495 .await
496 .map_err(|err| http_err!(BAD_REQUEST, "File open failed: {}", err))?;
497
498 let mut data: Vec<u8> = Vec::new();
499
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)
504 .await?;
505 let mut response = Response::new(enc.into_inner().into());
506 response.headers_mut().insert(
507 header::CONTENT_ENCODING,
508 CompressionMethod::Deflate.content_encoding(),
509 );
510 response
511 }
512 None => {
513 file.read_to_end(&mut data)
514 .await
515 .map_err(|err| http_err!(BAD_REQUEST, "File read failed: {}", err))?;
516 Response::new(data.into())
517 }
518 };
519
520 response.headers_mut().insert(
521 header::CONTENT_TYPE,
522 header::HeaderValue::from_static(content_type),
523 );
524
525 Ok(response)
526 }
527
528 async fn chuncked_static_file_download(
529 filename: PathBuf,
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);
536
537 let file = File::open(filename)
538 .await
539 .map_err(|err| http_err!(BAD_REQUEST, "File open failed: {}", err))?;
540
541 let body = match compression {
542 Some(CompressionMethod::Deflate) => {
543 resp = resp.header(
544 header::CONTENT_ENCODING,
545 CompressionMethod::Deflate.content_encoding(),
546 );
547 Body::wrap_stream(DeflateEncoder::with_quality(
548 AsyncReaderStream::new(file),
549 Level::Default,
550 ))
551 }
552 None => Body::wrap_stream(AsyncReaderStream::new(file)),
553 };
554
555 Ok(resp.body(body).unwrap())
556 }
557
558 async fn handle_static_file_download(
559 filename: PathBuf,
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))
564 .await?;
565
566 let (content_type, nocomp) = extension_to_content_type(&filename);
567 let compression = if nocomp { None } else { compression };
568
569 if metadata.len() < CHUNK_SIZE_LIMIT {
570 simple_static_file_download(filename, content_type, compression).await
571 } else {
572 chuncked_static_file_download(filename, content_type, compression).await
573 }
574 }
575
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");
579 }
580 None
581 }
582
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() {
588 return Some(method);
589 }
590 }
591 }
592 None
593 }
594
595 async fn handle_request(
596 api: Arc<ApiConfig>,
597 req: Request<Body>,
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())?;
603
604 let comp_len = components.len();
605
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)
610 .body("".into())
611 .unwrap());
612 }
613
614 let env_type = api.env_type();
615 let mut rpcenv = RestEnvironment::new(env_type, Arc::clone(&api));
616
617 rpcenv.set_client_ip(Some(*peer));
618
619 let auth = &api.api_auth;
620
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);
623
624 if comp_len >= 1 && components[0] == "api2" {
625 if comp_len >= 2 {
626 let format = components[1];
627
628 let formatter: &dyn OutputFormatter = match format {
629 "json" => JSON_FORMATTER,
630 "extjs" => EXTJS_FORMATTER,
631 _ => bail!("Unsupported output format '{}'.", format),
632 };
633
634 let mut uri_param = HashMap::new();
635 let api_method = api.find_method(&components[2..], method.clone(), &mut uri_param);
636
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
641 }
642 }
643
644 let mut user_info: Box<dyn UserInformation + Send + Sync> = Box::new(EmptyUserInformation {});
645
646 if auth_required {
647 match auth.check_auth(&parts.headers, &method) {
648 Ok((authid, info)) => {
649 rpcenv.set_auth_id(Some(authid));
650 user_info = info;
651 }
652 Err(auth_err) => {
653 let err = match auth_err {
654 AuthError::Generic(err) => err,
655 AuthError::NoData => {
656 format_err!("no authentication credentials provided.")
657 }
658 };
659 // fixme: log Username??
660 rpcenv.log_failed_auth(None, &err.to_string());
661
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));
666 }
667 }
668 }
669
670 match api_method {
671 None => {
672 let err = http_err!(NOT_FOUND, "Path '{}' not found.", path);
673 return Ok(formatter.format_error(err));
674 }
675 Some(api_method) => {
676 let auth_id = rpcenv.get_auth_id();
677 let user_info = user_info;
678
679 if !check_api_permission(
680 api_method.access.permission,
681 auth_id.as_deref(),
682 &uri_param,
683 user_info.as_ref(),
684 ) {
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));
688 }
689
690 let result = if api_method.protected && env_type == RpcEnvironmentType::PUBLIC {
691 proxy_protected_request(api_method, parts, body, peer).await
692 } else {
693 handle_api_request(rpcenv, api_method, formatter, parts, body, uri_param)
694 .await
695 };
696
697 let mut response = match result {
698 Ok(resp) => resp,
699 Err(err) => formatter.format_error(err),
700 };
701
702 if let Some(auth_id) = auth_id {
703 response.extensions_mut().insert(AuthStringExtension(auth_id));
704 }
705
706 return Ok(response);
707 }
708 }
709 }
710 } else {
711 // not Auth required for accessing files!
712
713 if method != hyper::Method::GET {
714 bail!("Unsupported HTTP method {}", method);
715 }
716
717 if comp_len == 0 {
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));
722 }
723 Err(AuthError::Generic(_)) => {
724 tokio::time::sleep_until(Instant::from_std(delay_unauth_time)).await;
725 }
726 Err(AuthError::NoData) => {}
727 }
728 return Ok(api.get_index(None, language, parts));
729 } else {
730 let filename = api.find_alias(&components);
731 let compression = extract_compression_method(&parts.headers);
732 return handle_static_file_download(filename, compression).await;
733 }
734 }
735
736 Err(http_err!(NOT_FOUND, "Path '{}' not found.", path))
737 }