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