]> git.proxmox.com Git - proxmox-backup.git/blame - pbs-client/src/http_client.rs
fix #4779: client: add missing "Connection" header for HTTP2 upgrade
[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;
5aeeb44a 25use proxmox_http::client::HttpsConnector;
2b9cf927 26use proxmox_http::uri::{build_authority, json_object_to_query};
5aeeb44a 27use proxmox_http::{ProxyConfig, RateLimiter};
8c090937 28
577095e2 29use pbs_api_types::percent_encoding::DEFAULT_ENCODE_SET;
bdfa6370 30use pbs_api_types::{Authid, RateLimitConfig, Userid};
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
3db20227 218 let raw = std::fs::read_to_string(path).ok()?;
5a74756c
DM
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
d97ff8ae 252 let ticket_lifetime = proxmox_auth_api::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 280 let path = base.place_runtime_file("tickets").ok()?;
3db20227 281 let data = file_get_json(path, None).ok()?;
6ef1b649 282 let now = proxmox_time::epoch_i64();
d97ff8ae 283 let ticket_lifetime = proxmox_auth_api::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 391
fc65ec43
SH
392 let proxy_config = ProxyConfig::from_proxy_env()?;
393 if let Some(config) = proxy_config {
394 log::info!("Using proxy connection: {}:{}", config.host, config.port);
395 https.set_proxy(config);
396 }
397
5030b7ce 398 let client = Client::builder()
bdfa6370
TL
399 //.http2_initial_stream_window_size( (1 << 31) - 2)
400 //.http2_initial_connection_window_size( (1 << 31) - 2)
5030b7ce 401 .build::<_, Body>(https);
d59dbeca
DM
402
403 let password = options.password.take();
5030b7ce 404 let use_ticket_cache = options.ticket_cache && options.prefix.is_some();
5a2df000 405
cc2ce4a9
DM
406 let password = if let Some(password) = password {
407 password
45cdce06 408 } else {
34aa8e13
FG
409 let userid = if auth_id.is_token() {
410 bail!("API token secret must be provided!");
411 } else {
412 auth_id.user()
413 };
d59dbeca 414 let mut ticket_info = None;
5030b7ce 415 if use_ticket_cache {
e7cb4dc5 416 ticket_info = load_ticket_info(options.prefix.as_ref().unwrap(), server, userid);
d59dbeca
DM
417 }
418 if let Some((ticket, _token)) = ticket_info {
419 ticket
420 } else {
e7cb4dc5 421 Self::get_password(userid, options.interactive)?
d59dbeca 422 }
45cdce06
DM
423 };
424
dd4b42ba 425 let auth = Arc::new(RwLock::new(AuthInfo {
34aa8e13 426 auth_id: auth_id.clone(),
dd4b42ba
DC
427 ticket: password.clone(),
428 token: "".to_string(),
429 }));
430
431 let server2 = server.to_string();
432 let client2 = client.clone();
433 let auth2 = auth.clone();
434 let prefix2 = options.prefix.clone();
435
436 let renewal_future = async move {
437 loop {
bdfa6370 438 tokio::time::sleep(Duration::new(60 * 15, 0)).await; // 15 minutes
34aa8e13 439 let (auth_id, ticket) = {
dd4b42ba 440 let authinfo = auth2.read().unwrap().clone();
34aa8e13 441 (authinfo.auth_id, authinfo.ticket)
dd4b42ba 442 };
bdfa6370
TL
443 match Self::credentials(
444 client2.clone(),
445 server2.clone(),
446 port,
447 auth_id.user().clone(),
448 ticket,
449 )
450 .await
451 {
dd4b42ba 452 Ok(auth) => {
dbd00a57 453 if use_ticket_cache && prefix2.is_some() {
70b22b62 454 if let Err(err) = store_ticket_info(
bdfa6370
TL
455 prefix2.as_ref().unwrap(),
456 &server2,
457 &auth.auth_id.to_string(),
458 &auth.ticket,
459 &auth.token,
70b22b62 460 ) {
73809d55
FE
461 if tty::stdout_isatty() {
462 log::error!("storing login ticket failed: {}", err);
463 }
70b22b62 464 }
dd4b42ba
DC
465 }
466 *auth2.write().unwrap() = auth;
bdfa6370 467 }
dd4b42ba 468 Err(err) => {
e10fccf5 469 log::error!("re-authentication failed: {}", err);
dd4b42ba
DC
470 return;
471 }
472 }
473 }
474 };
475
476 let (renewal_future, ticket_abort) = futures::future::abortable(renewal_future);
477
d59dbeca
DM
478 let login_future = Self::credentials(
479 client.clone(),
480 server.to_owned(),
ba20987a 481 port,
34aa8e13 482 auth_id.user().clone(),
29077d95 483 password,
bdfa6370
TL
484 )
485 .map_ok({
5030b7ce
DM
486 let server = server.to_string();
487 let prefix = options.prefix.clone();
dd4b42ba 488 let authinfo = auth.clone();
5030b7ce
DM
489
490 move |auth| {
dbd00a57 491 if use_ticket_cache && prefix.is_some() {
70b22b62 492 if let Err(err) = store_ticket_info(
bdfa6370
TL
493 prefix.as_ref().unwrap(),
494 &server,
495 &auth.auth_id.to_string(),
496 &auth.ticket,
497 &auth.token,
70b22b62 498 ) {
73809d55
FE
499 if tty::stdout_isatty() {
500 log::error!("storing login ticket failed: {}", err);
501 }
70b22b62 502 }
5030b7ce 503 }
dd4b42ba
DC
504 *authinfo.write().unwrap() = auth;
505 tokio::spawn(renewal_future);
5030b7ce
DM
506 }
507 });
45cdce06 508
34aa8e13
FG
509 let first_auth = if auth_id.is_token() {
510 // TODO check access here?
511 None
512 } else {
513 Some(BroadcastFuture::new(Box::new(login_future)))
514 };
515
45cdce06 516 Ok(Self {
5a2df000 517 client,
597641fd 518 server: String::from(server),
ba20987a 519 port,
d59dbeca 520 fingerprint: verified_fingerprint,
dd4b42ba
DC
521 auth,
522 ticket_abort,
34aa8e13 523 first_auth,
d59dbeca 524 _options: options,
45cdce06 525 })
597641fd
DM
526 }
527
1a7a0e74 528 /// Login
e240d8be 529 ///
add5861e 530 /// Login is done on demand, so this is only required if you need
e240d8be 531 /// access to authentication data in 'AuthInfo'.
0081903f
DM
532 ///
533 /// Note: tickets a periodially re-newed, so one can use this
534 /// to query changed ticket.
96f5e80a 535 pub async fn login(&self) -> Result<AuthInfo, Error> {
34aa8e13
FG
536 if let Some(future) = &self.first_auth {
537 future.listen().await?;
538 }
539
dd4b42ba
DC
540 let authinfo = self.auth.read().unwrap();
541 Ok(authinfo.clone())
e240d8be
DM
542 }
543
d59dbeca
DM
544 /// Returns the optional fingerprint passed to the new() constructor.
545 pub fn fingerprint(&self) -> Option<String> {
546 (*self.fingerprint.lock().unwrap()).clone()
547 }
548
e7cb4dc5 549 fn get_password(username: &Userid, interactive: bool) -> Result<String, Error> {
56458d97 550 // If we're on a TTY, query the user for a password
d59dbeca 551 if interactive && tty::stdin_isatty() {
99d863d7
DM
552 let msg = format!("Password for \"{}\": ", username);
553 return Ok(String::from_utf8(tty::read_password(&msg)?)?);
56458d97
WB
554 }
555
556 bail!("no password input mechanism available");
557 }
558
d59dbeca 559 fn verify_callback(
065013cc 560 openssl_valid: bool,
56d98ba9
FG
561 ctx: &mut X509StoreContextRef,
562 expected_fingerprint: Option<&String>,
d59dbeca 563 interactive: bool,
065013cc 564 ) -> Result<Option<String>, Error> {
065013cc
FG
565 if openssl_valid {
566 return Ok(None);
567 }
d59dbeca
DM
568
569 let cert = match ctx.current_cert() {
570 Some(cert) => cert,
065013cc 571 None => bail!("context lacks current certificate."),
d59dbeca
DM
572 };
573
574 let depth = ctx.error_depth();
bdfa6370
TL
575 if depth != 0 {
576 bail!("context depth != 0")
577 }
d59dbeca
DM
578
579 let fp = match cert.digest(openssl::hash::MessageDigest::sha256()) {
580 Ok(fp) => fp,
065013cc 581 Err(err) => bail!("failed to calculate certificate FP - {}", err), // should not happen
d59dbeca 582 };
16f6766a 583 let fp_string = hex::encode(fp);
bdfa6370
TL
584 let fp_string = fp_string
585 .as_bytes()
586 .chunks(2)
587 .map(|v| std::str::from_utf8(v).unwrap())
588 .collect::<Vec<&str>>()
589 .join(":");
d59dbeca
DM
590
591 if let Some(expected_fingerprint) = expected_fingerprint {
dda1b4fa
FG
592 let expected_fingerprint = expected_fingerprint.to_lowercase();
593 if expected_fingerprint == fp_string {
065013cc 594 return Ok(Some(fp_string));
d59dbeca 595 } else {
e10fccf5
HL
596 log::warn!("WARNING: certificate fingerprint does not match expected fingerprint!");
597 log::warn!("expected: {}", expected_fingerprint);
d59dbeca
DM
598 }
599 }
600
601 // If we're on a TTY, query the user
602 if interactive && tty::stdin_isatty() {
e10fccf5 603 log::info!("fingerprint: {}", fp_string);
d59dbeca 604 loop {
85f4e834 605 eprint!("Are you sure you want to continue connecting? (y/n): ");
d59dbeca 606 let _ = std::io::stdout().flush();
a595f0fe
WB
607 use std::io::{BufRead, BufReader};
608 let mut line = String::new();
609 match BufReader::new(std::io::stdin()).read_line(&mut line) {
610 Ok(_) => {
611 let trimmed = line.trim();
612 if trimmed == "y" || trimmed == "Y" {
065013cc 613 return Ok(Some(fp_string));
a595f0fe 614 } else if trimmed == "n" || trimmed == "N" {
065013cc 615 bail!("Certificate fingerprint was not confirmed.");
a595f0fe
WB
616 } else {
617 continue;
d59dbeca
DM
618 }
619 }
065013cc 620 Err(err) => bail!("Certificate fingerprint was not confirmed - {}.", err),
d59dbeca
DM
621 }
622 }
623 }
065013cc
FG
624
625 bail!("Certificate fingerprint was not confirmed.");
a6b75513
DM
626 }
627
1a7a0e74 628 pub async fn request(&self, mut req: Request<Body>) -> Result<Value, Error> {
5a2df000 629 let client = self.client.clone();
597641fd 630
bdfa6370 631 let auth = self.login().await?;
34aa8e13 632 if auth.auth_id.is_token() {
bdfa6370
TL
633 let enc_api_token = format!(
634 "PBSAPIToken {}:{}",
635 auth.auth_id,
636 percent_encode(auth.ticket.as_bytes(), DEFAULT_ENCODE_SET)
637 );
638 req.headers_mut().insert(
639 "Authorization",
640 HeaderValue::from_str(&enc_api_token).unwrap(),
641 );
34aa8e13 642 } else {
bdfa6370
TL
643 let enc_ticket = format!(
644 "PBSAuthCookie={}",
645 percent_encode(auth.ticket.as_bytes(), DEFAULT_ENCODE_SET)
646 );
647 req.headers_mut()
648 .insert("Cookie", HeaderValue::from_str(&enc_ticket).unwrap());
649 req.headers_mut().insert(
650 "CSRFPreventionToken",
651 HeaderValue::from_str(&auth.token).unwrap(),
652 );
34aa8e13 653 }
597641fd 654
1a7a0e74 655 Self::api_request(client, req).await
1fdb4c6f
DM
656 }
657
bdfa6370 658 pub async fn get(&self, path: &str, data: Option<Value>) -> Result<Value, Error> {
ba20987a 659 let req = Self::request_builder(&self.server, self.port, "GET", path, data)?;
1a7a0e74 660 self.request(req).await
a6b75513
DM
661 }
662
bdfa6370 663 pub async fn delete(&self, path: &str, data: Option<Value>) -> Result<Value, Error> {
ba20987a 664 let req = Self::request_builder(&self.server, self.port, "DELETE", path, data)?;
1a7a0e74 665 self.request(req).await
a6b75513
DM
666 }
667
bdfa6370 668 pub async fn post(&self, path: &str, data: Option<Value>) -> Result<Value, Error> {
ba20987a 669 let req = Self::request_builder(&self.server, self.port, "POST", path, data)?;
1a7a0e74 670 self.request(req).await
024f11bb
DM
671 }
672
bdfa6370 673 pub async fn put(&self, path: &str, data: Option<Value>) -> Result<Value, Error> {
3c945d73
DC
674 let req = Self::request_builder(&self.server, self.port, "PUT", path, data)?;
675 self.request(req).await
676 }
677
bdfa6370 678 pub async fn download(&self, path: &str, output: &mut (dyn Write + Send)) -> Result<(), Error> {
ba20987a 679 let mut req = Self::request_builder(&self.server, self.port, "GET", path, None)?;
024f11bb 680
5a2df000 681 let client = self.client.clone();
1fdb4c6f 682
1a7a0e74 683 let auth = self.login().await?;
81da38c1 684
bdfa6370
TL
685 let enc_ticket = format!(
686 "PBSAuthCookie={}",
687 percent_encode(auth.ticket.as_bytes(), DEFAULT_ENCODE_SET)
688 );
689 req.headers_mut()
690 .insert("Cookie", HeaderValue::from_str(&enc_ticket).unwrap());
6f62c924 691
bdfa6370 692 let resp = tokio::time::timeout(HTTP_TIMEOUT, client.request(req))
d148958b
FG
693 .await
694 .map_err(|_| format_err!("http download request timed out"))??;
1a7a0e74
DM
695 let status = resp.status();
696 if !status.is_success() {
697 HttpClient::api_response(resp)
698 .map(|_| Err(format_err!("unknown error")))
699 .await?
700 } else {
701 resp.into_body()
5a2df000 702 .map_err(Error::from)
1a7a0e74
DM
703 .try_fold(output, move |acc, chunk| async move {
704 acc.write_all(&chunk)?;
705 Ok::<_, Error>(acc)
5a2df000 706 })
1a7a0e74
DM
707 .await?;
708 }
709 Ok(())
6f62c924
DM
710 }
711
1a7a0e74 712 pub async fn upload(
d4877712 713 &self,
04512d30
DM
714 content_type: &str,
715 body: Body,
716 path: &str,
717 data: Option<Value>,
1a7a0e74 718 ) -> Result<Value, Error> {
a2daecc2 719 let query = match data {
9eb78407 720 Some(data) => Some(json_object_to_query(data)?),
a2daecc2
DM
721 None => None,
722 };
723 let url = build_uri(&self.server, self.port, path, query)?;
81da38c1 724
5a2df000 725 let req = Request::builder()
81da38c1
DM
726 .method("POST")
727 .uri(url)
728 .header("User-Agent", "proxmox-backup-client/1.0")
5a2df000 729 .header("Content-Type", content_type)
bdfa6370
TL
730 .body(body)
731 .unwrap();
81da38c1 732
1a7a0e74 733 self.request(req).await
1fdb4c6f
DM
734 }
735
1a7a0e74 736 pub async fn start_h2_connection(
fb047083
DM
737 &self,
738 mut req: Request<Body>,
739 protocol_name: String,
dc089345 740 ) -> Result<(H2Client, futures::future::AbortHandle), Error> {
cf639a47 741 let client = self.client.clone();
bdfa6370 742 let auth = self.login().await?;
34aa8e13
FG
743
744 if auth.auth_id.is_token() {
bdfa6370
TL
745 let enc_api_token = format!(
746 "PBSAPIToken {}:{}",
747 auth.auth_id,
748 percent_encode(auth.ticket.as_bytes(), DEFAULT_ENCODE_SET)
749 );
750 req.headers_mut().insert(
751 "Authorization",
752 HeaderValue::from_str(&enc_api_token).unwrap(),
753 );
34aa8e13 754 } else {
bdfa6370
TL
755 let enc_ticket = format!(
756 "PBSAuthCookie={}",
757 percent_encode(auth.ticket.as_bytes(), DEFAULT_ENCODE_SET)
758 );
759 req.headers_mut()
760 .insert("Cookie", HeaderValue::from_str(&enc_ticket).unwrap());
761 req.headers_mut().insert(
762 "CSRFPreventionToken",
763 HeaderValue::from_str(&auth.token).unwrap(),
764 );
34aa8e13 765 }
cf639a47 766
722b7bf7
MC
767 req.headers_mut()
768 .insert("Connection", HeaderValue::from_str("upgrade").unwrap());
bdfa6370
TL
769 req.headers_mut()
770 .insert("UPGRADE", HeaderValue::from_str(&protocol_name).unwrap());
cf639a47 771
bdfa6370 772 let resp = tokio::time::timeout(HTTP_TIMEOUT, client.request(req))
d148958b
FG
773 .await
774 .map_err(|_| format_err!("http upgrade request timed out"))??;
1a7a0e74 775 let status = resp.status();
cf639a47 776
1a7a0e74 777 if status != http::StatusCode::SWITCHING_PROTOCOLS {
ca611955
DM
778 Self::api_response(resp).await?;
779 bail!("unknown error");
1a7a0e74
DM
780 }
781
89e9134a 782 let upgraded = hyper::upgrade::on(resp).await?;
1a7a0e74
DM
783
784 let max_window_size = (1 << 31) - 2;
785
786 let (h2, connection) = h2::client::Builder::new()
787 .initial_connection_window_size(max_window_size)
788 .initial_window_size(max_window_size)
bdfa6370 789 .max_frame_size(4 * 1024 * 1024)
1a7a0e74
DM
790 .handshake(upgraded)
791 .await?;
792
e10fccf5 793 let connection = connection.map_err(|_| log::error!("HTTP/2.0 connection failed"));
1a7a0e74 794
dc089345 795 let (connection, abort) = futures::future::abortable(connection);
1a7a0e74
DM
796 // A cancellable future returns an Option which is None when cancelled and
797 // Some when it finished instead, since we don't care about the return type we
798 // need to map it away:
799 let connection = connection.map(|_| ());
800
801 // Spawn a new task to drive the connection state
db0cb9ce 802 tokio::spawn(connection);
1a7a0e74
DM
803
804 // Wait until the `SendRequest` handle has available capacity.
805 let c = h2.ready().await?;
dc089345 806 Ok((H2Client::new(c), abort))
cf639a47
DM
807 }
808
9d35dbbb 809 async fn credentials(
1434f4f8 810 client: Client<HttpsConnector>,
45cdce06 811 server: String,
ba20987a 812 port: u16,
e7cb4dc5 813 username: Userid,
45cdce06 814 password: String,
9d35dbbb
DM
815 ) -> Result<AuthInfo, Error> {
816 let data = json!({ "username": username, "password": password });
bdfa6370
TL
817 let req = Self::request_builder(
818 &server,
819 port,
820 "POST",
821 "/api2/json/access/ticket",
822 Some(data),
823 )?;
9d35dbbb
DM
824 let cred = Self::api_request(client, req).await?;
825 let auth = AuthInfo {
34aa8e13 826 auth_id: cred["data"]["username"].as_str().unwrap().parse()?,
9d35dbbb 827 ticket: cred["data"]["ticket"].as_str().unwrap().to_owned(),
bdfa6370
TL
828 token: cred["data"]["CSRFPreventionToken"]
829 .as_str()
830 .unwrap()
831 .to_owned(),
9d35dbbb
DM
832 };
833
9d35dbbb 834 Ok(auth)
ba3a60b2
DM
835 }
836
a6782ca1 837 async fn api_response(response: Response<Body>) -> Result<Value, Error> {
d2c48afc 838 let status = response.status();
db0cb9ce 839 let data = hyper::body::to_bytes(response.into_body()).await?;
a6782ca1
WB
840
841 let text = String::from_utf8(data.to_vec()).unwrap();
842 if status.is_success() {
11377a47
DM
843 if text.is_empty() {
844 Ok(Value::Null)
845 } else {
a6782ca1
WB
846 let value: Value = serde_json::from_str(&text)?;
847 Ok(value)
a6782ca1
WB
848 }
849 } else {
91f5594c 850 Err(Error::from(HttpError::new(status, text)))
a6782ca1 851 }
d2c48afc
DM
852 }
853
1a7a0e74 854 async fn api_request(
1434f4f8 855 client: Client<HttpsConnector>,
bdfa6370 856 req: Request<Body>,
1a7a0e74 857 ) -> Result<Value, Error> {
d148958b 858 Self::api_response(
bdfa6370 859 tokio::time::timeout(HTTP_TIMEOUT, client.request(req))
d148958b 860 .await
bdfa6370
TL
861 .map_err(|_| format_err!("http request timed out"))??,
862 )
863 .await
0dffe3f9
DM
864 }
865
9e490a74
DM
866 // Read-only access to server property
867 pub fn server(&self) -> &str {
868 &self.server
869 }
870
ba20987a
DC
871 pub fn port(&self) -> u16 {
872 self.port
873 }
874
bdfa6370
TL
875 pub fn request_builder(
876 server: &str,
877 port: u16,
878 method: &str,
879 path: &str,
880 data: Option<Value>,
881 ) -> Result<Request<Body>, Error> {
5a2df000
DM
882 if let Some(data) = data {
883 if method == "POST" {
a2daecc2 884 let url = build_uri(server, port, path, None)?;
5a2df000
DM
885 let request = Request::builder()
886 .method(method)
887 .uri(url)
888 .header("User-Agent", "proxmox-backup-client/1.0")
889 .header(hyper::header::CONTENT_TYPE, "application/json")
890 .body(Body::from(data.to_string()))?;
a2daecc2 891 Ok(request)
5a2df000 892 } else {
9eb78407 893 let query = json_object_to_query(data)?;
a2daecc2 894 let url = build_uri(server, port, path, Some(query))?;
9e391bb7
DM
895 let request = Request::builder()
896 .method(method)
897 .uri(url)
898 .header("User-Agent", "proxmox-backup-client/1.0")
bdfa6370
TL
899 .header(
900 hyper::header::CONTENT_TYPE,
901 "application/x-www-form-urlencoded",
902 )
9e391bb7 903 .body(Body::empty())?;
a2daecc2 904 Ok(request)
5a2df000 905 }
a2daecc2
DM
906 } else {
907 let url = build_uri(server, port, path, None)?;
908 let request = Request::builder()
909 .method(method)
910 .uri(url)
911 .header("User-Agent", "proxmox-backup-client/1.0")
bdfa6370
TL
912 .header(
913 hyper::header::CONTENT_TYPE,
914 "application/x-www-form-urlencoded",
915 )
a2daecc2 916 .body(Body::empty())?;
1fdb4c6f 917
a2daecc2
DM
918 Ok(request)
919 }
597641fd
DM
920 }
921}
b57cb264 922
dd4b42ba
DC
923impl Drop for HttpClient {
924 fn drop(&mut self) {
925 self.ticket_abort.abort();
926 }
927}
928
9af37c8f
DM
929#[derive(Clone)]
930pub struct H2Client {
931 h2: h2::client::SendRequest<bytes::Bytes>,
932}
933
934impl H2Client {
9af37c8f
DM
935 pub fn new(h2: h2::client::SendRequest<bytes::Bytes>) -> Self {
936 Self { h2 }
937 }
938
bdfa6370 939 pub async fn get(&self, path: &str, param: Option<Value>) -> Result<Value, Error> {
792a70b9 940 let req = Self::request_builder("localhost", "GET", path, param, None).unwrap();
2a1e6d7d 941 self.request(req).await
9af37c8f
DM
942 }
943
bdfa6370 944 pub async fn put(&self, path: &str, param: Option<Value>) -> Result<Value, Error> {
792a70b9 945 let req = Self::request_builder("localhost", "PUT", path, param, None).unwrap();
2a1e6d7d 946 self.request(req).await
9af37c8f
DM
947 }
948
bdfa6370 949 pub async fn post(&self, path: &str, param: Option<Value>) -> Result<Value, Error> {
792a70b9 950 let req = Self::request_builder("localhost", "POST", path, param, None).unwrap();
2a1e6d7d 951 self.request(req).await
9af37c8f
DM
952 }
953
d4a085e5 954 pub async fn download<W: Write + Send>(
a6782ca1
WB
955 &self,
956 path: &str,
957 param: Option<Value>,
2a1e6d7d 958 mut output: W,
3d571d55 959 ) -> Result<(), Error> {
792a70b9 960 let request = Self::request_builder("localhost", "GET", path, param, None).unwrap();
dd066d28 961
2a1e6d7d 962 let response_future = self.send_request(request, None).await?;
984a7c35 963
2a1e6d7d
DM
964 let resp = response_future.await?;
965
966 let status = resp.status();
967 if !status.is_success() {
44f59dc7
DM
968 H2Client::h2api_response(resp).await?; // raise error
969 unreachable!();
2a1e6d7d
DM
970 }
971
972 let mut body = resp.into_body();
db0cb9ce
WB
973 while let Some(chunk) = body.data().await {
974 let chunk = chunk?;
975 body.flow_control().release_capacity(chunk.len())?;
2a1e6d7d
DM
976 output.write_all(&chunk)?;
977 }
978
3d571d55 979 Ok(())
dd066d28
DM
980 }
981
2a1e6d7d 982 pub async fn upload(
a6782ca1 983 &self,
f011dba0 984 method: &str, // POST or PUT
a6782ca1
WB
985 path: &str,
986 param: Option<Value>,
792a70b9 987 content_type: &str,
a6782ca1 988 data: Vec<u8>,
2a1e6d7d 989 ) -> Result<Value, Error> {
bdfa6370
TL
990 let request =
991 Self::request_builder("localhost", method, path, param, Some(content_type)).unwrap();
9af37c8f 992
2a1e6d7d
DM
993 let mut send_request = self.h2.clone().ready().await?;
994
995 let (response, stream) = send_request.send_request(request, false).unwrap();
2a05048b
DM
996
997 PipeToSendStream::new(bytes::Bytes::from(data), stream).await?;
998
999 response
1000 .map_err(Error::from)
1001 .and_then(Self::h2api_response)
2a1e6d7d 1002 .await
9af37c8f 1003 }
adec8ea2 1004
bdfa6370 1005 async fn request(&self, request: Request<()>) -> Result<Value, Error> {
9af37c8f 1006 self.send_request(request, None)
bdfa6370 1007 .and_then(move |response| response.map_err(Error::from).and_then(Self::h2api_response))
2a1e6d7d 1008 .await
82ab7230
DM
1009 }
1010
cf9271e2 1011 pub fn send_request(
9af37c8f 1012 &self,
82ab7230
DM
1013 request: Request<()>,
1014 data: Option<bytes::Bytes>,
a6782ca1 1015 ) -> impl Future<Output = Result<h2::client::ResponseFuture, Error>> {
bdfa6370
TL
1016 self.h2
1017 .clone()
10130cf4
DM
1018 .ready()
1019 .map_err(Error::from)
2a05048b 1020 .and_then(move |mut send_request| async move {
82ab7230
DM
1021 if let Some(data) = data {
1022 let (response, stream) = send_request.send_request(request, false).unwrap();
2a05048b
DM
1023 PipeToSendStream::new(data, stream).await?;
1024 Ok(response)
82ab7230
DM
1025 } else {
1026 let (response, _stream) = send_request.send_request(request, true).unwrap();
2a05048b 1027 Ok(response)
82ab7230 1028 }
b57cb264
DM
1029 })
1030 }
1031
bdfa6370 1032 pub async fn h2api_response(response: Response<h2::RecvStream>) -> Result<Value, Error> {
b57cb264
DM
1033 let status = response.status();
1034
1035 let (_head, mut body) = response.into_parts();
1036
9edd3bf1 1037 let mut data = Vec::new();
db0cb9ce
WB
1038 while let Some(chunk) = body.data().await {
1039 let chunk = chunk?;
1040 // Whenever data is received, the caller is responsible for
1041 // releasing capacity back to the server once it has freed
1042 // the data from memory.
9edd3bf1 1043 // Let the server send more data.
db0cb9ce 1044 body.flow_control().release_capacity(chunk.len())?;
9edd3bf1
DM
1045 data.extend(chunk);
1046 }
1047
1048 let text = String::from_utf8(data.to_vec()).unwrap();
1049 if status.is_success() {
11377a47
DM
1050 if text.is_empty() {
1051 Ok(Value::Null)
1052 } else {
9edd3bf1
DM
1053 let mut value: Value = serde_json::from_str(&text)?;
1054 if let Some(map) = value.as_object_mut() {
1055 if let Some(data) = map.remove("data") {
1056 return Ok(data);
b57cb264 1057 }
b57cb264 1058 }
9edd3bf1 1059 bail!("got result without data property");
9edd3bf1
DM
1060 }
1061 } else {
91f5594c 1062 Err(Error::from(HttpError::new(status, text)))
9edd3bf1 1063 }
b57cb264
DM
1064 }
1065
eb2bdd1b 1066 // Note: We always encode parameters with the url
792a70b9
DM
1067 pub fn request_builder(
1068 server: &str,
1069 method: &str,
1070 path: &str,
1071 param: Option<Value>,
1072 content_type: Option<&str>,
1073 ) -> Result<Request<()>, Error> {
b57cb264 1074 let path = path.trim_matches('/');
b57cb264 1075
792a70b9 1076 let content_type = content_type.unwrap_or("application/x-www-form-urlencoded");
a2daecc2
DM
1077 let query = match param {
1078 Some(param) => {
9eb78407 1079 let query = json_object_to_query(param)?;
a2daecc2
DM
1080 // We detected problem with hyper around 6000 characters - so we try to keep on the safe side
1081 if query.len() > 4096 {
bdfa6370
TL
1082 bail!(
1083 "h2 query data too large ({} bytes) - please encode data inside body",
1084 query.len()
1085 );
a2daecc2
DM
1086 }
1087 Some(query)
1088 }
1089 None => None,
1090 };
792a70b9 1091
a2daecc2
DM
1092 let url = build_uri(server, 8007, path, query)?;
1093 let request = Request::builder()
1094 .method(method)
1095 .uri(url)
1096 .header("User-Agent", "proxmox-backup-client/1.0")
1097 .header(hyper::header::CONTENT_TYPE, content_type)
1098 .body(())?;
1099 Ok(request)
b57cb264
DM
1100 }
1101}