]> git.proxmox.com Git - proxmox-backup.git/blame - src/server/rest.rs
ui: automatically add 'localhost' as nodename for all panels
[proxmox-backup.git] / src / server / rest.rs
CommitLineData
91e45873 1use std::collections::HashMap;
db0cb9ce 2use std::future::Future;
62ee2eb4 3use std::hash::BuildHasher;
826bb982 4use std::path::{Path, PathBuf};
91e45873 5use std::pin::Pin;
9bc17e8d 6use std::sync::Arc;
91e45873 7use std::task::{Context, Poll};
9bc17e8d 8
f7d4e4b5 9use anyhow::{bail, format_err, Error};
ad51d02a 10use futures::future::{self, FutureExt, TryFutureExt};
91e45873
WB
11use futures::stream::TryStreamExt;
12use hyper::header;
13use hyper::http::request::Parts;
91e45873 14use hyper::{Body, Request, Response, StatusCode};
f4c514c1 15use serde_json::{json, Value};
9bc17e8d 16use tokio::fs::File;
db0cb9ce 17use tokio::time::Instant;
91e45873 18use url::form_urlencoded;
f9e3b110 19use handlebars::Handlebars;
9bc17e8d 20
9ea4bce4 21use proxmox::http_err;
ad51d02a 22use proxmox::api::{ApiHandler, ApiMethod, HttpError};
4b40148c 23use proxmox::api::{RpcEnvironment, RpcEnvironmentType, check_api_permission};
75a5a689 24use proxmox::api::schema::{ObjectSchema, parse_simple_value, verify_json_object, parse_parameter_strings};
a2479cfa 25
91e45873
WB
26use super::environment::RestEnvironment;
27use super::formatter::*;
e57e1cd8
DM
28use super::ApiConfig;
29
91e45873
WB
30use crate::auth_helpers::*;
31use crate::tools;
4b40148c 32use crate::config::cached_user_info::CachedUserInfo;
9bc17e8d 33
4b2cdeb9
DM
34extern "C" { fn tzset(); }
35
f0b10921
DM
36pub struct RestServer {
37 pub api_config: Arc<ApiConfig>,
38}
39
40impl RestServer {
41
42 pub fn new(api_config: ApiConfig) -> Self {
43 Self { api_config: Arc::new(api_config) }
44 }
45}
46
91e45873
WB
47impl tower_service::Service<&tokio_openssl::SslStream<tokio::net::TcpStream>> for RestServer {
48 type Response = ApiService;
7fb4f564 49 type Error = Error;
91e45873
WB
50 type Future = Pin<Box<dyn Future<Output = Result<ApiService, Error>> + Send>>;
51
52 fn poll_ready(&mut self, _cx: &mut Context) -> Poll<Result<(), Self::Error>> {
53 Poll::Ready(Ok(()))
54 }
55
56 fn call(&mut self, ctx: &tokio_openssl::SslStream<tokio::net::TcpStream>) -> Self::Future {
57 match ctx.get_ref().peer_addr() {
80af0467 58 Err(err) => {
91e45873 59 future::err(format_err!("unable to get peer address - {}", err)).boxed()
80af0467
DM
60 }
61 Ok(peer) => {
91e45873 62 future::ok(ApiService { peer, api_config: self.api_config.clone() }).boxed()
80af0467
DM
63 }
64 }
f0b10921
DM
65 }
66}
67
91e45873
WB
68impl tower_service::Service<&tokio::net::TcpStream> for RestServer {
69 type Response = ApiService;
7fb4f564 70 type Error = Error;
91e45873
WB
71 type Future = Pin<Box<dyn Future<Output = Result<ApiService, Error>> + Send>>;
72
73 fn poll_ready(&mut self, _cx: &mut Context) -> Poll<Result<(), Self::Error>> {
74 Poll::Ready(Ok(()))
75 }
76
77 fn call(&mut self, ctx: &tokio::net::TcpStream) -> Self::Future {
80af0467
DM
78 match ctx.peer_addr() {
79 Err(err) => {
91e45873 80 future::err(format_err!("unable to get peer address - {}", err)).boxed()
80af0467
DM
81 }
82 Ok(peer) => {
91e45873 83 future::ok(ApiService { peer, api_config: self.api_config.clone() }).boxed()
80af0467
DM
84 }
85 }
7fb4f564
DM
86 }
87}
88
f0b10921 89pub struct ApiService {
7fb4f564 90 pub peer: std::net::SocketAddr,
f0b10921
DM
91 pub api_config: Arc<ApiConfig>,
92}
93
7fb4f564
DM
94fn log_response(
95 peer: &std::net::SocketAddr,
96 method: hyper::Method,
97 path: &str,
98 resp: &Response<Body>,
99) {
7e03988c 100
d4736445 101 if resp.extensions().get::<NoLogExtension>().is_some() { return; };
7e03988c 102
d4736445 103 let status = resp.status();
7e03988c 104
1133fe9a 105 if !(status.is_success() || status.is_informational()) {
d4736445 106 let reason = status.canonical_reason().unwrap_or("unknown reason");
44c00c0d 107
d4736445
DM
108 let mut message = "request failed";
109 if let Some(data) = resp.extensions().get::<ErrorMessageExtension>() {
110 message = &data.0;
78a1fa67 111 }
d4736445 112
7fb4f564 113 log::error!("{} {}: {} {}: [client {}] {}", method.as_str(), path, status.as_str(), reason, peer, message);
78a1fa67
DM
114 }
115}
f0b10921 116
91e45873
WB
117impl tower_service::Service<Request<Body>> for ApiService {
118 type Response = Response<Body>;
7fb4f564 119 type Error = Error;
91e45873
WB
120 type Future = Pin<Box<dyn Future<Output = Result<Response<Body>, Self::Error>> + Send>>;
121
122 fn poll_ready(&mut self, _cx: &mut Context) -> Poll<Result<(), Self::Error>> {
123 Poll::Ready(Ok(()))
124 }
f0b10921 125
91e45873 126 fn call(&mut self, req: Request<Body>) -> Self::Future {
78a1fa67 127 let path = req.uri().path().to_owned();
d4736445
DM
128 let method = req.method().clone();
129
62ee2eb4 130 let peer = self.peer;
ad51d02a 131 handle_request(self.api_config.clone(), req)
91e45873 132 .map(move |result| match result {
78a1fa67 133 Ok(res) => {
7fb4f564
DM
134 log_response(&peer, method, &path, &res);
135 Ok::<_, Self::Error>(res)
78a1fa67 136 }
f0b10921 137 Err(err) => {
0dffe3f9 138 if let Some(apierr) = err.downcast_ref::<HttpError>() {
f0b10921
DM
139 let mut resp = Response::new(Body::from(apierr.message.clone()));
140 *resp.status_mut() = apierr.code;
7fb4f564 141 log_response(&peer, method, &path, &resp);
f0b10921
DM
142 Ok(resp)
143 } else {
144 let mut resp = Response::new(Body::from(err.to_string()));
145 *resp.status_mut() = StatusCode::BAD_REQUEST;
7fb4f564 146 log_response(&peer, method, &path, &resp);
f0b10921
DM
147 Ok(resp)
148 }
149 }
91e45873
WB
150 })
151 .boxed()
f0b10921
DM
152 }
153}
154
70fbac84
DM
155fn parse_query_parameters<S: 'static + BuildHasher + Send>(
156 param_schema: &ObjectSchema,
157 form: &str, // x-www-form-urlencoded body data
158 parts: &Parts,
159 uri_param: &HashMap<String, String, S>,
160) -> Result<Value, Error> {
161
162 let mut param_list: Vec<(String, String)> = vec![];
163
164 if !form.is_empty() {
165 for (k, v) in form_urlencoded::parse(form.as_bytes()).into_owned() {
166 param_list.push((k, v));
167 }
168 }
169
170 if let Some(query_str) = parts.uri.query() {
171 for (k, v) in form_urlencoded::parse(query_str.as_bytes()).into_owned() {
172 if k == "_dc" { continue; } // skip extjs "disable cache" parameter
173 param_list.push((k, v));
174 }
175 }
176
177 for (k, v) in uri_param {
178 param_list.push((k.clone(), v.clone()));
179 }
180
181 let params = parse_parameter_strings(&param_list, param_schema, true)?;
182
183 Ok(params)
184}
185
2bbd835b 186async fn get_request_parameters<S: 'static + BuildHasher + Send>(
75a5a689 187 param_schema: &ObjectSchema,
9bc17e8d
DM
188 parts: Parts,
189 req_body: Body,
62ee2eb4 190 uri_param: HashMap<String, String, S>,
ad51d02a
DM
191) -> Result<Value, Error> {
192
0ffbccce
DM
193 let mut is_json = false;
194
195 if let Some(value) = parts.headers.get(header::CONTENT_TYPE) {
8346f0d5
DM
196 match value.to_str().map(|v| v.split(';').next()) {
197 Ok(Some("application/x-www-form-urlencoded")) => {
198 is_json = false;
199 }
200 Ok(Some("application/json")) => {
201 is_json = true;
202 }
ad51d02a 203 _ => bail!("unsupported content type {:?}", value.to_str()),
0ffbccce
DM
204 }
205 }
206
ad51d02a 207 let body = req_body
4dcf43d2 208 .map_err(|err| http_err!(BAD_REQUEST, format!("Promlems reading request body: {}", err)))
91e45873 209 .try_fold(Vec::new(), |mut acc, chunk| async move {
9bc17e8d
DM
210 if acc.len() + chunk.len() < 64*1024 { //fimxe: max request body size?
211 acc.extend_from_slice(&*chunk);
212 Ok(acc)
91e45873 213 } else {
62ee2eb4 214 Err(http_err!(BAD_REQUEST, "Request body too large".to_string()))
9bc17e8d 215 }
ad51d02a 216 }).await?;
9bc17e8d 217
70fbac84 218 let utf8_data = std::str::from_utf8(&body)
ad51d02a 219 .map_err(|err| format_err!("Request body not uft8: {}", err))?;
0ffbccce 220
ad51d02a 221 if is_json {
70fbac84 222 let mut params: Value = serde_json::from_str(utf8_data)?;
ad51d02a 223 for (k, v) in uri_param {
75a5a689 224 if let Some((_optional, prop_schema)) = param_schema.lookup(&k) {
ad51d02a 225 params[&k] = parse_simple_value(&v, prop_schema)?;
9bc17e8d 226 }
ad51d02a 227 }
75a5a689 228 verify_json_object(&params, param_schema)?;
ad51d02a 229 return Ok(params);
70fbac84
DM
230 } else {
231 parse_query_parameters(param_schema, utf8_data, &parts, &uri_param)
ad51d02a 232 }
9bc17e8d
DM
233}
234
7171b3e0
DM
235struct NoLogExtension();
236
ad51d02a 237async fn proxy_protected_request(
4b2cdeb9 238 info: &'static ApiMethod,
a3da38dd 239 mut parts: Parts,
f1204833 240 req_body: Body,
ad51d02a 241) -> Result<Response<Body>, Error> {
f1204833 242
a3da38dd
DM
243 let mut uri_parts = parts.uri.clone().into_parts();
244
245 uri_parts.scheme = Some(http::uri::Scheme::HTTP);
246 uri_parts.authority = Some(http::uri::Authority::from_static("127.0.0.1:82"));
247 let new_uri = http::Uri::from_parts(uri_parts).unwrap();
248
249 parts.uri = new_uri;
250
251 let request = Request::from_parts(parts, req_body);
252
ad51d02a
DM
253 let reload_timezone = info.reload_timezone;
254
a3da38dd
DM
255 let resp = hyper::client::Client::new()
256 .request(request)
fc7f0352 257 .map_err(Error::from)
91e45873 258 .map_ok(|mut resp| {
1cb99c23 259 resp.extensions_mut().insert(NoLogExtension());
7e03988c 260 resp
ad51d02a
DM
261 })
262 .await?;
a3da38dd 263
ad51d02a 264 if reload_timezone { unsafe { tzset(); } }
1cb99c23 265
ad51d02a 266 Ok(resp)
f1204833
DM
267}
268
70fbac84 269pub async fn handle_api_request<Env: RpcEnvironment, S: 'static + BuildHasher + Send>(
f757b30e 270 mut rpcenv: Env,
279ecfdf 271 info: &'static ApiMethod,
1571873d 272 formatter: &'static OutputFormatter,
9bc17e8d
DM
273 parts: Parts,
274 req_body: Body,
62ee2eb4 275 uri_param: HashMap<String, String, S>,
ad51d02a
DM
276) -> Result<Response<Body>, Error> {
277
a154a8e8
DM
278 let delay_unauth_time = std::time::Instant::now() + std::time::Duration::from_millis(3000);
279
70fbac84 280 let result = match info.handler {
329d40b5 281 ApiHandler::AsyncHttp(handler) => {
70fbac84
DM
282 let params = parse_query_parameters(info.parameters, "", &parts, &uri_param)?;
283 (handler)(parts, req_body, params, info, Box::new(rpcenv)).await
284 }
285 ApiHandler::Sync(handler) => {
286 let params = get_request_parameters(info.parameters, parts, req_body, uri_param).await?;
287 (handler)(params, info, &mut rpcenv)
288 .map(|data| (formatter.format_data)(data, &rpcenv))
289 }
bb084b9c
DM
290 ApiHandler::Async(handler) => {
291 let params = get_request_parameters(info.parameters, parts, req_body, uri_param).await?;
292 (handler)(params, info, &mut rpcenv)
293 .await
294 .map(|data| (formatter.format_data)(data, &rpcenv))
295 }
70fbac84 296 };
a154a8e8 297
70fbac84
DM
298 let resp = match result {
299 Ok(resp) => resp,
ad51d02a
DM
300 Err(err) => {
301 if let Some(httperr) = err.downcast_ref::<HttpError>() {
302 if httperr.code == StatusCode::UNAUTHORIZED {
db0cb9ce 303 tokio::time::delay_until(Instant::from_std(delay_unauth_time)).await;
ad51d02a 304 }
4b2cdeb9 305 }
ad51d02a
DM
306 (formatter.format_error)(err)
307 }
308 };
4b2cdeb9 309
ad51d02a
DM
310 if info.reload_timezone { unsafe { tzset(); } }
311
ad51d02a 312 Ok(resp)
7e21da6e
DM
313}
314
f9e3b110 315fn get_index(username: Option<String>, token: Option<String>, template: &Handlebars, parts: Parts) -> Response<Body> {
f4c514c1 316
f69adc81 317 let nodename = proxmox::tools::nodename();
62ee2eb4 318 let username = username.unwrap_or_else(|| String::from(""));
7f168523 319
62ee2eb4 320 let token = token.unwrap_or_else(|| String::from(""));
f4c514c1 321
f9e3b110
DC
322 let mut debug = false;
323
324 if let Some(query_str) = parts.uri.query() {
325 for (k, v) in form_urlencoded::parse(query_str.as_bytes()).into_owned() {
326 if k == "debug" && v == "1" || v == "true" {
327 debug = true;
328 }
329 }
330 }
331
332 let data = json!({
f4c514c1
DM
333 "NodeName": nodename,
334 "UserName": username,
d15009c0 335 "CSRFPreventionToken": token,
f9e3b110 336 "debug": debug,
f4c514c1
DM
337 });
338
f9e3b110
DC
339 let mut ct = "text/html";
340
341 let index = match template.render("index", &data) {
342 Ok(index) => index,
343 Err(err) => {
344 ct = "text/plain";
345 format!("Error rendering template: {}", err.desc)
346 },
347 };
f4c514c1 348
7f168523 349 Response::builder()
d15009c0 350 .status(StatusCode::OK)
f9e3b110 351 .header(header::CONTENT_TYPE, ct)
d15009c0 352 .body(index.into())
7f168523 353 .unwrap()
f4c514c1
DM
354}
355
826bb982
DM
356fn extension_to_content_type(filename: &Path) -> (&'static str, bool) {
357
358 if let Some(ext) = filename.extension().and_then(|osstr| osstr.to_str()) {
359 return match ext {
360 "css" => ("text/css", false),
361 "html" => ("text/html", false),
362 "js" => ("application/javascript", false),
363 "json" => ("application/json", false),
364 "map" => ("application/json", false),
365 "png" => ("image/png", true),
366 "ico" => ("image/x-icon", true),
367 "gif" => ("image/gif", true),
368 "svg" => ("image/svg+xml", false),
369 "jar" => ("application/java-archive", true),
370 "woff" => ("application/font-woff", true),
371 "woff2" => ("application/font-woff2", true),
372 "ttf" => ("application/font-snft", true),
373 "pdf" => ("application/pdf", true),
374 "epub" => ("application/epub+zip", true),
375 "mp3" => ("audio/mpeg", true),
376 "oga" => ("audio/ogg", true),
377 "tgz" => ("application/x-compressed-tar", true),
378 _ => ("application/octet-stream", false),
379 };
380 }
381
382 ("application/octet-stream", false)
383}
384
91e45873 385async fn simple_static_file_download(filename: PathBuf) -> Result<Response<Body>, Error> {
9bc17e8d 386
826bb982
DM
387 let (content_type, _nocomp) = extension_to_content_type(&filename);
388
91e45873 389 use tokio::io::AsyncReadExt;
9bc17e8d 390
91e45873
WB
391 let mut file = File::open(filename)
392 .await
393 .map_err(|err| http_err!(BAD_REQUEST, format!("File open failed: {}", err)))?;
9bc17e8d 394
91e45873
WB
395 let mut data: Vec<u8> = Vec::new();
396 file.read_to_end(&mut data)
397 .await
398 .map_err(|err| http_err!(BAD_REQUEST, format!("File read failed: {}", err)))?;
399
400 let mut response = Response::new(data.into());
401 response.headers_mut().insert(
402 header::CONTENT_TYPE,
403 header::HeaderValue::from_static(content_type));
404 Ok(response)
405}
406
407async fn chuncked_static_file_download(filename: PathBuf) -> Result<Response<Body>, Error> {
826bb982
DM
408 let (content_type, _nocomp) = extension_to_content_type(&filename);
409
91e45873
WB
410 let file = File::open(filename)
411 .await
412 .map_err(|err| http_err!(BAD_REQUEST, format!("File open failed: {}", err)))?;
413
db0cb9ce
WB
414 let payload = tokio_util::codec::FramedRead::new(file, tokio_util::codec::BytesCodec::new())
415 .map_ok(|bytes| hyper::body::Bytes::from(bytes.freeze()));
91e45873
WB
416 let body = Body::wrap_stream(payload);
417
418 // fixme: set other headers ?
419 Ok(Response::builder()
420 .status(StatusCode::OK)
421 .header(header::CONTENT_TYPE, content_type)
422 .body(body)
423 .unwrap()
424 )
9bc17e8d
DM
425}
426
ad51d02a 427async fn handle_static_file_download(filename: PathBuf) -> Result<Response<Body>, Error> {
9bc17e8d 428
9c18e935 429 let metadata = tokio::fs::metadata(filename.clone())
4dcf43d2 430 .map_err(|err| http_err!(BAD_REQUEST, format!("File access problems: {}", err)))
9c18e935
TL
431 .await?;
432
433 if metadata.len() < 1024*32 {
434 simple_static_file_download(filename).await
435 } else {
436 chuncked_static_file_download(filename).await
437 }
9bc17e8d
DM
438}
439
5ddf8cb1
DM
440fn extract_auth_data(headers: &http::HeaderMap) -> (Option<String>, Option<String>) {
441
442 let mut ticket = None;
443 if let Some(raw_cookie) = headers.get("COOKIE") {
444 if let Ok(cookie) = raw_cookie.to_str() {
445 ticket = tools::extract_auth_cookie(cookie, "PBSAuthCookie");
446 }
447 }
448
449 let token = match headers.get("CSRFPreventionToken").map(|v| v.to_str()) {
450 Some(Ok(v)) => Some(v.to_owned()),
451 _ => None,
452 };
453
454 (ticket, token)
455}
456
4b40148c
DM
457fn check_auth(
458 method: &hyper::Method,
459 ticket: &Option<String>,
460 token: &Option<String>,
461 user_info: &CachedUserInfo,
462) -> Result<String, Error> {
5ddf8cb1 463
e5662b04 464 let ticket_lifetime = tools::ticket::TICKET_LIFETIME;
5ddf8cb1
DM
465
466 let username = match ticket {
467 Some(ticket) => match tools::ticket::verify_rsa_ticket(public_auth_key(), "PBS", &ticket, None, -300, ticket_lifetime) {
468 Ok((_age, Some(username))) => username.to_owned(),
469 Ok((_, None)) => bail!("ticket without username."),
470 Err(err) => return Err(err),
471 }
472 None => bail!("missing ticket"),
473 };
474
4b40148c
DM
475 if !user_info.is_active_user(&username) {
476 bail!("user account disabled or expired.");
477 }
478
5ddf8cb1
DM
479 if method != hyper::Method::GET {
480 if let Some(token) = token {
8225aa2f 481 println!("CSRF prevention token: {:?}", token);
5ddf8cb1
DM
482 verify_csrf_prevention_token(csrf_secret(), &username, &token, -300, ticket_lifetime)?;
483 } else {
8225aa2f 484 bail!("missing CSRF prevention token");
5ddf8cb1
DM
485 }
486 }
487
488 Ok(username)
489}
490
ad51d02a 491pub async fn handle_request(api: Arc<ApiConfig>, req: Request<Body>) -> Result<Response<Body>, Error> {
141de837
DM
492
493 let (parts, body) = req.into_parts();
494
495 let method = parts.method.clone();
ad51d02a 496 let (path, components) = tools::normalize_uri_path(parts.uri.path())?;
141de837 497
9bc17e8d
DM
498 let comp_len = components.len();
499
500 println!("REQUEST {} {}", method, path);
501 println!("COMPO {:?}", components);
502
f1204833
DM
503 let env_type = api.env_type();
504 let mut rpcenv = RestEnvironment::new(env_type);
e82dad97 505
4b40148c
DM
506 let user_info = CachedUserInfo::new()?;
507
b9903d63 508 let delay_unauth_time = std::time::Instant::now() + std::time::Duration::from_millis(3000);
9989d2c4 509 let access_forbidden_time = std::time::Instant::now() + std::time::Duration::from_millis(500);
b9903d63 510
576e3bf2 511 if comp_len >= 1 && components[0] == "api2" {
5ddf8cb1 512
9bc17e8d 513 if comp_len >= 2 {
ad51d02a 514
9bc17e8d 515 let format = components[1];
ad51d02a 516
1571873d
DM
517 let formatter = match format {
518 "json" => &JSON_FORMATTER,
519 "extjs" => &EXTJS_FORMATTER,
ad51d02a 520 _ => bail!("Unsupported output format '{}'.", format),
1571873d 521 };
9bc17e8d 522
e7ea17de
DM
523 let mut uri_param = HashMap::new();
524
708db4b3
DM
525 if comp_len == 4 && components[2] == "access" && (
526 (components[3] == "ticket" && method == hyper::Method::POST) ||
527 (components[3] == "domains" && method == hyper::Method::GET)
528 ) {
b9903d63
DM
529 // explicitly allow those calls without auth
530 } else {
5ddf8cb1 531 let (ticket, token) = extract_auth_data(&parts.headers);
4b40148c
DM
532 match check_auth(&method, &ticket, &token, &user_info) {
533 Ok(username) => rpcenv.set_user(Some(username)),
5ddf8cb1
DM
534 Err(err) => {
535 // always delay unauthorized calls by 3 seconds (from start of request)
4b40148c 536 let err = http_err!(UNAUTHORIZED, format!("authentication failed - {}", err));
db0cb9ce 537 tokio::time::delay_until(Instant::from_std(delay_unauth_time)).await;
ad51d02a 538 return Ok((formatter.format_error)(err));
5ddf8cb1 539 }
b9903d63
DM
540 }
541 }
d7d23785 542
7e21da6e 543 match api.find_method(&components[2..], method, &mut uri_param) {
255f378a 544 None => {
49d123ee 545 let err = http_err!(NOT_FOUND, "Path not found.".to_string());
ad51d02a 546 return Ok((formatter.format_error)(err));
49d123ee 547 }
255f378a 548 Some(api_method) => {
4b40148c 549 let user = rpcenv.get_user();
6e695960 550 if !check_api_permission(api_method.access.permission, user.as_deref(), &uri_param, user_info.as_ref()) {
4b40148c 551 let err = http_err!(FORBIDDEN, format!("permission check failed"));
9989d2c4 552 tokio::time::delay_until(Instant::from_std(access_forbidden_time)).await;
4b40148c
DM
553 return Ok((formatter.format_error)(err));
554 }
555
4299ca72
DM
556 let result = if api_method.protected && env_type == RpcEnvironmentType::PUBLIC {
557 proxy_protected_request(api_method, parts, body).await
f1204833 558 } else {
4299ca72
DM
559 handle_api_request(rpcenv, api_method, formatter, parts, body, uri_param).await
560 };
561
562 if let Err(err) = result {
563 return Ok((formatter.format_error)(err));
f1204833 564 }
4299ca72 565 return result;
7e21da6e 566 }
9bc17e8d 567 }
4299ca72 568
9bc17e8d 569 }
ad51d02a 570 } else {
7f168523 571 // not Auth required for accessing files!
9bc17e8d 572
7d4ef127 573 if method != hyper::Method::GET {
ad51d02a 574 bail!("Unsupported HTTP method {}", method);
7d4ef127
DM
575 }
576
f4c514c1 577 if comp_len == 0 {
7f168523
DM
578 let (ticket, token) = extract_auth_data(&parts.headers);
579 if ticket != None {
4b40148c 580 match check_auth(&method, &ticket, &token, &user_info) {
7d4ef127
DM
581 Ok(username) => {
582 let new_token = assemble_csrf_prevention_token(csrf_secret(), &username);
f9e3b110 583 return Ok(get_index(Some(username), Some(new_token), &api.templates, parts));
7d4ef127 584 }
91e45873 585 _ => {
db0cb9ce 586 tokio::time::delay_until(Instant::from_std(delay_unauth_time)).await;
f9e3b110 587 return Ok(get_index(None, None, &api.templates, parts));
91e45873 588 }
7f168523
DM
589 }
590 } else {
f9e3b110 591 return Ok(get_index(None, None, &api.templates, parts));
7f168523 592 }
f4c514c1
DM
593 } else {
594 let filename = api.find_alias(&components);
ad51d02a 595 return handle_static_file_download(filename).await;
f4c514c1 596 }
9bc17e8d
DM
597 }
598
ad51d02a 599 Err(http_err!(NOT_FOUND, "Path not found.".to_string()))
9bc17e8d 600}