]> git.proxmox.com Git - proxmox-backup.git/blame - src/client/http_client.rs
client/http_client: add necessary brackets
[proxmox-backup.git] / src / client / http_client.rs
CommitLineData
c2b94534 1use std::io::Write;
dd4b42ba
DC
2use std::sync::{Arc, Mutex, RwLock};
3use std::time::Duration;
597641fd 4
f7d4e4b5 5use anyhow::{bail, format_err, Error};
82ab7230 6use futures::*;
7a57cb77
WB
7use http::Uri;
8use http::header::HeaderValue;
9use http::{Request, Response};
10use hyper::Body;
1434f4f8 11use hyper::client::{Client, HttpConnector};
d59dbeca 12use openssl::{ssl::{SslConnector, SslMethod}, x509::X509StoreContextRef};
ba3a60b2 13use serde_json::{json, Value};
8a1028e0 14use percent_encoding::percent_encode;
7a57cb77 15use xdg::BaseDirectories;
1fdb4c6f 16
501f4fa2 17use proxmox::{
91f5594c 18 api::error::HttpError,
501f4fa2 19 sys::linux::tty,
5eb9dd0c 20 tools::fs::{file_get_json, replace_file, CreateOptions},
e18a6c9e
DM
21};
22
7a57cb77 23use super::pipe_to_stream::PipeToSendStream;
34aa8e13 24use crate::api2::types::{Authid, Userid};
97168f92
DM
25use crate::tools::{
26 self,
27 BroadcastFuture,
28 DEFAULT_ENCODE_SET,
5eb9dd0c 29 http::HttpsConnector,
97168f92 30};
986bef16 31
4799280c 32/// Timeout used for several HTTP operations that are expected to finish quickly but may block in
a941bbd0
TL
33/// certain error conditions. Keep it generous, to avoid false-positive under high load.
34const HTTP_TIMEOUT: Duration = Duration::from_secs(2 * 60);
4799280c 35
5a2df000 36#[derive(Clone)]
e240d8be 37pub struct AuthInfo {
34aa8e13 38 pub auth_id: Authid,
3743dee6
DM
39 pub ticket: String,
40 pub token: String,
5a2df000 41}
56458d97 42
d59dbeca 43pub struct HttpClientOptions {
5030b7ce 44 prefix: Option<String>,
d59dbeca
DM
45 password: Option<String>,
46 fingerprint: Option<String>,
47 interactive: bool,
48 ticket_cache: bool,
5a74756c 49 fingerprint_cache: bool,
d59dbeca
DM
50 verify_cert: bool,
51}
52
53impl HttpClientOptions {
54
93e3581c 55 pub fn new_interactive(password: Option<String>, fingerprint: Option<String>) -> Self {
d59dbeca 56 Self {
93e3581c
FG
57 password,
58 fingerprint,
59 fingerprint_cache: true,
60 ticket_cache: true,
61 interactive: true,
62 prefix: Some("proxmox-backup".to_string()),
63 ..Self::default()
64 }
65 }
66
67 pub fn new_non_interactive(password: String, fingerprint: Option<String>) -> Self {
68 Self {
69 password: Some(password),
70 fingerprint,
71 ..Self::default()
d59dbeca
DM
72 }
73 }
74
5030b7ce
DM
75 pub fn prefix(mut self, prefix: Option<String>) -> Self {
76 self.prefix = prefix;
77 self
78 }
79
d59dbeca
DM
80 pub fn password(mut self, password: Option<String>) -> Self {
81 self.password = password;
82 self
83 }
84
85 pub fn fingerprint(mut self, fingerprint: Option<String>) -> Self {
86 self.fingerprint = fingerprint;
87 self
88 }
89
90 pub fn interactive(mut self, interactive: bool) -> Self {
91 self.interactive = interactive;
92 self
93 }
94
95 pub fn ticket_cache(mut self, ticket_cache: bool) -> Self {
96 self.ticket_cache = ticket_cache;
97 self
98 }
99
5a74756c
DM
100 pub fn fingerprint_cache(mut self, fingerprint_cache: bool) -> Self {
101 self.fingerprint_cache = fingerprint_cache;
102 self
103 }
104
d59dbeca
DM
105 pub fn verify_cert(mut self, verify_cert: bool) -> Self {
106 self.verify_cert = verify_cert;
107 self
108 }
109}
110
93e3581c
FG
111impl Default for HttpClientOptions {
112 fn default() -> Self {
113 Self {
114 prefix: None,
115 password: None,
116 fingerprint: None,
117 interactive: false,
118 ticket_cache: false,
119 fingerprint_cache: false,
120 verify_cert: true,
121 }
122 }
123}
124
151c6ce2 125/// HTTP(S) API client
597641fd 126pub struct HttpClient {
1434f4f8 127 client: Client<HttpsConnector>,
597641fd 128 server: String,
ba20987a 129 port: u16,
d59dbeca 130 fingerprint: Arc<Mutex<Option<String>>>,
34aa8e13 131 first_auth: Option<BroadcastFuture<()>>,
dd4b42ba
DC
132 auth: Arc<RwLock<AuthInfo>>,
133 ticket_abort: futures::future::AbortHandle,
d59dbeca 134 _options: HttpClientOptions,
597641fd
DM
135}
136
e240d8be 137/// Delete stored ticket data (logout)
e7cb4dc5 138pub fn delete_ticket_info(prefix: &str, server: &str, username: &Userid) -> Result<(), Error> {
e240d8be 139
5030b7ce 140 let base = BaseDirectories::with_prefix(prefix)?;
e240d8be
DM
141
142 // usually /run/user/<uid>/...
143 let path = base.place_runtime_file("tickets")?;
144
145 let mode = nix::sys::stat::Mode::from_bits_truncate(0o0600);
146
147 let mut data = file_get_json(&path, Some(json!({})))?;
148
149 if let Some(map) = data[server].as_object_mut() {
e7cb4dc5 150 map.remove(username.as_str());
e240d8be
DM
151 }
152
feaa1ad3 153 replace_file(path, data.to_string().as_bytes(), CreateOptions::new().perm(mode))?;
e240d8be
DM
154
155 Ok(())
156}
157
5030b7ce 158fn store_fingerprint(prefix: &str, server: &str, fingerprint: &str) -> Result<(), Error> {
5a74756c 159
5030b7ce 160 let base = BaseDirectories::with_prefix(prefix)?;
5a74756c 161
5030b7ce 162 // usually ~/.config/<prefix>/fingerprints
5a74756c
DM
163 let path = base.place_config_file("fingerprints")?;
164
165 let raw = match std::fs::read_to_string(&path) {
166 Ok(v) => v,
167 Err(err) => {
168 if err.kind() == std::io::ErrorKind::NotFound {
169 String::new()
170 } else {
171 bail!("unable to read fingerprints from {:?} - {}", path, err);
172 }
173 }
174 };
175
176 let mut result = String::new();
177
178 raw.split('\n').for_each(|line| {
179 let items: Vec<String> = line.split_whitespace().map(String::from).collect();
180 if items.len() == 2 {
29077d95 181 if items[0] == server {
5a74756c
DM
182 // found, add later with new fingerprint
183 } else {
184 result.push_str(line);
185 result.push('\n');
186 }
187 }
188 });
189
190 result.push_str(server);
191 result.push(' ');
192 result.push_str(fingerprint);
193 result.push('\n');
194
195 replace_file(path, result.as_bytes(), CreateOptions::new())?;
196
197 Ok(())
198}
199
5030b7ce 200fn load_fingerprint(prefix: &str, server: &str) -> Option<String> {
5a74756c 201
5030b7ce 202 let base = BaseDirectories::with_prefix(prefix).ok()?;
5a74756c 203
5030b7ce 204 // usually ~/.config/<prefix>/fingerprints
5a74756c
DM
205 let path = base.place_config_file("fingerprints").ok()?;
206
207 let raw = std::fs::read_to_string(&path).ok()?;
208
209 for line in raw.split('\n') {
210 let items: Vec<String> = line.split_whitespace().map(String::from).collect();
29077d95 211 if items.len() == 2 && items[0] == server {
8db14689 212 return Some(items[1].clone());
5a74756c
DM
213 }
214 }
215
216 None
217}
218
5030b7ce 219fn store_ticket_info(prefix: &str, server: &str, username: &str, ticket: &str, token: &str) -> Result<(), Error> {
ba3a60b2 220
5030b7ce 221 let base = BaseDirectories::with_prefix(prefix)?;
ba3a60b2
DM
222
223 // usually /run/user/<uid>/...
224 let path = base.place_runtime_file("tickets")?;
225
226 let mode = nix::sys::stat::Mode::from_bits_truncate(0o0600);
227
e18a6c9e 228 let mut data = file_get_json(&path, Some(json!({})))?;
ba3a60b2 229
6a7be83e 230 let now = proxmox::tools::time::epoch_i64();
ba3a60b2
DM
231
232 data[server][username] = json!({ "timestamp": now, "ticket": ticket, "token": token});
233
234 let mut new_data = json!({});
235
236 let ticket_lifetime = tools::ticket::TICKET_LIFETIME - 60;
237
238 let empty = serde_json::map::Map::new();
239 for (server, info) in data.as_object().unwrap_or(&empty) {
afef7f3b 240 for (user, uinfo) in info.as_object().unwrap_or(&empty) {
4e32d1c5
DM
241 if let Some(timestamp) = uinfo["timestamp"].as_i64() {
242 let age = now - timestamp;
243 if age < ticket_lifetime {
244 new_data[server][user] = uinfo.clone();
ba3a60b2
DM
245 }
246 }
247 }
248 }
249
feaa1ad3 250 replace_file(path, new_data.to_string().as_bytes(), CreateOptions::new().perm(mode))?;
ba3a60b2
DM
251
252 Ok(())
253}
254
e7cb4dc5 255fn load_ticket_info(prefix: &str, server: &str, userid: &Userid) -> Option<(String, String)> {
5030b7ce 256 let base = BaseDirectories::with_prefix(prefix).ok()?;
ba3a60b2
DM
257
258 // usually /run/user/<uid>/...
66c8eb93
CE
259 let path = base.place_runtime_file("tickets").ok()?;
260 let data = file_get_json(&path, None).ok()?;
6a7be83e 261 let now = proxmox::tools::time::epoch_i64();
ba3a60b2 262 let ticket_lifetime = tools::ticket::TICKET_LIFETIME - 60;
e7cb4dc5 263 let uinfo = data[server][userid.as_str()].as_object()?;
66c8eb93
CE
264 let timestamp = uinfo["timestamp"].as_i64()?;
265 let age = now - timestamp;
266
267 if age < ticket_lifetime {
268 let ticket = uinfo["ticket"].as_str()?;
269 let token = uinfo["token"].as_str()?;
270 Some((ticket.to_owned(), token.to_owned()))
271 } else {
272 None
ba3a60b2 273 }
ba3a60b2
DM
274}
275
a2daecc2
DM
276fn build_uri(server: &str, port: u16, path: &str, query: Option<String>) -> Result<Uri, Error> {
277 let path = path.trim_matches('/');
278 let bytes = server.as_bytes();
279 let len = bytes.len();
280 let uri = if len > 3 && bytes.contains(&b':') && bytes[0] != b'[' && bytes[len-1] != b']' {
281 if let Some(query) = query {
282 format!("https://[{}]:{}/{}?{}", server, port, path, query)
283 } else {
284 format!("https://[{}]:{}/{}", server, port, path)
285 }
286 } else {
287 if let Some(query) = query {
288 format!("https://{}:{}/{}?{}", server, port, path, query)
289 } else {
290 format!("https://{}:{}/{}", server, port, path)
291 }
292 };
293 Ok(uri.parse()?)
294}
295
597641fd 296impl HttpClient {
e7cb4dc5
WB
297 pub fn new(
298 server: &str,
ba20987a 299 port: u16,
34aa8e13 300 auth_id: &Authid,
e7cb4dc5
WB
301 mut options: HttpClientOptions,
302 ) -> Result<Self, Error> {
d59dbeca
DM
303
304 let verified_fingerprint = Arc::new(Mutex::new(None));
305
5a74756c 306 let mut fingerprint = options.fingerprint.take();
a6e3da98
DM
307
308 if fingerprint.is_some() {
309 // do not store fingerprints passed via options in cache
310 options.fingerprint_cache = false;
311 } else if options.fingerprint_cache && options.prefix.is_some() {
5030b7ce 312 fingerprint = load_fingerprint(options.prefix.as_ref().unwrap(), server);
5a74756c
DM
313 }
314
5030b7ce
DM
315 let mut ssl_connector_builder = SslConnector::builder(SslMethod::tls()).unwrap();
316
317 if options.verify_cert {
318 let server = server.to_string();
319 let verified_fingerprint = verified_fingerprint.clone();
320 let interactive = options.interactive;
321 let fingerprint_cache = options.fingerprint_cache;
322 let prefix = options.prefix.clone();
323 ssl_connector_builder.set_verify_callback(openssl::ssl::SslVerifyMode::PEER, move |valid, ctx| {
324 let (valid, fingerprint) = Self::verify_callback(valid, ctx, fingerprint.clone(), interactive);
325 if valid {
326 if let Some(fingerprint) = fingerprint {
327 if fingerprint_cache && prefix.is_some() {
328 if let Err(err) = store_fingerprint(
329 prefix.as_ref().unwrap(), &server, &fingerprint) {
330 eprintln!("{}", err);
331 }
332 }
333 *verified_fingerprint.lock().unwrap() = Some(fingerprint);
334 }
335 }
336 valid
337 });
338 } else {
339 ssl_connector_builder.set_verify(openssl::ssl::SslVerifyMode::NONE);
340 }
341
5eb9dd0c 342 let mut httpc = HttpConnector::new();
5030b7ce 343 httpc.set_nodelay(true); // important for h2 download performance!
5030b7ce
DM
344 httpc.enforce_http(false); // we want https...
345
bb14d467 346 httpc.set_connect_timeout(Some(std::time::Duration::new(10, 0)));
5030b7ce
DM
347 let https = HttpsConnector::with_connector(httpc, ssl_connector_builder.build());
348
349 let client = Client::builder()
350 //.http2_initial_stream_window_size( (1 << 31) - 2)
351 //.http2_initial_connection_window_size( (1 << 31) - 2)
352 .build::<_, Body>(https);
d59dbeca
DM
353
354 let password = options.password.take();
5030b7ce 355 let use_ticket_cache = options.ticket_cache && options.prefix.is_some();
5a2df000 356
cc2ce4a9
DM
357 let password = if let Some(password) = password {
358 password
45cdce06 359 } else {
34aa8e13
FG
360 let userid = if auth_id.is_token() {
361 bail!("API token secret must be provided!");
362 } else {
363 auth_id.user()
364 };
d59dbeca 365 let mut ticket_info = None;
5030b7ce 366 if use_ticket_cache {
e7cb4dc5 367 ticket_info = load_ticket_info(options.prefix.as_ref().unwrap(), server, userid);
d59dbeca
DM
368 }
369 if let Some((ticket, _token)) = ticket_info {
370 ticket
371 } else {
e7cb4dc5 372 Self::get_password(userid, options.interactive)?
d59dbeca 373 }
45cdce06
DM
374 };
375
dd4b42ba 376 let auth = Arc::new(RwLock::new(AuthInfo {
34aa8e13 377 auth_id: auth_id.clone(),
dd4b42ba
DC
378 ticket: password.clone(),
379 token: "".to_string(),
380 }));
381
382 let server2 = server.to_string();
383 let client2 = client.clone();
384 let auth2 = auth.clone();
385 let prefix2 = options.prefix.clone();
386
387 let renewal_future = async move {
388 loop {
0a8d773a 389 tokio::time::sleep(Duration::new(60*15, 0)).await; // 15 minutes
34aa8e13 390 let (auth_id, ticket) = {
dd4b42ba 391 let authinfo = auth2.read().unwrap().clone();
34aa8e13 392 (authinfo.auth_id, authinfo.ticket)
dd4b42ba 393 };
34aa8e13 394 match Self::credentials(client2.clone(), server2.clone(), port, auth_id.user().clone(), ticket).await {
dd4b42ba 395 Ok(auth) => {
dbd00a57 396 if use_ticket_cache && prefix2.is_some() {
34aa8e13 397 let _ = store_ticket_info(prefix2.as_ref().unwrap(), &server2, &auth.auth_id.to_string(), &auth.ticket, &auth.token);
dd4b42ba
DC
398 }
399 *auth2.write().unwrap() = auth;
400 },
401 Err(err) => {
402 eprintln!("re-authentication failed: {}", err);
403 return;
404 }
405 }
406 }
407 };
408
409 let (renewal_future, ticket_abort) = futures::future::abortable(renewal_future);
410
d59dbeca
DM
411 let login_future = Self::credentials(
412 client.clone(),
413 server.to_owned(),
ba20987a 414 port,
34aa8e13 415 auth_id.user().clone(),
29077d95 416 password,
5030b7ce
DM
417 ).map_ok({
418 let server = server.to_string();
419 let prefix = options.prefix.clone();
dd4b42ba 420 let authinfo = auth.clone();
5030b7ce
DM
421
422 move |auth| {
dbd00a57 423 if use_ticket_cache && prefix.is_some() {
34aa8e13 424 let _ = store_ticket_info(prefix.as_ref().unwrap(), &server, &auth.auth_id.to_string(), &auth.ticket, &auth.token);
5030b7ce 425 }
dd4b42ba
DC
426 *authinfo.write().unwrap() = auth;
427 tokio::spawn(renewal_future);
5030b7ce
DM
428 }
429 });
45cdce06 430
34aa8e13
FG
431 let first_auth = if auth_id.is_token() {
432 // TODO check access here?
433 None
434 } else {
435 Some(BroadcastFuture::new(Box::new(login_future)))
436 };
437
45cdce06 438 Ok(Self {
5a2df000 439 client,
597641fd 440 server: String::from(server),
ba20987a 441 port,
d59dbeca 442 fingerprint: verified_fingerprint,
dd4b42ba
DC
443 auth,
444 ticket_abort,
34aa8e13 445 first_auth,
d59dbeca 446 _options: options,
45cdce06 447 })
597641fd
DM
448 }
449
1a7a0e74 450 /// Login
e240d8be 451 ///
add5861e 452 /// Login is done on demand, so this is only required if you need
e240d8be 453 /// access to authentication data in 'AuthInfo'.
0081903f
DM
454 ///
455 /// Note: tickets a periodially re-newed, so one can use this
456 /// to query changed ticket.
96f5e80a 457 pub async fn login(&self) -> Result<AuthInfo, Error> {
34aa8e13
FG
458 if let Some(future) = &self.first_auth {
459 future.listen().await?;
460 }
461
dd4b42ba
DC
462 let authinfo = self.auth.read().unwrap();
463 Ok(authinfo.clone())
e240d8be
DM
464 }
465
d59dbeca
DM
466 /// Returns the optional fingerprint passed to the new() constructor.
467 pub fn fingerprint(&self) -> Option<String> {
468 (*self.fingerprint.lock().unwrap()).clone()
469 }
470
e7cb4dc5 471 fn get_password(username: &Userid, interactive: bool) -> Result<String, Error> {
56458d97 472 // If we're on a TTY, query the user for a password
d59dbeca 473 if interactive && tty::stdin_isatty() {
99d863d7
DM
474 let msg = format!("Password for \"{}\": ", username);
475 return Ok(String::from_utf8(tty::read_password(&msg)?)?);
56458d97
WB
476 }
477
478 bail!("no password input mechanism available");
479 }
480
d59dbeca
DM
481 fn verify_callback(
482 valid: bool, ctx:
483 &mut X509StoreContextRef,
484 expected_fingerprint: Option<String>,
485 interactive: bool,
5030b7ce
DM
486 ) -> (bool, Option<String>) {
487 if valid { return (true, None); }
d59dbeca
DM
488
489 let cert = match ctx.current_cert() {
490 Some(cert) => cert,
5030b7ce 491 None => return (false, None),
d59dbeca
DM
492 };
493
494 let depth = ctx.error_depth();
5030b7ce 495 if depth != 0 { return (false, None); }
d59dbeca
DM
496
497 let fp = match cert.digest(openssl::hash::MessageDigest::sha256()) {
498 Ok(fp) => fp,
5030b7ce 499 Err(_) => return (false, None), // should not happen
d59dbeca
DM
500 };
501 let fp_string = proxmox::tools::digest_to_hex(&fp);
502 let fp_string = fp_string.as_bytes().chunks(2).map(|v| std::str::from_utf8(v).unwrap())
503 .collect::<Vec<&str>>().join(":");
504
505 if let Some(expected_fingerprint) = expected_fingerprint {
1bd6f32b 506 if expected_fingerprint.to_lowercase() == fp_string {
5030b7ce 507 return (true, Some(fp_string));
d59dbeca 508 } else {
5030b7ce 509 return (false, None);
d59dbeca
DM
510 }
511 }
512
513 // If we're on a TTY, query the user
514 if interactive && tty::stdin_isatty() {
515 println!("fingerprint: {}", fp_string);
516 loop {
a595f0fe 517 print!("Are you sure you want to continue connecting? (y/n): ");
d59dbeca 518 let _ = std::io::stdout().flush();
a595f0fe
WB
519 use std::io::{BufRead, BufReader};
520 let mut line = String::new();
521 match BufReader::new(std::io::stdin()).read_line(&mut line) {
522 Ok(_) => {
523 let trimmed = line.trim();
524 if trimmed == "y" || trimmed == "Y" {
5030b7ce 525 return (true, Some(fp_string));
a595f0fe 526 } else if trimmed == "n" || trimmed == "N" {
5030b7ce 527 return (false, None);
a595f0fe
WB
528 } else {
529 continue;
d59dbeca
DM
530 }
531 }
a595f0fe 532 Err(_) => return (false, None),
d59dbeca
DM
533 }
534 }
535 }
5030b7ce 536 (false, None)
a6b75513
DM
537 }
538
1a7a0e74 539 pub async fn request(&self, mut req: Request<Body>) -> Result<Value, Error> {
597641fd 540
5a2df000 541 let client = self.client.clone();
597641fd 542
1a7a0e74 543 let auth = self.login().await?;
34aa8e13 544 if auth.auth_id.is_token() {
36273905 545 let enc_api_token = format!("PBSAPIToken {}:{}", auth.auth_id, percent_encode(auth.ticket.as_bytes(), DEFAULT_ENCODE_SET));
34aa8e13
FG
546 req.headers_mut().insert("Authorization", HeaderValue::from_str(&enc_api_token).unwrap());
547 } else {
548 let enc_ticket = format!("PBSAuthCookie={}", percent_encode(auth.ticket.as_bytes(), DEFAULT_ENCODE_SET));
549 req.headers_mut().insert("Cookie", HeaderValue::from_str(&enc_ticket).unwrap());
550 req.headers_mut().insert("CSRFPreventionToken", HeaderValue::from_str(&auth.token).unwrap());
551 }
597641fd 552
1a7a0e74 553 Self::api_request(client, req).await
1fdb4c6f
DM
554 }
555
1a7a0e74 556 pub async fn get(
a6782ca1
WB
557 &self,
558 path: &str,
559 data: Option<Value>,
1a7a0e74 560 ) -> Result<Value, Error> {
ba20987a 561 let req = Self::request_builder(&self.server, self.port, "GET", path, data)?;
1a7a0e74 562 self.request(req).await
a6b75513
DM
563 }
564
1a7a0e74 565 pub async fn delete(
a6782ca1
WB
566 &mut self,
567 path: &str,
568 data: Option<Value>,
1a7a0e74 569 ) -> Result<Value, Error> {
ba20987a 570 let req = Self::request_builder(&self.server, self.port, "DELETE", path, data)?;
1a7a0e74 571 self.request(req).await
a6b75513
DM
572 }
573
1a7a0e74 574 pub async fn post(
a6782ca1
WB
575 &mut self,
576 path: &str,
577 data: Option<Value>,
1a7a0e74 578 ) -> Result<Value, Error> {
ba20987a 579 let req = Self::request_builder(&self.server, self.port, "POST", path, data)?;
1a7a0e74 580 self.request(req).await
024f11bb
DM
581 }
582
3c945d73
DC
583 pub async fn put(
584 &mut self,
585 path: &str,
586 data: Option<Value>,
587 ) -> Result<Value, Error> {
588 let req = Self::request_builder(&self.server, self.port, "PUT", path, data)?;
589 self.request(req).await
590 }
591
1a7a0e74 592 pub async fn download(
a6782ca1
WB
593 &mut self,
594 path: &str,
1a7a0e74 595 output: &mut (dyn Write + Send),
3d571d55 596 ) -> Result<(), Error> {
ba20987a 597 let mut req = Self::request_builder(&self.server, self.port, "GET", path, None)?;
024f11bb 598
5a2df000 599 let client = self.client.clone();
1fdb4c6f 600
1a7a0e74 601 let auth = self.login().await?;
81da38c1 602
1a7a0e74
DM
603 let enc_ticket = format!("PBSAuthCookie={}", percent_encode(auth.ticket.as_bytes(), DEFAULT_ENCODE_SET));
604 req.headers_mut().insert("Cookie", HeaderValue::from_str(&enc_ticket).unwrap());
6f62c924 605
d148958b
FG
606 let resp = tokio::time::timeout(
607 HTTP_TIMEOUT,
608 client.request(req)
609 )
610 .await
611 .map_err(|_| format_err!("http download request timed out"))??;
1a7a0e74
DM
612 let status = resp.status();
613 if !status.is_success() {
614 HttpClient::api_response(resp)
615 .map(|_| Err(format_err!("unknown error")))
616 .await?
617 } else {
618 resp.into_body()
5a2df000 619 .map_err(Error::from)
1a7a0e74
DM
620 .try_fold(output, move |acc, chunk| async move {
621 acc.write_all(&chunk)?;
622 Ok::<_, Error>(acc)
5a2df000 623 })
1a7a0e74
DM
624 .await?;
625 }
626 Ok(())
6f62c924
DM
627 }
628
1a7a0e74 629 pub async fn upload(
04512d30
DM
630 &mut self,
631 content_type: &str,
632 body: Body,
633 path: &str,
634 data: Option<Value>,
1a7a0e74 635 ) -> Result<Value, Error> {
81da38c1 636
a2daecc2
DM
637 let query = match data {
638 Some(data) => Some(tools::json_object_to_query(data)?),
639 None => None,
640 };
641 let url = build_uri(&self.server, self.port, path, query)?;
81da38c1 642
5a2df000 643 let req = Request::builder()
81da38c1
DM
644 .method("POST")
645 .uri(url)
646 .header("User-Agent", "proxmox-backup-client/1.0")
5a2df000
DM
647 .header("Content-Type", content_type)
648 .body(body).unwrap();
81da38c1 649
1a7a0e74 650 self.request(req).await
1fdb4c6f
DM
651 }
652
1a7a0e74 653 pub async fn start_h2_connection(
fb047083
DM
654 &self,
655 mut req: Request<Body>,
656 protocol_name: String,
dc089345 657 ) -> Result<(H2Client, futures::future::AbortHandle), Error> {
cf639a47
DM
658
659 let client = self.client.clone();
34aa8e13
FG
660 let auth = self.login().await?;
661
662 if auth.auth_id.is_token() {
36273905 663 let enc_api_token = format!("PBSAPIToken {}:{}", auth.auth_id, percent_encode(auth.ticket.as_bytes(), DEFAULT_ENCODE_SET));
34aa8e13
FG
664 req.headers_mut().insert("Authorization", HeaderValue::from_str(&enc_api_token).unwrap());
665 } else {
666 let enc_ticket = format!("PBSAuthCookie={}", percent_encode(auth.ticket.as_bytes(), DEFAULT_ENCODE_SET));
667 req.headers_mut().insert("Cookie", HeaderValue::from_str(&enc_ticket).unwrap());
668 req.headers_mut().insert("CSRFPreventionToken", HeaderValue::from_str(&auth.token).unwrap());
669 }
cf639a47 670
1a7a0e74 671 req.headers_mut().insert("UPGRADE", HeaderValue::from_str(&protocol_name).unwrap());
cf639a47 672
d148958b
FG
673 let resp = tokio::time::timeout(
674 HTTP_TIMEOUT,
675 client.request(req)
676 )
677 .await
678 .map_err(|_| format_err!("http upgrade request timed out"))??;
1a7a0e74 679 let status = resp.status();
cf639a47 680
1a7a0e74 681 if status != http::StatusCode::SWITCHING_PROTOCOLS {
ca611955
DM
682 Self::api_response(resp).await?;
683 bail!("unknown error");
1a7a0e74
DM
684 }
685
89e9134a 686 let upgraded = hyper::upgrade::on(resp).await?;
1a7a0e74
DM
687
688 let max_window_size = (1 << 31) - 2;
689
690 let (h2, connection) = h2::client::Builder::new()
691 .initial_connection_window_size(max_window_size)
692 .initial_window_size(max_window_size)
693 .max_frame_size(4*1024*1024)
694 .handshake(upgraded)
695 .await?;
696
697 let connection = connection
97168f92 698 .map_err(|_| eprintln!("HTTP/2.0 connection failed"));
1a7a0e74 699
dc089345 700 let (connection, abort) = futures::future::abortable(connection);
1a7a0e74
DM
701 // A cancellable future returns an Option which is None when cancelled and
702 // Some when it finished instead, since we don't care about the return type we
703 // need to map it away:
704 let connection = connection.map(|_| ());
705
706 // Spawn a new task to drive the connection state
db0cb9ce 707 tokio::spawn(connection);
1a7a0e74
DM
708
709 // Wait until the `SendRequest` handle has available capacity.
710 let c = h2.ready().await?;
dc089345 711 Ok((H2Client::new(c), abort))
cf639a47
DM
712 }
713
9d35dbbb 714 async fn credentials(
1434f4f8 715 client: Client<HttpsConnector>,
45cdce06 716 server: String,
ba20987a 717 port: u16,
e7cb4dc5 718 username: Userid,
45cdce06 719 password: String,
9d35dbbb
DM
720 ) -> Result<AuthInfo, Error> {
721 let data = json!({ "username": username, "password": password });
ba20987a 722 let req = Self::request_builder(&server, port, "POST", "/api2/json/access/ticket", Some(data))?;
9d35dbbb
DM
723 let cred = Self::api_request(client, req).await?;
724 let auth = AuthInfo {
34aa8e13 725 auth_id: cred["data"]["username"].as_str().unwrap().parse()?,
9d35dbbb
DM
726 ticket: cred["data"]["ticket"].as_str().unwrap().to_owned(),
727 token: cred["data"]["CSRFPreventionToken"].as_str().unwrap().to_owned(),
728 };
729
9d35dbbb 730 Ok(auth)
ba3a60b2
DM
731 }
732
a6782ca1 733 async fn api_response(response: Response<Body>) -> Result<Value, Error> {
d2c48afc 734 let status = response.status();
db0cb9ce 735 let data = hyper::body::to_bytes(response.into_body()).await?;
a6782ca1
WB
736
737 let text = String::from_utf8(data.to_vec()).unwrap();
738 if status.is_success() {
11377a47
DM
739 if text.is_empty() {
740 Ok(Value::Null)
741 } else {
a6782ca1
WB
742 let value: Value = serde_json::from_str(&text)?;
743 Ok(value)
a6782ca1
WB
744 }
745 } else {
91f5594c 746 Err(Error::from(HttpError::new(status, text)))
a6782ca1 747 }
d2c48afc
DM
748 }
749
1a7a0e74 750 async fn api_request(
1434f4f8 751 client: Client<HttpsConnector>,
5a2df000 752 req: Request<Body>
1a7a0e74 753 ) -> Result<Value, Error> {
ba3a60b2 754
d148958b
FG
755 Self::api_response(
756 tokio::time::timeout(
757 HTTP_TIMEOUT,
758 client.request(req)
759 )
760 .await
761 .map_err(|_| format_err!("http request timed out"))??
762 ).await
0dffe3f9
DM
763 }
764
9e490a74
DM
765 // Read-only access to server property
766 pub fn server(&self) -> &str {
767 &self.server
768 }
769
ba20987a
DC
770 pub fn port(&self) -> u16 {
771 self.port
772 }
773
774 pub fn request_builder(server: &str, port: u16, method: &str, path: &str, data: Option<Value>) -> Result<Request<Body>, Error> {
5a2df000
DM
775 if let Some(data) = data {
776 if method == "POST" {
a2daecc2 777 let url = build_uri(server, port, path, None)?;
5a2df000
DM
778 let request = Request::builder()
779 .method(method)
780 .uri(url)
781 .header("User-Agent", "proxmox-backup-client/1.0")
782 .header(hyper::header::CONTENT_TYPE, "application/json")
783 .body(Body::from(data.to_string()))?;
a2daecc2 784 Ok(request)
5a2df000 785 } else {
9e391bb7 786 let query = tools::json_object_to_query(data)?;
a2daecc2 787 let url = build_uri(server, port, path, Some(query))?;
9e391bb7
DM
788 let request = Request::builder()
789 .method(method)
790 .uri(url)
791 .header("User-Agent", "proxmox-backup-client/1.0")
792 .header(hyper::header::CONTENT_TYPE, "application/x-www-form-urlencoded")
793 .body(Body::empty())?;
a2daecc2 794 Ok(request)
5a2df000 795 }
a2daecc2
DM
796 } else {
797 let url = build_uri(server, port, path, None)?;
798 let request = Request::builder()
799 .method(method)
800 .uri(url)
801 .header("User-Agent", "proxmox-backup-client/1.0")
802 .header(hyper::header::CONTENT_TYPE, "application/x-www-form-urlencoded")
803 .body(Body::empty())?;
1fdb4c6f 804
a2daecc2
DM
805 Ok(request)
806 }
597641fd
DM
807 }
808}
b57cb264 809
dd4b42ba
DC
810impl Drop for HttpClient {
811 fn drop(&mut self) {
812 self.ticket_abort.abort();
813 }
814}
815
9af37c8f
DM
816
817#[derive(Clone)]
818pub struct H2Client {
819 h2: h2::client::SendRequest<bytes::Bytes>,
820}
821
822impl H2Client {
823
824 pub fn new(h2: h2::client::SendRequest<bytes::Bytes>) -> Self {
825 Self { h2 }
826 }
827
2a1e6d7d
DM
828 pub async fn get(
829 &self,
830 path: &str,
831 param: Option<Value>
832 ) -> Result<Value, Error> {
792a70b9 833 let req = Self::request_builder("localhost", "GET", path, param, None).unwrap();
2a1e6d7d 834 self.request(req).await
9af37c8f
DM
835 }
836
2a1e6d7d
DM
837 pub async fn put(
838 &self,
839 path: &str,
840 param: Option<Value>
841 ) -> Result<Value, Error> {
792a70b9 842 let req = Self::request_builder("localhost", "PUT", path, param, None).unwrap();
2a1e6d7d 843 self.request(req).await
9af37c8f
DM
844 }
845
2a1e6d7d
DM
846 pub async fn post(
847 &self,
848 path: &str,
849 param: Option<Value>
850 ) -> Result<Value, Error> {
792a70b9 851 let req = Self::request_builder("localhost", "POST", path, param, None).unwrap();
2a1e6d7d 852 self.request(req).await
9af37c8f
DM
853 }
854
d4a085e5 855 pub async fn download<W: Write + Send>(
a6782ca1
WB
856 &self,
857 path: &str,
858 param: Option<Value>,
2a1e6d7d 859 mut output: W,
3d571d55 860 ) -> Result<(), Error> {
792a70b9 861 let request = Self::request_builder("localhost", "GET", path, param, None).unwrap();
dd066d28 862
2a1e6d7d 863 let response_future = self.send_request(request, None).await?;
984a7c35 864
2a1e6d7d
DM
865 let resp = response_future.await?;
866
867 let status = resp.status();
868 if !status.is_success() {
44f59dc7
DM
869 H2Client::h2api_response(resp).await?; // raise error
870 unreachable!();
2a1e6d7d
DM
871 }
872
873 let mut body = resp.into_body();
db0cb9ce
WB
874 while let Some(chunk) = body.data().await {
875 let chunk = chunk?;
876 body.flow_control().release_capacity(chunk.len())?;
2a1e6d7d
DM
877 output.write_all(&chunk)?;
878 }
879
3d571d55 880 Ok(())
dd066d28
DM
881 }
882
2a1e6d7d 883 pub async fn upload(
a6782ca1 884 &self,
f011dba0 885 method: &str, // POST or PUT
a6782ca1
WB
886 path: &str,
887 param: Option<Value>,
792a70b9 888 content_type: &str,
a6782ca1 889 data: Vec<u8>,
2a1e6d7d 890 ) -> Result<Value, Error> {
f011dba0 891 let request = Self::request_builder("localhost", method, path, param, Some(content_type)).unwrap();
9af37c8f 892
2a1e6d7d
DM
893 let mut send_request = self.h2.clone().ready().await?;
894
895 let (response, stream) = send_request.send_request(request, false).unwrap();
2a05048b
DM
896
897 PipeToSendStream::new(bytes::Bytes::from(data), stream).await?;
898
899 response
900 .map_err(Error::from)
901 .and_then(Self::h2api_response)
2a1e6d7d 902 .await
9af37c8f 903 }
adec8ea2 904
2a1e6d7d 905 async fn request(
9af37c8f 906 &self,
b57cb264 907 request: Request<()>,
2a1e6d7d 908 ) -> Result<Value, Error> {
b57cb264 909
9af37c8f 910 self.send_request(request, None)
82ab7230
DM
911 .and_then(move |response| {
912 response
913 .map_err(Error::from)
914 .and_then(Self::h2api_response)
915 })
2a1e6d7d 916 .await
82ab7230
DM
917 }
918
cf9271e2 919 pub fn send_request(
9af37c8f 920 &self,
82ab7230
DM
921 request: Request<()>,
922 data: Option<bytes::Bytes>,
a6782ca1 923 ) -> impl Future<Output = Result<h2::client::ResponseFuture, Error>> {
82ab7230 924
9af37c8f 925 self.h2.clone()
10130cf4
DM
926 .ready()
927 .map_err(Error::from)
2a05048b 928 .and_then(move |mut send_request| async move {
82ab7230
DM
929 if let Some(data) = data {
930 let (response, stream) = send_request.send_request(request, false).unwrap();
2a05048b
DM
931 PipeToSendStream::new(data, stream).await?;
932 Ok(response)
82ab7230
DM
933 } else {
934 let (response, _stream) = send_request.send_request(request, true).unwrap();
2a05048b 935 Ok(response)
82ab7230 936 }
b57cb264
DM
937 })
938 }
939
f16aea68 940 pub async fn h2api_response(
a6782ca1 941 response: Response<h2::RecvStream>,
9edd3bf1 942 ) -> Result<Value, Error> {
b57cb264
DM
943 let status = response.status();
944
945 let (_head, mut body) = response.into_parts();
946
9edd3bf1 947 let mut data = Vec::new();
db0cb9ce
WB
948 while let Some(chunk) = body.data().await {
949 let chunk = chunk?;
950 // Whenever data is received, the caller is responsible for
951 // releasing capacity back to the server once it has freed
952 // the data from memory.
9edd3bf1 953 // Let the server send more data.
db0cb9ce 954 body.flow_control().release_capacity(chunk.len())?;
9edd3bf1
DM
955 data.extend(chunk);
956 }
957
958 let text = String::from_utf8(data.to_vec()).unwrap();
959 if status.is_success() {
11377a47
DM
960 if text.is_empty() {
961 Ok(Value::Null)
962 } else {
9edd3bf1
DM
963 let mut value: Value = serde_json::from_str(&text)?;
964 if let Some(map) = value.as_object_mut() {
965 if let Some(data) = map.remove("data") {
966 return Ok(data);
b57cb264 967 }
b57cb264 968 }
9edd3bf1 969 bail!("got result without data property");
9edd3bf1
DM
970 }
971 } else {
91f5594c 972 Err(Error::from(HttpError::new(status, text)))
9edd3bf1 973 }
b57cb264
DM
974 }
975
eb2bdd1b 976 // Note: We always encode parameters with the url
792a70b9
DM
977 pub fn request_builder(
978 server: &str,
979 method: &str,
980 path: &str,
981 param: Option<Value>,
982 content_type: Option<&str>,
983 ) -> Result<Request<()>, Error> {
b57cb264 984 let path = path.trim_matches('/');
b57cb264 985
792a70b9 986 let content_type = content_type.unwrap_or("application/x-www-form-urlencoded");
a2daecc2
DM
987 let query = match param {
988 Some(param) => {
989 let query = tools::json_object_to_query(param)?;
990 // We detected problem with hyper around 6000 characters - so we try to keep on the safe side
991 if query.len() > 4096 {
992 bail!("h2 query data too large ({} bytes) - please encode data inside body", query.len());
993 }
994 Some(query)
995 }
996 None => None,
997 };
792a70b9 998
a2daecc2
DM
999 let url = build_uri(server, 8007, path, query)?;
1000 let request = Request::builder()
1001 .method(method)
1002 .uri(url)
1003 .header("User-Agent", "proxmox-backup-client/1.0")
1004 .header(hyper::header::CONTENT_TYPE, content_type)
1005 .body(())?;
1006 Ok(request)
b57cb264
DM
1007 }
1008}