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