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