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