]>
Commit | Line | Data |
---|---|---|
91e45873 | 1 | use std::collections::HashMap; |
db0cb9ce | 2 | use std::future::Future; |
62ee2eb4 | 3 | use std::hash::BuildHasher; |
826bb982 | 4 | use std::path::{Path, PathBuf}; |
91e45873 | 5 | use std::pin::Pin; |
8e7e2223 | 6 | use std::sync::{Arc, Mutex}; |
91e45873 | 7 | use std::task::{Context, Poll}; |
9bc17e8d | 8 | |
f7d4e4b5 | 9 | use anyhow::{bail, format_err, Error}; |
ad51d02a | 10 | use futures::future::{self, FutureExt, TryFutureExt}; |
91e45873 | 11 | use futures::stream::TryStreamExt; |
8e7e2223 | 12 | use hyper::body::HttpBody; |
d43c407a | 13 | use hyper::header::{self, HeaderMap}; |
91e45873 | 14 | use hyper::http::request::Parts; |
91e45873 | 15 | use hyper::{Body, Request, Response, StatusCode}; |
29633e2f | 16 | use lazy_static::lazy_static; |
d43c407a | 17 | use regex::Regex; |
f4c514c1 | 18 | use serde_json::{json, Value}; |
9bc17e8d | 19 | use tokio::fs::File; |
db0cb9ce | 20 | use tokio::time::Instant; |
91e45873 | 21 | use url::form_urlencoded; |
9bc17e8d | 22 | |
4e6dc587 | 23 | use proxmox::api::schema::{ |
d43c407a | 24 | parse_parameter_strings, parse_simple_value, verify_json_object, ObjectSchemaType, |
29a59b38 | 25 | ParameterSchema, |
4e6dc587 | 26 | }; |
d43c407a TL |
27 | use proxmox::api::{ |
28 | check_api_permission, ApiHandler, ApiMethod, HttpError, Permission, RpcEnvironment, | |
29 | RpcEnvironmentType, | |
30 | }; | |
31 | use proxmox::http_err; | |
a2479cfa | 32 | |
26858dba | 33 | use super::auth::AuthError; |
91e45873 WB |
34 | use super::environment::RestEnvironment; |
35 | use super::formatter::*; | |
e57e1cd8 DM |
36 | use super::ApiConfig; |
37 | ||
e6dc35ac | 38 | use crate::api2::types::{Authid, Userid}; |
d43c407a TL |
39 | use crate::auth_helpers::*; |
40 | use crate::config::cached_user_info::CachedUserInfo; | |
91e45873 | 41 | use crate::tools; |
2f29f1c7 | 42 | use crate::tools::compression::{CompressionMethod, DeflateEncoder, Level}; |
59477ad2 | 43 | use crate::tools::AsyncReaderStream; |
d43c407a | 44 | use crate::tools::FileLogger; |
9bc17e8d | 45 | |
d43c407a TL |
46 | extern "C" { |
47 | fn tzset(); | |
48 | } | |
4b2cdeb9 | 49 | |
f0b10921 DM |
50 | pub struct RestServer { |
51 | pub api_config: Arc<ApiConfig>, | |
52 | } | |
53 | ||
4703ba81 | 54 | const MAX_URI_QUERY_LENGTH: usize = 3072; |
59477ad2 | 55 | const CHUNK_SIZE_LIMIT: u64 = 32 * 1024; |
4703ba81 | 56 | |
f0b10921 | 57 | impl RestServer { |
f0b10921 | 58 | pub fn new(api_config: ApiConfig) -> Self { |
d43c407a TL |
59 | Self { |
60 | api_config: Arc::new(api_config), | |
61 | } | |
f0b10921 DM |
62 | } |
63 | } | |
64 | ||
d43c407a TL |
65 | impl tower_service::Service<&Pin<Box<tokio_openssl::SslStream<tokio::net::TcpStream>>>> |
66 | for RestServer | |
67 | { | |
91e45873 | 68 | type Response = ApiService; |
7fb4f564 | 69 | type Error = Error; |
91e45873 WB |
70 | type Future = Pin<Box<dyn Future<Output = Result<ApiService, Error>> + Send>>; |
71 | ||
72 | fn poll_ready(&mut self, _cx: &mut Context) -> Poll<Result<(), Self::Error>> { | |
73 | Poll::Ready(Ok(())) | |
74 | } | |
75 | ||
d43c407a TL |
76 | fn call( |
77 | &mut self, | |
78 | ctx: &Pin<Box<tokio_openssl::SslStream<tokio::net::TcpStream>>>, | |
79 | ) -> Self::Future { | |
91e45873 | 80 | match ctx.get_ref().peer_addr() { |
d43c407a TL |
81 | Err(err) => future::err(format_err!("unable to get peer address - {}", err)).boxed(), |
82 | Ok(peer) => future::ok(ApiService { | |
83 | peer, | |
84 | api_config: self.api_config.clone(), | |
85 | }) | |
86 | .boxed(), | |
80af0467 | 87 | } |
f0b10921 DM |
88 | } |
89 | } | |
90 | ||
91e45873 WB |
91 | impl tower_service::Service<&tokio::net::TcpStream> for RestServer { |
92 | type Response = ApiService; | |
7fb4f564 | 93 | type Error = Error; |
91e45873 WB |
94 | type Future = Pin<Box<dyn Future<Output = Result<ApiService, Error>> + Send>>; |
95 | ||
96 | fn poll_ready(&mut self, _cx: &mut Context) -> Poll<Result<(), Self::Error>> { | |
97 | Poll::Ready(Ok(())) | |
98 | } | |
99 | ||
100 | fn call(&mut self, ctx: &tokio::net::TcpStream) -> Self::Future { | |
80af0467 | 101 | match ctx.peer_addr() { |
d43c407a TL |
102 | Err(err) => future::err(format_err!("unable to get peer address - {}", err)).boxed(), |
103 | Ok(peer) => future::ok(ApiService { | |
104 | peer, | |
105 | api_config: self.api_config.clone(), | |
106 | }) | |
107 | .boxed(), | |
80af0467 | 108 | } |
7fb4f564 DM |
109 | } |
110 | } | |
111 | ||
b57c0dbe SR |
112 | impl tower_service::Service<&tokio::net::UnixStream> for RestServer { |
113 | type Response = ApiService; | |
114 | type Error = Error; | |
115 | type Future = Pin<Box<dyn Future<Output = Result<ApiService, Error>> + Send>>; | |
116 | ||
117 | fn poll_ready(&mut self, _cx: &mut Context) -> Poll<Result<(), Self::Error>> { | |
118 | Poll::Ready(Ok(())) | |
119 | } | |
120 | ||
121 | fn call(&mut self, _ctx: &tokio::net::UnixStream) -> Self::Future { | |
122 | // TODO: Find a way to actually represent the vsock peer in the ApiService struct - for now | |
123 | // it doesn't really matter, so just use a fake IP address | |
124 | let fake_peer = "0.0.0.0:807".parse().unwrap(); | |
125 | future::ok(ApiService { | |
126 | peer: fake_peer, | |
d43c407a TL |
127 | api_config: self.api_config.clone(), |
128 | }) | |
129 | .boxed() | |
b57c0dbe SR |
130 | } |
131 | } | |
132 | ||
f0b10921 | 133 | pub struct ApiService { |
7fb4f564 | 134 | pub peer: std::net::SocketAddr, |
f0b10921 DM |
135 | pub api_config: Arc<ApiConfig>, |
136 | } | |
137 | ||
7fb4f564 | 138 | fn log_response( |
fe4cc5b1 | 139 | logfile: Option<&Arc<Mutex<FileLogger>>>, |
7fb4f564 DM |
140 | peer: &std::net::SocketAddr, |
141 | method: hyper::Method, | |
400c568f | 142 | path_query: &str, |
7fb4f564 | 143 | resp: &Response<Body>, |
86f3c236 | 144 | user_agent: Option<String>, |
7fb4f564 | 145 | ) { |
d43c407a TL |
146 | if resp.extensions().get::<NoLogExtension>().is_some() { |
147 | return; | |
148 | }; | |
7e03988c | 149 | |
4703ba81 TL |
150 | // we also log URL-to-long requests, so avoid message bigger than PIPE_BUF (4k on Linux) |
151 | // to profit from atomicty guarantees for O_APPEND opened logfiles | |
400c568f | 152 | let path = &path_query[..MAX_URI_QUERY_LENGTH.min(path_query.len())]; |
4703ba81 | 153 | |
d4736445 | 154 | let status = resp.status(); |
1133fe9a | 155 | if !(status.is_success() || status.is_informational()) { |
d4736445 | 156 | let reason = status.canonical_reason().unwrap_or("unknown reason"); |
44c00c0d | 157 | |
6b5013ed TL |
158 | let message = match resp.extensions().get::<ErrorMessageExtension>() { |
159 | Some(data) => &data.0, | |
160 | None => "request failed", | |
161 | }; | |
d4736445 | 162 | |
d43c407a TL |
163 | log::error!( |
164 | "{} {}: {} {}: [client {}] {}", | |
165 | method.as_str(), | |
166 | path, | |
167 | status.as_str(), | |
168 | reason, | |
169 | peer, | |
170 | message | |
171 | ); | |
78a1fa67 | 172 | } |
8e7e2223 | 173 | if let Some(logfile) = logfile { |
e6dc35ac FG |
174 | let auth_id = match resp.extensions().get::<Authid>() { |
175 | Some(auth_id) => auth_id.to_string(), | |
176 | None => "-".to_string(), | |
8e7e2223 TL |
177 | }; |
178 | let now = proxmox::tools::time::epoch_i64(); | |
179 | // time format which apache/nginx use (by default), copied from pve-http-server | |
180 | let datetime = proxmox::tools::time::strftime_local("%d/%m/%Y:%H:%M:%S %z", now) | |
e062ebbc | 181 | .unwrap_or_else(|_| "-".to_string()); |
8e7e2223 | 182 | |
d43c407a TL |
183 | logfile.lock().unwrap().log(format!( |
184 | "{} - {} [{}] \"{} {}\" {} {} {}", | |
185 | peer.ip(), | |
186 | auth_id, | |
187 | datetime, | |
188 | method.as_str(), | |
189 | path, | |
190 | status.as_str(), | |
191 | resp.body().size_hint().lower(), | |
192 | user_agent.unwrap_or_else(|| "-".to_string()), | |
193 | )); | |
8e7e2223 | 194 | } |
78a1fa67 | 195 | } |
4fdf13f9 TL |
196 | pub fn auth_logger() -> Result<FileLogger, Error> { |
197 | let logger_options = tools::FileLogOptions { | |
198 | append: true, | |
199 | prefix_time: true, | |
200 | owned_by_backup: true, | |
201 | ..Default::default() | |
202 | }; | |
af06decd | 203 | FileLogger::new(pbs_buildcfg::API_AUTH_LOG_FN, logger_options) |
4fdf13f9 | 204 | } |
f0b10921 | 205 | |
29633e2f TL |
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 | ||
86f3c236 TL |
217 | fn get_user_agent(headers: &HeaderMap) -> Option<String> { |
218 | let agent = headers.get(header::USER_AGENT)?.to_str(); | |
d43c407a TL |
219 | agent |
220 | .map(|s| { | |
221 | let mut s = s.to_owned(); | |
222 | s.truncate(128); | |
223 | s | |
224 | }) | |
225 | .ok() | |
86f3c236 TL |
226 | } |
227 | ||
91e45873 WB |
228 | impl tower_service::Service<Request<Body>> for ApiService { |
229 | type Response = Response<Body>; | |
7fb4f564 | 230 | type Error = Error; |
12e874ce FG |
231 | #[allow(clippy::type_complexity)] |
232 | type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>; | |
91e45873 WB |
233 | |
234 | fn poll_ready(&mut self, _cx: &mut Context) -> Poll<Result<(), Self::Error>> { | |
235 | Poll::Ready(Ok(())) | |
236 | } | |
f0b10921 | 237 | |
91e45873 | 238 | fn call(&mut self, req: Request<Body>) -> Self::Future { |
400c568f | 239 | let path = req.uri().path_and_query().unwrap().as_str().to_owned(); |
d4736445 | 240 | let method = req.method().clone(); |
86f3c236 | 241 | let user_agent = get_user_agent(req.headers()); |
d4736445 | 242 | |
07995a3c | 243 | let config = Arc::clone(&self.api_config); |
29633e2f TL |
244 | let peer = match get_proxied_peer(req.headers()) { |
245 | Some(proxied_peer) => proxied_peer, | |
246 | None => self.peer, | |
247 | }; | |
07995a3c | 248 | async move { |
8e7e2223 | 249 | let response = match handle_request(Arc::clone(&config), req, &peer).await { |
b947b1e7 | 250 | Ok(response) => response, |
f0b10921 | 251 | Err(err) => { |
b947b1e7 TL |
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 | }; | |
f4d371d2 TL |
256 | Response::builder() |
257 | .status(code) | |
258 | .extension(ErrorMessageExtension(err.to_string())) | |
259 | .body(err.into())? | |
f0b10921 | 260 | } |
b947b1e7 | 261 | }; |
8e7e2223 | 262 | let logger = config.get_file_log(); |
86f3c236 | 263 | log_response(logger, &peer, method, &path, &response, user_agent); |
b947b1e7 | 264 | Ok(response) |
07995a3c TL |
265 | } |
266 | .boxed() | |
f0b10921 DM |
267 | } |
268 | } | |
269 | ||
70fbac84 | 270 | fn parse_query_parameters<S: 'static + BuildHasher + Send>( |
b2362a12 | 271 | param_schema: ParameterSchema, |
70fbac84 DM |
272 | form: &str, // x-www-form-urlencoded body data |
273 | parts: &Parts, | |
274 | uri_param: &HashMap<String, String, S>, | |
275 | ) -> Result<Value, Error> { | |
70fbac84 DM |
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() { | |
d43c407a TL |
286 | if k == "_dc" { |
287 | continue; | |
288 | } // skip extjs "disable cache" parameter | |
70fbac84 DM |
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(¶m_list, param_schema, true)?; | |
298 | ||
299 | Ok(params) | |
300 | } | |
301 | ||
2bbd835b | 302 | async fn get_request_parameters<S: 'static + BuildHasher + Send>( |
b2362a12 | 303 | param_schema: ParameterSchema, |
9bc17e8d DM |
304 | parts: Parts, |
305 | req_body: Body, | |
62ee2eb4 | 306 | uri_param: HashMap<String, String, S>, |
ad51d02a | 307 | ) -> Result<Value, Error> { |
0ffbccce DM |
308 | let mut is_json = false; |
309 | ||
310 | if let Some(value) = parts.headers.get(header::CONTENT_TYPE) { | |
8346f0d5 DM |
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 | } | |
ad51d02a | 318 | _ => bail!("unsupported content type {:?}", value.to_str()), |
0ffbccce DM |
319 | } |
320 | } | |
321 | ||
eeff085d TL |
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?; | |
9bc17e8d | 335 | |
d43c407a TL |
336 | let utf8_data = |
337 | std::str::from_utf8(&body).map_err(|err| format_err!("Request body not uft8: {}", err))?; | |
0ffbccce | 338 | |
ad51d02a | 339 | if is_json { |
70fbac84 | 340 | let mut params: Value = serde_json::from_str(utf8_data)?; |
ad51d02a | 341 | for (k, v) in uri_param { |
75a5a689 | 342 | if let Some((_optional, prop_schema)) = param_schema.lookup(&k) { |
ad51d02a | 343 | params[&k] = parse_simple_value(&v, prop_schema)?; |
9bc17e8d | 344 | } |
ad51d02a | 345 | } |
b2362a12 | 346 | verify_json_object(¶ms, ¶m_schema)?; |
ad51d02a | 347 | return Ok(params); |
70fbac84 DM |
348 | } else { |
349 | parse_query_parameters(param_schema, utf8_data, &parts, &uri_param) | |
ad51d02a | 350 | } |
9bc17e8d DM |
351 | } |
352 | ||
7171b3e0 DM |
353 | struct NoLogExtension(); |
354 | ||
ad51d02a | 355 | async fn proxy_protected_request( |
4b2cdeb9 | 356 | info: &'static ApiMethod, |
a3da38dd | 357 | mut parts: Parts, |
f1204833 | 358 | req_body: Body, |
29633e2f | 359 | peer: &std::net::SocketAddr, |
ad51d02a | 360 | ) -> Result<Response<Body>, Error> { |
a3da38dd DM |
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 | ||
29633e2f | 369 | let mut request = Request::from_parts(parts, req_body); |
d43c407a TL |
370 | request.headers_mut().insert( |
371 | header::FORWARDED, | |
372 | format!("for=\"{}\";", peer).parse().unwrap(), | |
373 | ); | |
a3da38dd | 374 | |
ad51d02a DM |
375 | let reload_timezone = info.reload_timezone; |
376 | ||
a3da38dd DM |
377 | let resp = hyper::client::Client::new() |
378 | .request(request) | |
fc7f0352 | 379 | .map_err(Error::from) |
91e45873 | 380 | .map_ok(|mut resp| { |
1cb99c23 | 381 | resp.extensions_mut().insert(NoLogExtension()); |
7e03988c | 382 | resp |
ad51d02a DM |
383 | }) |
384 | .await?; | |
a3da38dd | 385 | |
d43c407a TL |
386 | if reload_timezone { |
387 | unsafe { | |
388 | tzset(); | |
389 | } | |
390 | } | |
1cb99c23 | 391 | |
ad51d02a | 392 | Ok(resp) |
f1204833 DM |
393 | } |
394 | ||
70fbac84 | 395 | pub async fn handle_api_request<Env: RpcEnvironment, S: 'static + BuildHasher + Send>( |
f757b30e | 396 | mut rpcenv: Env, |
279ecfdf | 397 | info: &'static ApiMethod, |
1571873d | 398 | formatter: &'static OutputFormatter, |
9bc17e8d DM |
399 | parts: Parts, |
400 | req_body: Body, | |
62ee2eb4 | 401 | uri_param: HashMap<String, String, S>, |
ad51d02a | 402 | ) -> Result<Response<Body>, Error> { |
a154a8e8 | 403 | let delay_unauth_time = std::time::Instant::now() + std::time::Duration::from_millis(3000); |
2f29f1c7 | 404 | let compression = extract_compression_method(&parts.headers); |
a154a8e8 | 405 | |
70fbac84 | 406 | let result = match info.handler { |
329d40b5 | 407 | ApiHandler::AsyncHttp(handler) => { |
70fbac84 DM |
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) => { | |
d43c407a TL |
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)) | |
70fbac84 | 415 | } |
bb084b9c | 416 | ApiHandler::Async(handler) => { |
d43c407a TL |
417 | let params = |
418 | get_request_parameters(info.parameters, parts, req_body, uri_param).await?; | |
bb084b9c DM |
419 | (handler)(params, info, &mut rpcenv) |
420 | .await | |
421 | .map(|data| (formatter.format_data)(data, &rpcenv)) | |
422 | } | |
70fbac84 | 423 | }; |
a154a8e8 | 424 | |
2f29f1c7 | 425 | let mut resp = match result { |
70fbac84 | 426 | Ok(resp) => resp, |
ad51d02a DM |
427 | Err(err) => { |
428 | if let Some(httperr) = err.downcast_ref::<HttpError>() { | |
429 | if httperr.code == StatusCode::UNAUTHORIZED { | |
0a8d773a | 430 | tokio::time::sleep_until(Instant::from_std(delay_unauth_time)).await; |
ad51d02a | 431 | } |
4b2cdeb9 | 432 | } |
ad51d02a DM |
433 | (formatter.format_error)(err) |
434 | } | |
435 | }; | |
4b2cdeb9 | 436 | |
2f29f1c7 DC |
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( | |
f2f43e19 | 445 | TryStreamExt::map_err(body, |err| { |
2f29f1c7 DC |
446 | proxmox::io_format_err!("error during compression: {}", err) |
447 | }), | |
b84e8aae | 448 | Level::Default, |
2f29f1c7 DC |
449 | )) |
450 | }) | |
451 | } | |
452 | None => resp, | |
453 | }; | |
454 | ||
d43c407a TL |
455 | if info.reload_timezone { |
456 | unsafe { | |
457 | tzset(); | |
458 | } | |
459 | } | |
ad51d02a | 460 | |
ad51d02a | 461 | Ok(resp) |
7e21da6e DM |
462 | } |
463 | ||
abd4c4cb TL |
464 | fn get_index( |
465 | userid: Option<Userid>, | |
6c5bdef5 | 466 | csrf_token: Option<String>, |
abd4c4cb TL |
467 | language: Option<String>, |
468 | api: &Arc<ApiConfig>, | |
469 | parts: Parts, | |
d43c407a | 470 | ) -> Response<Body> { |
f69adc81 | 471 | let nodename = proxmox::tools::nodename(); |
6c5bdef5 | 472 | let user = userid.as_ref().map(|u| u.as_str()).unwrap_or(""); |
7f168523 | 473 | |
6c5bdef5 | 474 | let csrf_token = csrf_token.unwrap_or_else(|| String::from("")); |
f4c514c1 | 475 | |
f9e3b110 | 476 | let mut debug = false; |
01ca99da | 477 | let mut template_file = "index"; |
f9e3b110 DC |
478 | |
479 | if let Some(query_str) = parts.uri.query() { | |
480 | for (k, v) in form_urlencoded::parse(query_str.as_bytes()).into_owned() { | |
3f683799 | 481 | if k == "debug" && v != "0" && v != "false" { |
f9e3b110 | 482 | debug = true; |
01ca99da DC |
483 | } else if k == "console" { |
484 | template_file = "console"; | |
f9e3b110 DC |
485 | } |
486 | } | |
487 | } | |
488 | ||
abd4c4cb TL |
489 | let mut lang = String::from(""); |
490 | if let Some(language) = language { | |
491 | if Path::new(&format!("/usr/share/pbs-i18n/pbs-lang-{}.js", language)).exists() { | |
492 | lang = language; | |
493 | } | |
494 | } | |
495 | ||
f9e3b110 | 496 | let data = json!({ |
f4c514c1 | 497 | "NodeName": nodename, |
6c5bdef5 TL |
498 | "UserName": user, |
499 | "CSRFPreventionToken": csrf_token, | |
abd4c4cb | 500 | "language": lang, |
f9e3b110 | 501 | "debug": debug, |
f4c514c1 DM |
502 | }); |
503 | ||
adfcfb67 TL |
504 | let (ct, index) = match api.render_template(template_file, &data) { |
505 | Ok(index) => ("text/html", index), | |
d43c407a | 506 | Err(err) => ("text/plain", format!("Error rendering template: {}", err)), |
f9e3b110 | 507 | }; |
f4c514c1 | 508 | |
8e7e2223 | 509 | let mut resp = Response::builder() |
d15009c0 | 510 | .status(StatusCode::OK) |
f9e3b110 | 511 | .header(header::CONTENT_TYPE, ct) |
d15009c0 | 512 | .body(index.into()) |
8e7e2223 TL |
513 | .unwrap(); |
514 | ||
515 | if let Some(userid) = userid { | |
e6dc35ac | 516 | resp.extensions_mut().insert(Authid::from((userid, None))); |
8e7e2223 TL |
517 | } |
518 | ||
519 | resp | |
f4c514c1 DM |
520 | } |
521 | ||
826bb982 | 522 | fn extension_to_content_type(filename: &Path) -> (&'static str, bool) { |
826bb982 DM |
523 | if let Some(ext) = filename.extension().and_then(|osstr| osstr.to_str()) { |
524 | return match ext { | |
525 | "css" => ("text/css", false), | |
526 | "html" => ("text/html", false), | |
527 | "js" => ("application/javascript", false), | |
528 | "json" => ("application/json", false), | |
529 | "map" => ("application/json", false), | |
530 | "png" => ("image/png", true), | |
531 | "ico" => ("image/x-icon", true), | |
532 | "gif" => ("image/gif", true), | |
533 | "svg" => ("image/svg+xml", false), | |
534 | "jar" => ("application/java-archive", true), | |
535 | "woff" => ("application/font-woff", true), | |
536 | "woff2" => ("application/font-woff2", true), | |
537 | "ttf" => ("application/font-snft", true), | |
538 | "pdf" => ("application/pdf", true), | |
539 | "epub" => ("application/epub+zip", true), | |
540 | "mp3" => ("audio/mpeg", true), | |
541 | "oga" => ("audio/ogg", true), | |
542 | "tgz" => ("application/x-compressed-tar", true), | |
543 | _ => ("application/octet-stream", false), | |
544 | }; | |
545 | } | |
546 | ||
547 | ("application/octet-stream", false) | |
548 | } | |
549 | ||
59477ad2 DC |
550 | async fn simple_static_file_download( |
551 | filename: PathBuf, | |
552 | content_type: &'static str, | |
553 | compression: Option<CompressionMethod>, | |
554 | ) -> Result<Response<Body>, Error> { | |
91e45873 | 555 | use tokio::io::AsyncReadExt; |
9bc17e8d | 556 | |
91e45873 WB |
557 | let mut file = File::open(filename) |
558 | .await | |
8aa67ee7 | 559 | .map_err(|err| http_err!(BAD_REQUEST, "File open failed: {}", err))?; |
9bc17e8d | 560 | |
91e45873 | 561 | let mut data: Vec<u8> = Vec::new(); |
91e45873 | 562 | |
59477ad2 DC |
563 | let mut response = match compression { |
564 | Some(CompressionMethod::Deflate) => { | |
b84e8aae | 565 | let mut enc = DeflateEncoder::with_quality(data, Level::Default); |
2d485333 TL |
566 | enc.compress_vec(&mut file, CHUNK_SIZE_LIMIT as usize) |
567 | .await?; | |
59477ad2 DC |
568 | let mut response = Response::new(enc.into_inner().into()); |
569 | response.headers_mut().insert( | |
570 | header::CONTENT_ENCODING, | |
571 | CompressionMethod::Deflate.content_encoding(), | |
572 | ); | |
573 | response | |
574 | } | |
575 | None => { | |
576 | file.read_to_end(&mut data) | |
577 | .await | |
578 | .map_err(|err| http_err!(BAD_REQUEST, "File read failed: {}", err))?; | |
579 | Response::new(data.into()) | |
580 | } | |
581 | }; | |
582 | ||
91e45873 WB |
583 | response.headers_mut().insert( |
584 | header::CONTENT_TYPE, | |
d43c407a TL |
585 | header::HeaderValue::from_static(content_type), |
586 | ); | |
59477ad2 | 587 | |
91e45873 WB |
588 | Ok(response) |
589 | } | |
590 | ||
59477ad2 DC |
591 | async fn chuncked_static_file_download( |
592 | filename: PathBuf, | |
593 | content_type: &'static str, | |
594 | compression: Option<CompressionMethod>, | |
595 | ) -> Result<Response<Body>, Error> { | |
596 | let mut resp = Response::builder() | |
597 | .status(StatusCode::OK) | |
598 | .header(header::CONTENT_TYPE, content_type); | |
826bb982 | 599 | |
91e45873 WB |
600 | let file = File::open(filename) |
601 | .await | |
8aa67ee7 | 602 | .map_err(|err| http_err!(BAD_REQUEST, "File open failed: {}", err))?; |
91e45873 | 603 | |
59477ad2 DC |
604 | let body = match compression { |
605 | Some(CompressionMethod::Deflate) => { | |
606 | resp = resp.header( | |
607 | header::CONTENT_ENCODING, | |
608 | CompressionMethod::Deflate.content_encoding(), | |
609 | ); | |
610 | Body::wrap_stream(DeflateEncoder::with_quality( | |
611 | AsyncReaderStream::new(file), | |
b84e8aae | 612 | Level::Default, |
59477ad2 DC |
613 | )) |
614 | } | |
615 | None => Body::wrap_stream(AsyncReaderStream::new(file)), | |
616 | }; | |
91e45873 | 617 | |
59477ad2 | 618 | Ok(resp.body(body).unwrap()) |
9bc17e8d DM |
619 | } |
620 | ||
59477ad2 DC |
621 | async fn handle_static_file_download( |
622 | filename: PathBuf, | |
623 | compression: Option<CompressionMethod>, | |
624 | ) -> Result<Response<Body>, Error> { | |
9c18e935 | 625 | let metadata = tokio::fs::metadata(filename.clone()) |
8aa67ee7 | 626 | .map_err(|err| http_err!(BAD_REQUEST, "File access problems: {}", err)) |
9c18e935 TL |
627 | .await?; |
628 | ||
59477ad2 DC |
629 | let (content_type, nocomp) = extension_to_content_type(&filename); |
630 | let compression = if nocomp { None } else { compression }; | |
631 | ||
632 | if metadata.len() < CHUNK_SIZE_LIMIT { | |
633 | simple_static_file_download(filename, content_type, compression).await | |
9c18e935 | 634 | } else { |
59477ad2 | 635 | chuncked_static_file_download(filename, content_type, compression).await |
9c18e935 | 636 | } |
9bc17e8d DM |
637 | } |
638 | ||
c30816c1 | 639 | fn extract_lang_header(headers: &http::HeaderMap) -> Option<String> { |
c47609fe TL |
640 | if let Some(Ok(cookie)) = headers.get("COOKIE").map(|v| v.to_str()) { |
641 | return tools::extract_cookie(cookie, "PBSLangCookie"); | |
c30816c1 | 642 | } |
c30816c1 FG |
643 | None |
644 | } | |
645 | ||
4d84e869 DC |
646 | // FIXME: support handling multiple compression methods |
647 | fn extract_compression_method(headers: &http::HeaderMap) -> Option<CompressionMethod> { | |
c47609fe TL |
648 | if let Some(Ok(encodings)) = headers.get(header::ACCEPT_ENCODING).map(|v| v.to_str()) { |
649 | for encoding in encodings.split(&[',', ' '][..]) { | |
650 | if let Ok(method) = encoding.parse() { | |
651 | return Some(method); | |
4d84e869 DC |
652 | } |
653 | } | |
654 | } | |
4d84e869 DC |
655 | None |
656 | } | |
657 | ||
29633e2f TL |
658 | async fn handle_request( |
659 | api: Arc<ApiConfig>, | |
660 | req: Request<Body>, | |
661 | peer: &std::net::SocketAddr, | |
662 | ) -> Result<Response<Body>, Error> { | |
141de837 | 663 | let (parts, body) = req.into_parts(); |
141de837 | 664 | let method = parts.method.clone(); |
217c22c7 | 665 | let (path, components) = tools::normalize_uri_path(parts.uri.path())?; |
141de837 | 666 | |
9bc17e8d DM |
667 | let comp_len = components.len(); |
668 | ||
4703ba81 TL |
669 | let query = parts.uri.query().unwrap_or_default(); |
670 | if path.len() + query.len() > MAX_URI_QUERY_LENGTH { | |
671 | return Ok(Response::builder() | |
672 | .status(StatusCode::URI_TOO_LONG) | |
673 | .body("".into()) | |
674 | .unwrap()); | |
675 | } | |
676 | ||
f1204833 DM |
677 | let env_type = api.env_type(); |
678 | let mut rpcenv = RestEnvironment::new(env_type); | |
e82dad97 | 679 | |
29633e2f TL |
680 | rpcenv.set_client_ip(Some(*peer)); |
681 | ||
4b40148c | 682 | let user_info = CachedUserInfo::new()?; |
26858dba | 683 | let auth = &api.api_auth; |
4b40148c | 684 | |
b9903d63 | 685 | let delay_unauth_time = std::time::Instant::now() + std::time::Duration::from_millis(3000); |
9989d2c4 | 686 | let access_forbidden_time = std::time::Instant::now() + std::time::Duration::from_millis(500); |
b9903d63 | 687 | |
576e3bf2 | 688 | if comp_len >= 1 && components[0] == "api2" { |
9bc17e8d DM |
689 | if comp_len >= 2 { |
690 | let format = components[1]; | |
ad51d02a | 691 | |
1571873d DM |
692 | let formatter = match format { |
693 | "json" => &JSON_FORMATTER, | |
694 | "extjs" => &EXTJS_FORMATTER, | |
d43c407a | 695 | _ => bail!("Unsupported output format '{}'.", format), |
1571873d | 696 | }; |
9bc17e8d | 697 | |
e7ea17de | 698 | let mut uri_param = HashMap::new(); |
0ac61247 | 699 | let api_method = api.find_method(&components[2..], method.clone(), &mut uri_param); |
e7ea17de | 700 | |
0ac61247 TL |
701 | let mut auth_required = true; |
702 | if let Some(api_method) = api_method { | |
703 | if let Permission::World = *api_method.access.permission { | |
704 | auth_required = false; // no auth for endpoints with World permission | |
705 | } | |
706 | } | |
707 | ||
708 | if auth_required { | |
26858dba | 709 | match auth.check_auth(&parts.headers, &method, &user_info) { |
e6dc35ac | 710 | Ok(authid) => rpcenv.set_auth_id(Some(authid.to_string())), |
26858dba SR |
711 | Err(auth_err) => { |
712 | let err = match auth_err { | |
713 | AuthError::Generic(err) => err, | |
714 | AuthError::NoData => { | |
715 | format_err!("no authentication credentials provided.") | |
716 | } | |
717 | }; | |
4fdf13f9 | 718 | let peer = peer.ip(); |
d43c407a TL |
719 | auth_logger()?.log(format!( |
720 | "authentication failure; rhost={} msg={}", | |
721 | peer, err | |
722 | )); | |
4fdf13f9 | 723 | |
5ddf8cb1 | 724 | // always delay unauthorized calls by 3 seconds (from start of request) |
8aa67ee7 | 725 | let err = http_err!(UNAUTHORIZED, "authentication failed - {}", err); |
0a8d773a | 726 | tokio::time::sleep_until(Instant::from_std(delay_unauth_time)).await; |
ad51d02a | 727 | return Ok((formatter.format_error)(err)); |
5ddf8cb1 | 728 | } |
b9903d63 DM |
729 | } |
730 | } | |
d7d23785 | 731 | |
0ac61247 | 732 | match api_method { |
255f378a | 733 | None => { |
8aa67ee7 | 734 | let err = http_err!(NOT_FOUND, "Path '{}' not found.", path); |
ad51d02a | 735 | return Ok((formatter.format_error)(err)); |
49d123ee | 736 | } |
255f378a | 737 | Some(api_method) => { |
e6dc35ac | 738 | let auth_id = rpcenv.get_auth_id(); |
d43c407a TL |
739 | if !check_api_permission( |
740 | api_method.access.permission, | |
741 | auth_id.as_deref(), | |
742 | &uri_param, | |
743 | user_info.as_ref(), | |
744 | ) { | |
8aa67ee7 | 745 | let err = http_err!(FORBIDDEN, "permission check failed"); |
0a8d773a | 746 | tokio::time::sleep_until(Instant::from_std(access_forbidden_time)).await; |
4b40148c DM |
747 | return Ok((formatter.format_error)(err)); |
748 | } | |
749 | ||
4299ca72 | 750 | let result = if api_method.protected && env_type == RpcEnvironmentType::PUBLIC { |
29633e2f | 751 | proxy_protected_request(api_method, parts, body, peer).await |
f1204833 | 752 | } else { |
d43c407a TL |
753 | handle_api_request(rpcenv, api_method, formatter, parts, body, uri_param) |
754 | .await | |
4299ca72 DM |
755 | }; |
756 | ||
8e7e2223 TL |
757 | let mut response = match result { |
758 | Ok(resp) => resp, | |
759 | Err(err) => (formatter.format_error)(err), | |
760 | }; | |
761 | ||
e6dc35ac FG |
762 | if let Some(auth_id) = auth_id { |
763 | let auth_id: Authid = auth_id.parse()?; | |
764 | response.extensions_mut().insert(auth_id); | |
f1204833 | 765 | } |
8e7e2223 TL |
766 | |
767 | return Ok(response); | |
7e21da6e | 768 | } |
9bc17e8d DM |
769 | } |
770 | } | |
d43c407a | 771 | } else { |
7f168523 | 772 | // not Auth required for accessing files! |
9bc17e8d | 773 | |
7d4ef127 | 774 | if method != hyper::Method::GET { |
ad51d02a | 775 | bail!("Unsupported HTTP method {}", method); |
7d4ef127 DM |
776 | } |
777 | ||
f4c514c1 | 778 | if comp_len == 0 { |
c30816c1 | 779 | let language = extract_lang_header(&parts.headers); |
26858dba SR |
780 | match auth.check_auth(&parts.headers, &method, &user_info) { |
781 | Ok(auth_id) => { | |
782 | if !auth_id.is_token() { | |
e6dc35ac FG |
783 | let userid = auth_id.user(); |
784 | let new_csrf_token = assemble_csrf_prevention_token(csrf_secret(), userid); | |
d43c407a TL |
785 | return Ok(get_index( |
786 | Some(userid.clone()), | |
787 | Some(new_csrf_token), | |
788 | language, | |
789 | &api, | |
790 | parts, | |
791 | )); | |
792 | } | |
7f168523 | 793 | } |
26858dba SR |
794 | Err(AuthError::Generic(_)) => { |
795 | tokio::time::sleep_until(Instant::from_std(delay_unauth_time)).await; | |
796 | } | |
797 | Err(AuthError::NoData) => {} | |
7f168523 | 798 | } |
26858dba | 799 | return Ok(get_index(None, None, language, &api, parts)); |
f4c514c1 DM |
800 | } else { |
801 | let filename = api.find_alias(&components); | |
59477ad2 DC |
802 | let compression = extract_compression_method(&parts.headers); |
803 | return handle_static_file_download(filename, compression).await; | |
f4c514c1 | 804 | } |
9bc17e8d DM |
805 | } |
806 | ||
8aa67ee7 | 807 | Err(http_err!(NOT_FOUND, "Path '{}' not found.", path)) |
9bc17e8d | 808 | } |