]> git.proxmox.com Git - proxmox-backup.git/blob - src/client/http_client.rs
client: improve fingerprint variable names
[proxmox-backup.git] / src / client / http_client.rs
1 use std::io::Write;
2 use std::sync::{Arc, Mutex, RwLock};
3 use std::time::Duration;
4
5 use anyhow::{bail, format_err, Error};
6 use futures::*;
7 use http::Uri;
8 use http::header::HeaderValue;
9 use http::{Request, Response};
10 use hyper::Body;
11 use hyper::client::{Client, HttpConnector};
12 use openssl::{ssl::{SslConnector, SslMethod}, x509::X509StoreContextRef};
13 use serde_json::{json, Value};
14 use percent_encoding::percent_encode;
15 use xdg::BaseDirectories;
16
17 use proxmox::{
18 api::error::HttpError,
19 sys::linux::tty,
20 tools::fs::{file_get_json, replace_file, CreateOptions},
21 };
22
23 use super::pipe_to_stream::PipeToSendStream;
24 use crate::api2::types::{Authid, Userid};
25 use crate::tools::{
26 self,
27 BroadcastFuture,
28 DEFAULT_ENCODE_SET,
29 http::{
30 build_authority,
31 HttpsConnector,
32 },
33 };
34
35 /// Timeout used for several HTTP operations that are expected to finish quickly but may block in
36 /// certain error conditions. Keep it generous, to avoid false-positive under high load.
37 const HTTP_TIMEOUT: Duration = Duration::from_secs(2 * 60);
38
39 #[derive(Clone)]
40 pub struct AuthInfo {
41 pub auth_id: Authid,
42 pub ticket: String,
43 pub token: String,
44 }
45
46 pub struct HttpClientOptions {
47 prefix: Option<String>,
48 password: Option<String>,
49 fingerprint: Option<String>,
50 interactive: bool,
51 ticket_cache: bool,
52 fingerprint_cache: bool,
53 verify_cert: bool,
54 }
55
56 impl HttpClientOptions {
57
58 pub fn new_interactive(password: Option<String>, fingerprint: Option<String>) -> Self {
59 Self {
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()
75 }
76 }
77
78 pub fn prefix(mut self, prefix: Option<String>) -> Self {
79 self.prefix = prefix;
80 self
81 }
82
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
103 pub fn fingerprint_cache(mut self, fingerprint_cache: bool) -> Self {
104 self.fingerprint_cache = fingerprint_cache;
105 self
106 }
107
108 pub fn verify_cert(mut self, verify_cert: bool) -> Self {
109 self.verify_cert = verify_cert;
110 self
111 }
112 }
113
114 impl 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
128 /// HTTP(S) API client
129 pub struct HttpClient {
130 client: Client<HttpsConnector>,
131 server: String,
132 port: u16,
133 fingerprint: Arc<Mutex<Option<String>>>,
134 first_auth: Option<BroadcastFuture<()>>,
135 auth: Arc<RwLock<AuthInfo>>,
136 ticket_abort: futures::future::AbortHandle,
137 _options: HttpClientOptions,
138 }
139
140 /// Delete stored ticket data (logout)
141 pub fn delete_ticket_info(prefix: &str, server: &str, username: &Userid) -> Result<(), Error> {
142
143 let base = BaseDirectories::with_prefix(prefix)?;
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() {
153 map.remove(username.as_str());
154 }
155
156 replace_file(path, data.to_string().as_bytes(), CreateOptions::new().perm(mode))?;
157
158 Ok(())
159 }
160
161 fn store_fingerprint(prefix: &str, server: &str, fingerprint: &str) -> Result<(), Error> {
162
163 let base = BaseDirectories::with_prefix(prefix)?;
164
165 // usually ~/.config/<prefix>/fingerprints
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 {
184 if items[0] == server {
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
203 fn load_fingerprint(prefix: &str, server: &str) -> Option<String> {
204
205 let base = BaseDirectories::with_prefix(prefix).ok()?;
206
207 // usually ~/.config/<prefix>/fingerprints
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();
214 if items.len() == 2 && items[0] == server {
215 return Some(items[1].clone());
216 }
217 }
218
219 None
220 }
221
222 fn store_ticket_info(prefix: &str, server: &str, username: &str, ticket: &str, token: &str) -> Result<(), Error> {
223
224 let base = BaseDirectories::with_prefix(prefix)?;
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
231 let mut data = file_get_json(&path, Some(json!({})))?;
232
233 let now = proxmox::tools::time::epoch_i64();
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) {
243 for (user, uinfo) in info.as_object().unwrap_or(&empty) {
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();
248 }
249 }
250 }
251 }
252
253 replace_file(path, new_data.to_string().as_bytes(), CreateOptions::new().perm(mode))?;
254
255 Ok(())
256 }
257
258 fn load_ticket_info(prefix: &str, server: &str, userid: &Userid) -> Option<(String, String)> {
259 let base = BaseDirectories::with_prefix(prefix).ok()?;
260
261 // usually /run/user/<uid>/...
262 let path = base.place_runtime_file("tickets").ok()?;
263 let data = file_get_json(&path, None).ok()?;
264 let now = proxmox::tools::time::epoch_i64();
265 let ticket_lifetime = tools::ticket::TICKET_LIFETIME - 60;
266 let uinfo = data[server][userid.as_str()].as_object()?;
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
276 }
277 }
278
279 fn build_uri(server: &str, port: u16, path: &str, query: Option<String>) -> Result<Uri, Error> {
280 Uri::builder()
281 .scheme("https")
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))
289 }
290
291 impl HttpClient {
292 pub fn new(
293 server: &str,
294 port: u16,
295 auth_id: &Authid,
296 mut options: HttpClientOptions,
297 ) -> Result<Self, Error> {
298
299 let verified_fingerprint = Arc::new(Mutex::new(None));
300
301 let mut expected_fingerprint = options.fingerprint.take();
302
303 if expected_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() {
307 expected_fingerprint = load_fingerprint(options.prefix.as_ref().unwrap(), server);
308 }
309
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, expected_fingerprint.as_ref(), 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
337 let mut httpc = HttpConnector::new();
338 httpc.set_nodelay(true); // important for h2 download performance!
339 httpc.enforce_http(false); // we want https...
340
341 httpc.set_connect_timeout(Some(std::time::Duration::new(10, 0)));
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);
348
349 let password = options.password.take();
350 let use_ticket_cache = options.ticket_cache && options.prefix.is_some();
351
352 let password = if let Some(password) = password {
353 password
354 } else {
355 let userid = if auth_id.is_token() {
356 bail!("API token secret must be provided!");
357 } else {
358 auth_id.user()
359 };
360 let mut ticket_info = None;
361 if use_ticket_cache {
362 ticket_info = load_ticket_info(options.prefix.as_ref().unwrap(), server, userid);
363 }
364 if let Some((ticket, _token)) = ticket_info {
365 ticket
366 } else {
367 Self::get_password(userid, options.interactive)?
368 }
369 };
370
371 let auth = Arc::new(RwLock::new(AuthInfo {
372 auth_id: auth_id.clone(),
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 {
384 tokio::time::sleep(Duration::new(60*15, 0)).await; // 15 minutes
385 let (auth_id, ticket) = {
386 let authinfo = auth2.read().unwrap().clone();
387 (authinfo.auth_id, authinfo.ticket)
388 };
389 match Self::credentials(client2.clone(), server2.clone(), port, auth_id.user().clone(), ticket).await {
390 Ok(auth) => {
391 if use_ticket_cache && prefix2.is_some() {
392 let _ = store_ticket_info(prefix2.as_ref().unwrap(), &server2, &auth.auth_id.to_string(), &auth.ticket, &auth.token);
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
406 let login_future = Self::credentials(
407 client.clone(),
408 server.to_owned(),
409 port,
410 auth_id.user().clone(),
411 password,
412 ).map_ok({
413 let server = server.to_string();
414 let prefix = options.prefix.clone();
415 let authinfo = auth.clone();
416
417 move |auth| {
418 if use_ticket_cache && prefix.is_some() {
419 let _ = store_ticket_info(prefix.as_ref().unwrap(), &server, &auth.auth_id.to_string(), &auth.ticket, &auth.token);
420 }
421 *authinfo.write().unwrap() = auth;
422 tokio::spawn(renewal_future);
423 }
424 });
425
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
433 Ok(Self {
434 client,
435 server: String::from(server),
436 port,
437 fingerprint: verified_fingerprint,
438 auth,
439 ticket_abort,
440 first_auth,
441 _options: options,
442 })
443 }
444
445 /// Login
446 ///
447 /// Login is done on demand, so this is only required if you need
448 /// access to authentication data in 'AuthInfo'.
449 ///
450 /// Note: tickets a periodially re-newed, so one can use this
451 /// to query changed ticket.
452 pub async fn login(&self) -> Result<AuthInfo, Error> {
453 if let Some(future) = &self.first_auth {
454 future.listen().await?;
455 }
456
457 let authinfo = self.auth.read().unwrap();
458 Ok(authinfo.clone())
459 }
460
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
466 fn get_password(username: &Userid, interactive: bool) -> Result<String, Error> {
467 // If we're on a TTY, query the user for a password
468 if interactive && tty::stdin_isatty() {
469 let msg = format!("Password for \"{}\": ", username);
470 return Ok(String::from_utf8(tty::read_password(&msg)?)?);
471 }
472
473 bail!("no password input mechanism available");
474 }
475
476 fn verify_callback(
477 valid: bool,
478 ctx: &mut X509StoreContextRef,
479 expected_fingerprint: Option<&String>,
480 interactive: bool,
481 ) -> (bool, Option<String>) {
482 if valid { return (true, None); }
483
484 let cert = match ctx.current_cert() {
485 Some(cert) => cert,
486 None => return (false, None),
487 };
488
489 let depth = ctx.error_depth();
490 if depth != 0 { return (false, None); }
491
492 let fp = match cert.digest(openssl::hash::MessageDigest::sha256()) {
493 Ok(fp) => fp,
494 Err(_) => return (false, None), // should not happen
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 {
501 let expected_fingerprint = expected_fingerprint.to_lowercase();
502 if expected_fingerprint == fp_string {
503 return (true, Some(fp_string));
504 } else {
505 eprintln!("WARNING: certificate fingerprint does not match expected fingerprint!");
506 eprintln!("expected: {}", expected_fingerprint);
507 }
508 }
509
510 // If we're on a TTY, query the user
511 if interactive && tty::stdin_isatty() {
512 println!("fingerprint: {}", fp_string);
513 loop {
514 print!("Are you sure you want to continue connecting? (y/n): ");
515 let _ = std::io::stdout().flush();
516 use std::io::{BufRead, BufReader};
517 let mut line = String::new();
518 match BufReader::new(std::io::stdin()).read_line(&mut line) {
519 Ok(_) => {
520 let trimmed = line.trim();
521 if trimmed == "y" || trimmed == "Y" {
522 return (true, Some(fp_string));
523 } else if trimmed == "n" || trimmed == "N" {
524 return (false, None);
525 } else {
526 continue;
527 }
528 }
529 Err(_) => return (false, None),
530 }
531 }
532 }
533 (false, None)
534 }
535
536 pub async fn request(&self, mut req: Request<Body>) -> Result<Value, Error> {
537
538 let client = self.client.clone();
539
540 let auth = self.login().await?;
541 if auth.auth_id.is_token() {
542 let enc_api_token = format!("PBSAPIToken {}:{}", auth.auth_id, percent_encode(auth.ticket.as_bytes(), DEFAULT_ENCODE_SET));
543 req.headers_mut().insert("Authorization", HeaderValue::from_str(&enc_api_token).unwrap());
544 } else {
545 let enc_ticket = format!("PBSAuthCookie={}", percent_encode(auth.ticket.as_bytes(), DEFAULT_ENCODE_SET));
546 req.headers_mut().insert("Cookie", HeaderValue::from_str(&enc_ticket).unwrap());
547 req.headers_mut().insert("CSRFPreventionToken", HeaderValue::from_str(&auth.token).unwrap());
548 }
549
550 Self::api_request(client, req).await
551 }
552
553 pub async fn get(
554 &self,
555 path: &str,
556 data: Option<Value>,
557 ) -> Result<Value, Error> {
558 let req = Self::request_builder(&self.server, self.port, "GET", path, data)?;
559 self.request(req).await
560 }
561
562 pub async fn delete(
563 &mut self,
564 path: &str,
565 data: Option<Value>,
566 ) -> Result<Value, Error> {
567 let req = Self::request_builder(&self.server, self.port, "DELETE", path, data)?;
568 self.request(req).await
569 }
570
571 pub async fn post(
572 &mut self,
573 path: &str,
574 data: Option<Value>,
575 ) -> Result<Value, Error> {
576 let req = Self::request_builder(&self.server, self.port, "POST", path, data)?;
577 self.request(req).await
578 }
579
580 pub async fn put(
581 &mut self,
582 path: &str,
583 data: Option<Value>,
584 ) -> Result<Value, Error> {
585 let req = Self::request_builder(&self.server, self.port, "PUT", path, data)?;
586 self.request(req).await
587 }
588
589 pub async fn download(
590 &mut self,
591 path: &str,
592 output: &mut (dyn Write + Send),
593 ) -> Result<(), Error> {
594 let mut req = Self::request_builder(&self.server, self.port, "GET", path, None)?;
595
596 let client = self.client.clone();
597
598 let auth = self.login().await?;
599
600 let enc_ticket = format!("PBSAuthCookie={}", percent_encode(auth.ticket.as_bytes(), DEFAULT_ENCODE_SET));
601 req.headers_mut().insert("Cookie", HeaderValue::from_str(&enc_ticket).unwrap());
602
603 let resp = tokio::time::timeout(
604 HTTP_TIMEOUT,
605 client.request(req)
606 )
607 .await
608 .map_err(|_| format_err!("http download request timed out"))??;
609 let status = resp.status();
610 if !status.is_success() {
611 HttpClient::api_response(resp)
612 .map(|_| Err(format_err!("unknown error")))
613 .await?
614 } else {
615 resp.into_body()
616 .map_err(Error::from)
617 .try_fold(output, move |acc, chunk| async move {
618 acc.write_all(&chunk)?;
619 Ok::<_, Error>(acc)
620 })
621 .await?;
622 }
623 Ok(())
624 }
625
626 pub async fn upload(
627 &mut self,
628 content_type: &str,
629 body: Body,
630 path: &str,
631 data: Option<Value>,
632 ) -> Result<Value, Error> {
633
634 let query = match data {
635 Some(data) => Some(tools::json_object_to_query(data)?),
636 None => None,
637 };
638 let url = build_uri(&self.server, self.port, path, query)?;
639
640 let req = Request::builder()
641 .method("POST")
642 .uri(url)
643 .header("User-Agent", "proxmox-backup-client/1.0")
644 .header("Content-Type", content_type)
645 .body(body).unwrap();
646
647 self.request(req).await
648 }
649
650 pub async fn start_h2_connection(
651 &self,
652 mut req: Request<Body>,
653 protocol_name: String,
654 ) -> Result<(H2Client, futures::future::AbortHandle), Error> {
655
656 let client = self.client.clone();
657 let auth = self.login().await?;
658
659 if auth.auth_id.is_token() {
660 let enc_api_token = format!("PBSAPIToken {}:{}", auth.auth_id, percent_encode(auth.ticket.as_bytes(), DEFAULT_ENCODE_SET));
661 req.headers_mut().insert("Authorization", HeaderValue::from_str(&enc_api_token).unwrap());
662 } else {
663 let enc_ticket = format!("PBSAuthCookie={}", percent_encode(auth.ticket.as_bytes(), DEFAULT_ENCODE_SET));
664 req.headers_mut().insert("Cookie", HeaderValue::from_str(&enc_ticket).unwrap());
665 req.headers_mut().insert("CSRFPreventionToken", HeaderValue::from_str(&auth.token).unwrap());
666 }
667
668 req.headers_mut().insert("UPGRADE", HeaderValue::from_str(&protocol_name).unwrap());
669
670 let resp = tokio::time::timeout(
671 HTTP_TIMEOUT,
672 client.request(req)
673 )
674 .await
675 .map_err(|_| format_err!("http upgrade request timed out"))??;
676 let status = resp.status();
677
678 if status != http::StatusCode::SWITCHING_PROTOCOLS {
679 Self::api_response(resp).await?;
680 bail!("unknown error");
681 }
682
683 let upgraded = hyper::upgrade::on(resp).await?;
684
685 let max_window_size = (1 << 31) - 2;
686
687 let (h2, connection) = h2::client::Builder::new()
688 .initial_connection_window_size(max_window_size)
689 .initial_window_size(max_window_size)
690 .max_frame_size(4*1024*1024)
691 .handshake(upgraded)
692 .await?;
693
694 let connection = connection
695 .map_err(|_| eprintln!("HTTP/2.0 connection failed"));
696
697 let (connection, abort) = futures::future::abortable(connection);
698 // A cancellable future returns an Option which is None when cancelled and
699 // Some when it finished instead, since we don't care about the return type we
700 // need to map it away:
701 let connection = connection.map(|_| ());
702
703 // Spawn a new task to drive the connection state
704 tokio::spawn(connection);
705
706 // Wait until the `SendRequest` handle has available capacity.
707 let c = h2.ready().await?;
708 Ok((H2Client::new(c), abort))
709 }
710
711 async fn credentials(
712 client: Client<HttpsConnector>,
713 server: String,
714 port: u16,
715 username: Userid,
716 password: String,
717 ) -> Result<AuthInfo, Error> {
718 let data = json!({ "username": username, "password": password });
719 let req = Self::request_builder(&server, port, "POST", "/api2/json/access/ticket", Some(data))?;
720 let cred = Self::api_request(client, req).await?;
721 let auth = AuthInfo {
722 auth_id: cred["data"]["username"].as_str().unwrap().parse()?,
723 ticket: cred["data"]["ticket"].as_str().unwrap().to_owned(),
724 token: cred["data"]["CSRFPreventionToken"].as_str().unwrap().to_owned(),
725 };
726
727 Ok(auth)
728 }
729
730 async fn api_response(response: Response<Body>) -> Result<Value, Error> {
731 let status = response.status();
732 let data = hyper::body::to_bytes(response.into_body()).await?;
733
734 let text = String::from_utf8(data.to_vec()).unwrap();
735 if status.is_success() {
736 if text.is_empty() {
737 Ok(Value::Null)
738 } else {
739 let value: Value = serde_json::from_str(&text)?;
740 Ok(value)
741 }
742 } else {
743 Err(Error::from(HttpError::new(status, text)))
744 }
745 }
746
747 async fn api_request(
748 client: Client<HttpsConnector>,
749 req: Request<Body>
750 ) -> Result<Value, Error> {
751
752 Self::api_response(
753 tokio::time::timeout(
754 HTTP_TIMEOUT,
755 client.request(req)
756 )
757 .await
758 .map_err(|_| format_err!("http request timed out"))??
759 ).await
760 }
761
762 // Read-only access to server property
763 pub fn server(&self) -> &str {
764 &self.server
765 }
766
767 pub fn port(&self) -> u16 {
768 self.port
769 }
770
771 pub fn request_builder(server: &str, port: u16, method: &str, path: &str, data: Option<Value>) -> Result<Request<Body>, Error> {
772 if let Some(data) = data {
773 if method == "POST" {
774 let url = build_uri(server, port, path, None)?;
775 let request = Request::builder()
776 .method(method)
777 .uri(url)
778 .header("User-Agent", "proxmox-backup-client/1.0")
779 .header(hyper::header::CONTENT_TYPE, "application/json")
780 .body(Body::from(data.to_string()))?;
781 Ok(request)
782 } else {
783 let query = tools::json_object_to_query(data)?;
784 let url = build_uri(server, port, path, Some(query))?;
785 let request = Request::builder()
786 .method(method)
787 .uri(url)
788 .header("User-Agent", "proxmox-backup-client/1.0")
789 .header(hyper::header::CONTENT_TYPE, "application/x-www-form-urlencoded")
790 .body(Body::empty())?;
791 Ok(request)
792 }
793 } else {
794 let url = build_uri(server, port, path, None)?;
795 let request = Request::builder()
796 .method(method)
797 .uri(url)
798 .header("User-Agent", "proxmox-backup-client/1.0")
799 .header(hyper::header::CONTENT_TYPE, "application/x-www-form-urlencoded")
800 .body(Body::empty())?;
801
802 Ok(request)
803 }
804 }
805 }
806
807 impl Drop for HttpClient {
808 fn drop(&mut self) {
809 self.ticket_abort.abort();
810 }
811 }
812
813
814 #[derive(Clone)]
815 pub struct H2Client {
816 h2: h2::client::SendRequest<bytes::Bytes>,
817 }
818
819 impl H2Client {
820
821 pub fn new(h2: h2::client::SendRequest<bytes::Bytes>) -> Self {
822 Self { h2 }
823 }
824
825 pub async fn get(
826 &self,
827 path: &str,
828 param: Option<Value>
829 ) -> Result<Value, Error> {
830 let req = Self::request_builder("localhost", "GET", path, param, None).unwrap();
831 self.request(req).await
832 }
833
834 pub async fn put(
835 &self,
836 path: &str,
837 param: Option<Value>
838 ) -> Result<Value, Error> {
839 let req = Self::request_builder("localhost", "PUT", path, param, None).unwrap();
840 self.request(req).await
841 }
842
843 pub async fn post(
844 &self,
845 path: &str,
846 param: Option<Value>
847 ) -> Result<Value, Error> {
848 let req = Self::request_builder("localhost", "POST", path, param, None).unwrap();
849 self.request(req).await
850 }
851
852 pub async fn download<W: Write + Send>(
853 &self,
854 path: &str,
855 param: Option<Value>,
856 mut output: W,
857 ) -> Result<(), Error> {
858 let request = Self::request_builder("localhost", "GET", path, param, None).unwrap();
859
860 let response_future = self.send_request(request, None).await?;
861
862 let resp = response_future.await?;
863
864 let status = resp.status();
865 if !status.is_success() {
866 H2Client::h2api_response(resp).await?; // raise error
867 unreachable!();
868 }
869
870 let mut body = resp.into_body();
871 while let Some(chunk) = body.data().await {
872 let chunk = chunk?;
873 body.flow_control().release_capacity(chunk.len())?;
874 output.write_all(&chunk)?;
875 }
876
877 Ok(())
878 }
879
880 pub async fn upload(
881 &self,
882 method: &str, // POST or PUT
883 path: &str,
884 param: Option<Value>,
885 content_type: &str,
886 data: Vec<u8>,
887 ) -> Result<Value, Error> {
888 let request = Self::request_builder("localhost", method, path, param, Some(content_type)).unwrap();
889
890 let mut send_request = self.h2.clone().ready().await?;
891
892 let (response, stream) = send_request.send_request(request, false).unwrap();
893
894 PipeToSendStream::new(bytes::Bytes::from(data), stream).await?;
895
896 response
897 .map_err(Error::from)
898 .and_then(Self::h2api_response)
899 .await
900 }
901
902 async fn request(
903 &self,
904 request: Request<()>,
905 ) -> Result<Value, Error> {
906
907 self.send_request(request, None)
908 .and_then(move |response| {
909 response
910 .map_err(Error::from)
911 .and_then(Self::h2api_response)
912 })
913 .await
914 }
915
916 pub fn send_request(
917 &self,
918 request: Request<()>,
919 data: Option<bytes::Bytes>,
920 ) -> impl Future<Output = Result<h2::client::ResponseFuture, Error>> {
921
922 self.h2.clone()
923 .ready()
924 .map_err(Error::from)
925 .and_then(move |mut send_request| async move {
926 if let Some(data) = data {
927 let (response, stream) = send_request.send_request(request, false).unwrap();
928 PipeToSendStream::new(data, stream).await?;
929 Ok(response)
930 } else {
931 let (response, _stream) = send_request.send_request(request, true).unwrap();
932 Ok(response)
933 }
934 })
935 }
936
937 pub async fn h2api_response(
938 response: Response<h2::RecvStream>,
939 ) -> Result<Value, Error> {
940 let status = response.status();
941
942 let (_head, mut body) = response.into_parts();
943
944 let mut data = Vec::new();
945 while let Some(chunk) = body.data().await {
946 let chunk = chunk?;
947 // Whenever data is received, the caller is responsible for
948 // releasing capacity back to the server once it has freed
949 // the data from memory.
950 // Let the server send more data.
951 body.flow_control().release_capacity(chunk.len())?;
952 data.extend(chunk);
953 }
954
955 let text = String::from_utf8(data.to_vec()).unwrap();
956 if status.is_success() {
957 if text.is_empty() {
958 Ok(Value::Null)
959 } else {
960 let mut value: Value = serde_json::from_str(&text)?;
961 if let Some(map) = value.as_object_mut() {
962 if let Some(data) = map.remove("data") {
963 return Ok(data);
964 }
965 }
966 bail!("got result without data property");
967 }
968 } else {
969 Err(Error::from(HttpError::new(status, text)))
970 }
971 }
972
973 // Note: We always encode parameters with the url
974 pub fn request_builder(
975 server: &str,
976 method: &str,
977 path: &str,
978 param: Option<Value>,
979 content_type: Option<&str>,
980 ) -> Result<Request<()>, Error> {
981 let path = path.trim_matches('/');
982
983 let content_type = content_type.unwrap_or("application/x-www-form-urlencoded");
984 let query = match param {
985 Some(param) => {
986 let query = tools::json_object_to_query(param)?;
987 // We detected problem with hyper around 6000 characters - so we try to keep on the safe side
988 if query.len() > 4096 {
989 bail!("h2 query data too large ({} bytes) - please encode data inside body", query.len());
990 }
991 Some(query)
992 }
993 None => None,
994 };
995
996 let url = build_uri(server, 8007, path, query)?;
997 let request = Request::builder()
998 .method(method)
999 .uri(url)
1000 .header("User-Agent", "proxmox-backup-client/1.0")
1001 .header(hyper::header::CONTENT_TYPE, content_type)
1002 .body(())?;
1003 Ok(request)
1004 }
1005 }