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