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