]> git.proxmox.com Git - proxmox-backup.git/blob - proxmox-rest-server/src/rest.rs
proxmox-rest-server: start module 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 pub struct ApiService {
143 pub peer: std::net::SocketAddr,
144 pub api_config: Arc<ApiConfig>,
145 }
146
147 fn log_response(
148 logfile: Option<&Arc<Mutex<FileLogger>>>,
149 peer: &std::net::SocketAddr,
150 method: hyper::Method,
151 path_query: &str,
152 resp: &Response<Body>,
153 user_agent: Option<String>,
154 ) {
155 if resp.extensions().get::<NoLogExtension>().is_some() {
156 return;
157 };
158
159 // we also log URL-to-long requests, so avoid message bigger than PIPE_BUF (4k on Linux)
160 // to profit from atomicty guarantees for O_APPEND opened logfiles
161 let path = &path_query[..MAX_URI_QUERY_LENGTH.min(path_query.len())];
162
163 let status = resp.status();
164 if !(status.is_success() || status.is_informational()) {
165 let reason = status.canonical_reason().unwrap_or("unknown reason");
166
167 let message = match resp.extensions().get::<ErrorMessageExtension>() {
168 Some(data) => &data.0,
169 None => "request failed",
170 };
171
172 log::error!(
173 "{} {}: {} {}: [client {}] {}",
174 method.as_str(),
175 path,
176 status.as_str(),
177 reason,
178 peer,
179 message
180 );
181 }
182 if let Some(logfile) = logfile {
183 let auth_id = match resp.extensions().get::<AuthStringExtension>() {
184 Some(AuthStringExtension(auth_id)) => auth_id.clone(),
185 None => "-".to_string(),
186 };
187 let now = proxmox::tools::time::epoch_i64();
188 // time format which apache/nginx use (by default), copied from pve-http-server
189 let datetime = proxmox::tools::time::strftime_local("%d/%m/%Y:%H:%M:%S %z", now)
190 .unwrap_or_else(|_| "-".to_string());
191
192 logfile.lock().unwrap().log(format!(
193 "{} - {} [{}] \"{} {}\" {} {} {}",
194 peer.ip(),
195 auth_id,
196 datetime,
197 method.as_str(),
198 path,
199 status.as_str(),
200 resp.body().size_hint().lower(),
201 user_agent.unwrap_or_else(|| "-".to_string()),
202 ));
203 }
204 }
205
206 fn get_proxied_peer(headers: &HeaderMap) -> Option<std::net::SocketAddr> {
207 lazy_static! {
208 static ref RE: Regex = Regex::new(r#"for="([^"]+)""#).unwrap();
209 }
210 let forwarded = headers.get(header::FORWARDED)?.to_str().ok()?;
211 let capture = RE.captures(&forwarded)?;
212 let rhost = capture.get(1)?.as_str();
213
214 rhost.parse().ok()
215 }
216
217 fn get_user_agent(headers: &HeaderMap) -> Option<String> {
218 let agent = headers.get(header::USER_AGENT)?.to_str();
219 agent
220 .map(|s| {
221 let mut s = s.to_owned();
222 s.truncate(128);
223 s
224 })
225 .ok()
226 }
227
228 impl Service<Request<Body>> for ApiService {
229 type Response = Response<Body>;
230 type Error = Error;
231 #[allow(clippy::type_complexity)]
232 type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
233
234 fn poll_ready(&mut self, _cx: &mut Context) -> Poll<Result<(), Self::Error>> {
235 Poll::Ready(Ok(()))
236 }
237
238 fn call(&mut self, req: Request<Body>) -> Self::Future {
239 let path = req.uri().path_and_query().unwrap().as_str().to_owned();
240 let method = req.method().clone();
241 let user_agent = get_user_agent(req.headers());
242
243 let config = Arc::clone(&self.api_config);
244 let peer = match get_proxied_peer(req.headers()) {
245 Some(proxied_peer) => proxied_peer,
246 None => self.peer,
247 };
248 async move {
249 let response = match handle_request(Arc::clone(&config), req, &peer).await {
250 Ok(response) => response,
251 Err(err) => {
252 let (err, code) = match err.downcast_ref::<HttpError>() {
253 Some(apierr) => (apierr.message.clone(), apierr.code),
254 _ => (err.to_string(), StatusCode::BAD_REQUEST),
255 };
256 Response::builder()
257 .status(code)
258 .extension(ErrorMessageExtension(err.to_string()))
259 .body(err.into())?
260 }
261 };
262 let logger = config.get_access_log();
263 log_response(logger, &peer, method, &path, &response, user_agent);
264 Ok(response)
265 }
266 .boxed()
267 }
268 }
269
270 fn parse_query_parameters<S: 'static + BuildHasher + Send>(
271 param_schema: ParameterSchema,
272 form: &str, // x-www-form-urlencoded body data
273 parts: &Parts,
274 uri_param: &HashMap<String, String, S>,
275 ) -> Result<Value, Error> {
276 let mut param_list: Vec<(String, String)> = vec![];
277
278 if !form.is_empty() {
279 for (k, v) in form_urlencoded::parse(form.as_bytes()).into_owned() {
280 param_list.push((k, v));
281 }
282 }
283
284 if let Some(query_str) = parts.uri.query() {
285 for (k, v) in form_urlencoded::parse(query_str.as_bytes()).into_owned() {
286 if k == "_dc" {
287 continue;
288 } // skip extjs "disable cache" parameter
289 param_list.push((k, v));
290 }
291 }
292
293 for (k, v) in uri_param {
294 param_list.push((k.clone(), v.clone()));
295 }
296
297 let params = parse_parameter_strings(&param_list, param_schema, true)?;
298
299 Ok(params)
300 }
301
302 async fn get_request_parameters<S: 'static + BuildHasher + Send>(
303 param_schema: ParameterSchema,
304 parts: Parts,
305 req_body: Body,
306 uri_param: HashMap<String, String, S>,
307 ) -> Result<Value, Error> {
308 let mut is_json = false;
309
310 if let Some(value) = parts.headers.get(header::CONTENT_TYPE) {
311 match value.to_str().map(|v| v.split(';').next()) {
312 Ok(Some("application/x-www-form-urlencoded")) => {
313 is_json = false;
314 }
315 Ok(Some("application/json")) => {
316 is_json = true;
317 }
318 _ => bail!("unsupported content type {:?}", value.to_str()),
319 }
320 }
321
322 let body = TryStreamExt::map_err(req_body, |err| {
323 http_err!(BAD_REQUEST, "Problems reading request body: {}", err)
324 })
325 .try_fold(Vec::new(), |mut acc, chunk| async move {
326 // FIXME: max request body size?
327 if acc.len() + chunk.len() < 64 * 1024 {
328 acc.extend_from_slice(&*chunk);
329 Ok(acc)
330 } else {
331 Err(http_err!(BAD_REQUEST, "Request body too large"))
332 }
333 })
334 .await?;
335
336 let utf8_data =
337 std::str::from_utf8(&body).map_err(|err| format_err!("Request body not uft8: {}", err))?;
338
339 if is_json {
340 let mut params: Value = serde_json::from_str(utf8_data)?;
341 for (k, v) in uri_param {
342 if let Some((_optional, prop_schema)) = param_schema.lookup(&k) {
343 params[&k] = parse_simple_value(&v, prop_schema)?;
344 }
345 }
346 verify_json_object(&params, &param_schema)?;
347 return Ok(params);
348 } else {
349 parse_query_parameters(param_schema, utf8_data, &parts, &uri_param)
350 }
351 }
352
353 struct NoLogExtension();
354
355 async fn proxy_protected_request(
356 info: &'static ApiMethod,
357 mut parts: Parts,
358 req_body: Body,
359 peer: &std::net::SocketAddr,
360 ) -> Result<Response<Body>, Error> {
361 let mut uri_parts = parts.uri.clone().into_parts();
362
363 uri_parts.scheme = Some(http::uri::Scheme::HTTP);
364 uri_parts.authority = Some(http::uri::Authority::from_static("127.0.0.1:82"));
365 let new_uri = http::Uri::from_parts(uri_parts).unwrap();
366
367 parts.uri = new_uri;
368
369 let mut request = Request::from_parts(parts, req_body);
370 request.headers_mut().insert(
371 header::FORWARDED,
372 format!("for=\"{}\";", peer).parse().unwrap(),
373 );
374
375 let reload_timezone = info.reload_timezone;
376
377 let resp = hyper::client::Client::new()
378 .request(request)
379 .map_err(Error::from)
380 .map_ok(|mut resp| {
381 resp.extensions_mut().insert(NoLogExtension());
382 resp
383 })
384 .await?;
385
386 if reload_timezone {
387 unsafe {
388 tzset();
389 }
390 }
391
392 Ok(resp)
393 }
394
395 pub(crate) async fn handle_api_request<Env: RpcEnvironment, S: 'static + BuildHasher + Send>(
396 mut rpcenv: Env,
397 info: &'static ApiMethod,
398 formatter: &'static dyn OutputFormatter,
399 parts: Parts,
400 req_body: Body,
401 uri_param: HashMap<String, String, S>,
402 ) -> Result<Response<Body>, Error> {
403 let delay_unauth_time = std::time::Instant::now() + std::time::Duration::from_millis(3000);
404 let compression = extract_compression_method(&parts.headers);
405
406 let result = match info.handler {
407 ApiHandler::AsyncHttp(handler) => {
408 let params = parse_query_parameters(info.parameters, "", &parts, &uri_param)?;
409 (handler)(parts, req_body, params, info, Box::new(rpcenv)).await
410 }
411 ApiHandler::Sync(handler) => {
412 let params =
413 get_request_parameters(info.parameters, parts, req_body, uri_param).await?;
414 (handler)(params, info, &mut rpcenv).map(|data| formatter.format_data(data, &rpcenv))
415 }
416 ApiHandler::Async(handler) => {
417 let params =
418 get_request_parameters(info.parameters, parts, req_body, uri_param).await?;
419 (handler)(params, info, &mut rpcenv)
420 .await
421 .map(|data| formatter.format_data(data, &rpcenv))
422 }
423 };
424
425 let mut resp = match result {
426 Ok(resp) => resp,
427 Err(err) => {
428 if let Some(httperr) = err.downcast_ref::<HttpError>() {
429 if httperr.code == StatusCode::UNAUTHORIZED {
430 tokio::time::sleep_until(Instant::from_std(delay_unauth_time)).await;
431 }
432 }
433 formatter.format_error(err)
434 }
435 };
436
437 let resp = match compression {
438 Some(CompressionMethod::Deflate) => {
439 resp.headers_mut().insert(
440 header::CONTENT_ENCODING,
441 CompressionMethod::Deflate.content_encoding(),
442 );
443 resp.map(|body| {
444 Body::wrap_stream(DeflateEncoder::with_quality(
445 TryStreamExt::map_err(body, |err| {
446 proxmox::io_format_err!("error during compression: {}", err)
447 }),
448 Level::Default,
449 ))
450 })
451 }
452 None => resp,
453 };
454
455 if info.reload_timezone {
456 unsafe {
457 tzset();
458 }
459 }
460
461 Ok(resp)
462 }
463
464
465 fn extension_to_content_type(filename: &Path) -> (&'static str, bool) {
466 if let Some(ext) = filename.extension().and_then(|osstr| osstr.to_str()) {
467 return match ext {
468 "css" => ("text/css", false),
469 "html" => ("text/html", false),
470 "js" => ("application/javascript", false),
471 "json" => ("application/json", false),
472 "map" => ("application/json", false),
473 "png" => ("image/png", true),
474 "ico" => ("image/x-icon", true),
475 "gif" => ("image/gif", true),
476 "svg" => ("image/svg+xml", false),
477 "jar" => ("application/java-archive", true),
478 "woff" => ("application/font-woff", true),
479 "woff2" => ("application/font-woff2", true),
480 "ttf" => ("application/font-snft", true),
481 "pdf" => ("application/pdf", true),
482 "epub" => ("application/epub+zip", true),
483 "mp3" => ("audio/mpeg", true),
484 "oga" => ("audio/ogg", true),
485 "tgz" => ("application/x-compressed-tar", true),
486 _ => ("application/octet-stream", false),
487 };
488 }
489
490 ("application/octet-stream", false)
491 }
492
493 async fn simple_static_file_download(
494 filename: PathBuf,
495 content_type: &'static str,
496 compression: Option<CompressionMethod>,
497 ) -> Result<Response<Body>, Error> {
498 use tokio::io::AsyncReadExt;
499
500 let mut file = File::open(filename)
501 .await
502 .map_err(|err| http_err!(BAD_REQUEST, "File open failed: {}", err))?;
503
504 let mut data: Vec<u8> = Vec::new();
505
506 let mut response = match compression {
507 Some(CompressionMethod::Deflate) => {
508 let mut enc = DeflateEncoder::with_quality(data, Level::Default);
509 enc.compress_vec(&mut file, CHUNK_SIZE_LIMIT as usize)
510 .await?;
511 let mut response = Response::new(enc.into_inner().into());
512 response.headers_mut().insert(
513 header::CONTENT_ENCODING,
514 CompressionMethod::Deflate.content_encoding(),
515 );
516 response
517 }
518 None => {
519 file.read_to_end(&mut data)
520 .await
521 .map_err(|err| http_err!(BAD_REQUEST, "File read failed: {}", err))?;
522 Response::new(data.into())
523 }
524 };
525
526 response.headers_mut().insert(
527 header::CONTENT_TYPE,
528 header::HeaderValue::from_static(content_type),
529 );
530
531 Ok(response)
532 }
533
534 async fn chuncked_static_file_download(
535 filename: PathBuf,
536 content_type: &'static str,
537 compression: Option<CompressionMethod>,
538 ) -> Result<Response<Body>, Error> {
539 let mut resp = Response::builder()
540 .status(StatusCode::OK)
541 .header(header::CONTENT_TYPE, content_type);
542
543 let file = File::open(filename)
544 .await
545 .map_err(|err| http_err!(BAD_REQUEST, "File open failed: {}", err))?;
546
547 let body = match compression {
548 Some(CompressionMethod::Deflate) => {
549 resp = resp.header(
550 header::CONTENT_ENCODING,
551 CompressionMethod::Deflate.content_encoding(),
552 );
553 Body::wrap_stream(DeflateEncoder::with_quality(
554 AsyncReaderStream::new(file),
555 Level::Default,
556 ))
557 }
558 None => Body::wrap_stream(AsyncReaderStream::new(file)),
559 };
560
561 Ok(resp.body(body).unwrap())
562 }
563
564 async fn handle_static_file_download(
565 filename: PathBuf,
566 compression: Option<CompressionMethod>,
567 ) -> Result<Response<Body>, Error> {
568 let metadata = tokio::fs::metadata(filename.clone())
569 .map_err(|err| http_err!(BAD_REQUEST, "File access problems: {}", err))
570 .await?;
571
572 let (content_type, nocomp) = extension_to_content_type(&filename);
573 let compression = if nocomp { None } else { compression };
574
575 if metadata.len() < CHUNK_SIZE_LIMIT {
576 simple_static_file_download(filename, content_type, compression).await
577 } else {
578 chuncked_static_file_download(filename, content_type, compression).await
579 }
580 }
581
582 fn extract_lang_header(headers: &http::HeaderMap) -> Option<String> {
583 if let Some(Ok(cookie)) = headers.get("COOKIE").map(|v| v.to_str()) {
584 return extract_cookie(cookie, "PBSLangCookie");
585 }
586 None
587 }
588
589 // FIXME: support handling multiple compression methods
590 fn extract_compression_method(headers: &http::HeaderMap) -> Option<CompressionMethod> {
591 if let Some(Ok(encodings)) = headers.get(header::ACCEPT_ENCODING).map(|v| v.to_str()) {
592 for encoding in encodings.split(&[',', ' '][..]) {
593 if let Ok(method) = encoding.parse() {
594 return Some(method);
595 }
596 }
597 }
598 None
599 }
600
601 async fn handle_request(
602 api: Arc<ApiConfig>,
603 req: Request<Body>,
604 peer: &std::net::SocketAddr,
605 ) -> Result<Response<Body>, Error> {
606 let (parts, body) = req.into_parts();
607 let method = parts.method.clone();
608 let (path, components) = normalize_uri_path(parts.uri.path())?;
609
610 let comp_len = components.len();
611
612 let query = parts.uri.query().unwrap_or_default();
613 if path.len() + query.len() > MAX_URI_QUERY_LENGTH {
614 return Ok(Response::builder()
615 .status(StatusCode::URI_TOO_LONG)
616 .body("".into())
617 .unwrap());
618 }
619
620 let env_type = api.env_type();
621 let mut rpcenv = RestEnvironment::new(env_type, Arc::clone(&api));
622
623 rpcenv.set_client_ip(Some(*peer));
624
625 let auth = &api.api_auth;
626
627 let delay_unauth_time = std::time::Instant::now() + std::time::Duration::from_millis(3000);
628 let access_forbidden_time = std::time::Instant::now() + std::time::Duration::from_millis(500);
629
630 if comp_len >= 1 && components[0] == "api2" {
631 if comp_len >= 2 {
632 let format = components[1];
633
634 let formatter: &dyn OutputFormatter = match format {
635 "json" => JSON_FORMATTER,
636 "extjs" => EXTJS_FORMATTER,
637 _ => bail!("Unsupported output format '{}'.", format),
638 };
639
640 let mut uri_param = HashMap::new();
641 let api_method = api.find_method(&components[2..], method.clone(), &mut uri_param);
642
643 let mut auth_required = true;
644 if let Some(api_method) = api_method {
645 if let Permission::World = *api_method.access.permission {
646 auth_required = false; // no auth for endpoints with World permission
647 }
648 }
649
650 let mut user_info: Box<dyn UserInformation + Send + Sync> = Box::new(EmptyUserInformation {});
651
652 if auth_required {
653 match auth.check_auth(&parts.headers, &method) {
654 Ok((authid, info)) => {
655 rpcenv.set_auth_id(Some(authid));
656 user_info = info;
657 }
658 Err(auth_err) => {
659 let err = match auth_err {
660 AuthError::Generic(err) => err,
661 AuthError::NoData => {
662 format_err!("no authentication credentials provided.")
663 }
664 };
665 // fixme: log Username??
666 rpcenv.log_failed_auth(None, &err.to_string());
667
668 // always delay unauthorized calls by 3 seconds (from start of request)
669 let err = http_err!(UNAUTHORIZED, "authentication failed - {}", err);
670 tokio::time::sleep_until(Instant::from_std(delay_unauth_time)).await;
671 return Ok(formatter.format_error(err));
672 }
673 }
674 }
675
676 match api_method {
677 None => {
678 let err = http_err!(NOT_FOUND, "Path '{}' not found.", path);
679 return Ok(formatter.format_error(err));
680 }
681 Some(api_method) => {
682 let auth_id = rpcenv.get_auth_id();
683 let user_info = user_info;
684
685 if !check_api_permission(
686 api_method.access.permission,
687 auth_id.as_deref(),
688 &uri_param,
689 user_info.as_ref(),
690 ) {
691 let err = http_err!(FORBIDDEN, "permission check failed");
692 tokio::time::sleep_until(Instant::from_std(access_forbidden_time)).await;
693 return Ok(formatter.format_error(err));
694 }
695
696 let result = if api_method.protected && env_type == RpcEnvironmentType::PUBLIC {
697 proxy_protected_request(api_method, parts, body, peer).await
698 } else {
699 handle_api_request(rpcenv, api_method, formatter, parts, body, uri_param)
700 .await
701 };
702
703 let mut response = match result {
704 Ok(resp) => resp,
705 Err(err) => formatter.format_error(err),
706 };
707
708 if let Some(auth_id) = auth_id {
709 response.extensions_mut().insert(AuthStringExtension(auth_id));
710 }
711
712 return Ok(response);
713 }
714 }
715 }
716 } else {
717 // not Auth required for accessing files!
718
719 if method != hyper::Method::GET {
720 bail!("Unsupported HTTP method {}", method);
721 }
722
723 if comp_len == 0 {
724 let language = extract_lang_header(&parts.headers);
725 match auth.check_auth(&parts.headers, &method) {
726 Ok((auth_id, _user_info)) => {
727 return Ok(api.get_index(Some(auth_id), language, parts));
728 }
729 Err(AuthError::Generic(_)) => {
730 tokio::time::sleep_until(Instant::from_std(delay_unauth_time)).await;
731 }
732 Err(AuthError::NoData) => {}
733 }
734 return Ok(api.get_index(None, language, parts));
735 } else {
736 let filename = api.find_alias(&components);
737 let compression = extract_compression_method(&parts.headers);
738 return handle_static_file_download(filename, compression).await;
739 }
740 }
741
742 Err(http_err!(NOT_FOUND, "Path '{}' not found.", path))
743 }