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