2 use std
::sync
::{Arc, Mutex, RwLock}
;
3 use std
::time
::Duration
;
5 use anyhow
::{bail, format_err, Error}
;
8 use http
::header
::HeaderValue
;
9 use http
::{Request, Response}
;
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
;
18 api
::error
::HttpError
,
20 tools
::fs
::{file_get_json, replace_file, CreateOptions}
,
23 use super::pipe_to_stream
::PipeToSendStream
;
24 use crate::api2
::types
::{Authid, Userid}
;
39 pub struct HttpClientOptions
{
40 prefix
: Option
<String
>,
41 password
: Option
<String
>,
42 fingerprint
: Option
<String
>,
45 fingerprint_cache
: bool
,
49 impl HttpClientOptions
{
51 pub fn new() -> Self {
58 fingerprint_cache
: false,
63 pub fn prefix(mut self, prefix
: Option
<String
>) -> Self {
68 pub fn password(mut self, password
: Option
<String
>) -> Self {
69 self.password
= password
;
73 pub fn fingerprint(mut self, fingerprint
: Option
<String
>) -> Self {
74 self.fingerprint
= fingerprint
;
78 pub fn interactive(mut self, interactive
: bool
) -> Self {
79 self.interactive
= interactive
;
83 pub fn ticket_cache(mut self, ticket_cache
: bool
) -> Self {
84 self.ticket_cache
= ticket_cache
;
88 pub fn fingerprint_cache(mut self, fingerprint_cache
: bool
) -> Self {
89 self.fingerprint_cache
= fingerprint_cache
;
93 pub fn verify_cert(mut self, verify_cert
: bool
) -> Self {
94 self.verify_cert
= verify_cert
;
99 /// HTTP(S) API client
100 pub struct HttpClient
{
101 client
: Client
<HttpsConnector
>,
104 fingerprint
: Arc
<Mutex
<Option
<String
>>>,
105 first_auth
: Option
<BroadcastFuture
<()>>,
106 auth
: Arc
<RwLock
<AuthInfo
>>,
107 ticket_abort
: futures
::future
::AbortHandle
,
108 _options
: HttpClientOptions
,
111 /// Delete stored ticket data (logout)
112 pub fn delete_ticket_info(prefix
: &str, server
: &str, username
: &Userid
) -> Result
<(), Error
> {
114 let base
= BaseDirectories
::with_prefix(prefix
)?
;
116 // usually /run/user/<uid>/...
117 let path
= base
.place_runtime_file("tickets")?
;
119 let mode
= nix
::sys
::stat
::Mode
::from_bits_truncate(0o0600);
121 let mut data
= file_get_json(&path
, Some(json
!({}
)))?
;
123 if let Some(map
) = data
[server
].as_object_mut() {
124 map
.remove(username
.as_str());
127 replace_file(path
, data
.to_string().as_bytes(), CreateOptions
::new().perm(mode
))?
;
132 fn store_fingerprint(prefix
: &str, server
: &str, fingerprint
: &str) -> Result
<(), Error
> {
134 let base
= BaseDirectories
::with_prefix(prefix
)?
;
136 // usually ~/.config/<prefix>/fingerprints
137 let path
= base
.place_config_file("fingerprints")?
;
139 let raw
= match std
::fs
::read_to_string(&path
) {
142 if err
.kind() == std
::io
::ErrorKind
::NotFound
{
145 bail
!("unable to read fingerprints from {:?} - {}", path
, err
);
150 let mut result
= String
::new();
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
158 result
.push_str(line
);
164 result
.push_str(server
);
166 result
.push_str(fingerprint
);
169 replace_file(path
, result
.as_bytes(), CreateOptions
::new())?
;
174 fn load_fingerprint(prefix
: &str, server
: &str) -> Option
<String
> {
176 let base
= BaseDirectories
::with_prefix(prefix
).ok()?
;
178 // usually ~/.config/<prefix>/fingerprints
179 let path
= base
.place_config_file("fingerprints").ok()?
;
181 let raw
= std
::fs
::read_to_string(&path
).ok()?
;
183 for line
in raw
.split('
\n'
) {
184 let items
: Vec
<String
> = line
.split_whitespace().map(String
::from
).collect();
185 if items
.len() == 2 && &items
[0] == server
{
186 return Some(items
[1].clone());
193 fn store_ticket_info(prefix
: &str, server
: &str, username
: &str, ticket
: &str, token
: &str) -> Result
<(), Error
> {
195 let base
= BaseDirectories
::with_prefix(prefix
)?
;
197 // usually /run/user/<uid>/...
198 let path
= base
.place_runtime_file("tickets")?
;
200 let mode
= nix
::sys
::stat
::Mode
::from_bits_truncate(0o0600);
202 let mut data
= file_get_json(&path
, Some(json
!({}
)))?
;
204 let now
= proxmox
::tools
::time
::epoch_i64();
206 data
[server
][username
] = json
!({ "timestamp": now, "ticket": ticket, "token": token}
);
208 let mut new_data
= json
!({}
);
210 let ticket_lifetime
= tools
::ticket
::TICKET_LIFETIME
- 60;
212 let empty
= serde_json
::map
::Map
::new();
213 for (server
, info
) in data
.as_object().unwrap_or(&empty
) {
214 for (user
, uinfo
) in info
.as_object().unwrap_or(&empty
) {
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();
224 replace_file(path
, new_data
.to_string().as_bytes(), CreateOptions
::new().perm(mode
))?
;
229 fn load_ticket_info(prefix
: &str, server
: &str, userid
: &Userid
) -> Option
<(String
, String
)> {
230 let base
= BaseDirectories
::with_prefix(prefix
).ok()?
;
232 // usually /run/user/<uid>/...
233 let path
= base
.place_runtime_file("tickets").ok()?
;
234 let data
= file_get_json(&path
, None
).ok()?
;
235 let now
= proxmox
::tools
::time
::epoch_i64();
236 let ticket_lifetime
= tools
::ticket
::TICKET_LIFETIME
- 60;
237 let uinfo
= data
[server
][userid
.as_str()].as_object()?
;
238 let timestamp
= uinfo
["timestamp"].as_i64()?
;
239 let age
= now
- timestamp
;
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()))
255 mut options
: HttpClientOptions
,
256 ) -> Result
<Self, Error
> {
258 let verified_fingerprint
= Arc
::new(Mutex
::new(None
));
260 let mut fingerprint
= options
.fingerprint
.take();
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() {
266 fingerprint
= load_fingerprint(options
.prefix
.as_ref().unwrap(), server
);
269 let mut ssl_connector_builder
= SslConnector
::builder(SslMethod
::tls()).unwrap();
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
);
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
);
287 *verified_fingerprint
.lock().unwrap() = Some(fingerprint
);
293 ssl_connector_builder
.set_verify(openssl
::ssl
::SslVerifyMode
::NONE
);
296 let mut httpc
= HttpConnector
::new();
297 httpc
.set_nodelay(true); // important for h2 download performance!
298 httpc
.enforce_http(false); // we want https...
300 httpc
.set_connect_timeout(Some(std
::time
::Duration
::new(10, 0)));
301 let https
= HttpsConnector
::with_connector(httpc
, ssl_connector_builder
.build());
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
);
308 let password
= options
.password
.take();
309 let use_ticket_cache
= options
.ticket_cache
&& options
.prefix
.is_some();
311 let password
= if let Some(password
) = password
{
314 let userid
= if auth_id
.is_token() {
315 bail
!("API token secret must be provided!");
319 let mut ticket_info
= None
;
320 if use_ticket_cache
{
321 ticket_info
= load_ticket_info(options
.prefix
.as_ref().unwrap(), server
, userid
);
323 if let Some((ticket
, _token
)) = ticket_info
{
326 Self::get_password(userid
, options
.interactive
)?
330 let auth
= Arc
::new(RwLock
::new(AuthInfo
{
331 auth_id
: auth_id
.clone(),
332 ticket
: password
.clone(),
333 token
: "".to_string(),
336 let server2
= server
.to_string();
337 let client2
= client
.clone();
338 let auth2
= auth
.clone();
339 let prefix2
= options
.prefix
.clone();
341 let renewal_future
= async
move {
343 tokio
::time
::delay_for(Duration
::new(60*15, 0)).await
; // 15 minutes
344 let (auth_id
, ticket
) = {
345 let authinfo
= auth2
.read().unwrap().clone();
346 (authinfo
.auth_id
, authinfo
.ticket
)
348 match Self::credentials(client2
.clone(), server2
.clone(), port
, auth_id
.user().clone(), ticket
).await
{
350 if use_ticket_cache
& &prefix2
.is_some() {
351 let _
= store_ticket_info(prefix2
.as_ref().unwrap(), &server2
, &auth
.auth_id
.to_string(), &auth
.ticket
, &auth
.token
);
353 *auth2
.write().unwrap() = auth
;
356 eprintln
!("re-authentication failed: {}", err
);
363 let (renewal_future
, ticket_abort
) = futures
::future
::abortable(renewal_future
);
365 let login_future
= Self::credentials(
369 auth_id
.user().clone(),
372 let server
= server
.to_string();
373 let prefix
= options
.prefix
.clone();
374 let authinfo
= auth
.clone();
377 if use_ticket_cache
& &prefix
.is_some() {
378 let _
= store_ticket_info(prefix
.as_ref().unwrap(), &server
, &auth
.auth_id
.to_string(), &auth
.ticket
, &auth
.token
);
380 *authinfo
.write().unwrap() = auth
;
381 tokio
::spawn(renewal_future
);
385 let first_auth
= if auth_id
.is_token() {
386 // TODO check access here?
389 Some(BroadcastFuture
::new(Box
::new(login_future
)))
394 server
: String
::from(server
),
396 fingerprint
: verified_fingerprint
,
406 /// Login is done on demand, so this is only required if you need
407 /// access to authentication data in 'AuthInfo'.
409 /// Note: tickets a periodially re-newed, so one can use this
410 /// to query changed ticket.
411 pub async
fn login(&self) -> Result
<AuthInfo
, Error
> {
412 if let Some(future
) = &self.first_auth
{
413 future
.listen().await?
;
416 let authinfo
= self.auth
.read().unwrap();
420 /// Returns the optional fingerprint passed to the new() constructor.
421 pub fn fingerprint(&self) -> Option
<String
> {
422 (*self.fingerprint
.lock().unwrap()).clone()
425 fn get_password(username
: &Userid
, interactive
: bool
) -> Result
<String
, Error
> {
426 // If we're on a TTY, query the user for a password
427 if interactive
&& tty
::stdin_isatty() {
428 let msg
= format
!("Password for \"{}\": ", username
);
429 return Ok(String
::from_utf8(tty
::read_password(&msg
)?
)?
);
432 bail
!("no password input mechanism available");
437 &mut X509StoreContextRef
,
438 expected_fingerprint
: Option
<String
>,
440 ) -> (bool
, Option
<String
>) {
441 if valid { return (true, None); }
443 let cert
= match ctx
.current_cert() {
445 None
=> return (false, None
),
448 let depth
= ctx
.error_depth();
449 if depth
!= 0 { return (false, None); }
451 let fp
= match cert
.digest(openssl
::hash
::MessageDigest
::sha256()) {
453 Err(_
) => return (false, None
), // should not happen
455 let fp_string
= proxmox
::tools
::digest_to_hex(&fp
);
456 let fp_string
= fp_string
.as_bytes().chunks(2).map(|v
| std
::str::from_utf8(v
).unwrap())
457 .collect
::<Vec
<&str>>().join(":");
459 if let Some(expected_fingerprint
) = expected_fingerprint
{
460 if expected_fingerprint
.to_lowercase() == fp_string
{
461 return (true, Some(fp_string
));
463 return (false, None
);
467 // If we're on a TTY, query the user
468 if interactive
&& tty
::stdin_isatty() {
469 println
!("fingerprint: {}", fp_string
);
471 print
!("Are you sure you want to continue connecting? (y/n): ");
472 let _
= std
::io
::stdout().flush();
473 use std
::io
::{BufRead, BufReader}
;
474 let mut line
= String
::new();
475 match BufReader
::new(std
::io
::stdin()).read_line(&mut line
) {
477 let trimmed
= line
.trim();
478 if trimmed
== "y" || trimmed
== "Y" {
479 return (true, Some(fp_string
));
480 } else if trimmed
== "n" || trimmed
== "N" {
481 return (false, None
);
486 Err(_
) => return (false, None
),
493 pub async
fn request(&self, mut req
: Request
<Body
>) -> Result
<Value
, Error
> {
495 let client
= self.client
.clone();
497 let auth
= self.login().await?
;
498 if auth
.auth_id
.is_token() {
499 let enc_api_token
= format
!("PBSAPIToken {}:{}", auth
.auth_id
, percent_encode(auth
.ticket
.as_bytes(), DEFAULT_ENCODE_SET
));
500 req
.headers_mut().insert("Authorization", HeaderValue
::from_str(&enc_api_token
).unwrap());
502 let enc_ticket
= format
!("PBSAuthCookie={}", percent_encode(auth
.ticket
.as_bytes(), DEFAULT_ENCODE_SET
));
503 req
.headers_mut().insert("Cookie", HeaderValue
::from_str(&enc_ticket
).unwrap());
504 req
.headers_mut().insert("CSRFPreventionToken", HeaderValue
::from_str(&auth
.token
).unwrap());
507 Self::api_request(client
, req
).await
514 ) -> Result
<Value
, Error
> {
515 let req
= Self::request_builder(&self.server
, self.port
, "GET", path
, data
)?
;
516 self.request(req
).await
523 ) -> Result
<Value
, Error
> {
524 let req
= Self::request_builder(&self.server
, self.port
, "DELETE", path
, data
)?
;
525 self.request(req
).await
532 ) -> Result
<Value
, Error
> {
533 let req
= Self::request_builder(&self.server
, self.port
, "POST", path
, data
)?
;
534 self.request(req
).await
541 ) -> Result
<Value
, Error
> {
542 let req
= Self::request_builder(&self.server
, self.port
, "PUT", path
, data
)?
;
543 self.request(req
).await
546 pub async
fn download(
549 output
: &mut (dyn Write
+ Send
),
550 ) -> Result
<(), Error
> {
551 let mut req
= Self::request_builder(&self.server
, self.port
, "GET", path
, None
)?
;
553 let client
= self.client
.clone();
555 let auth
= self.login().await?
;
557 let enc_ticket
= format
!("PBSAuthCookie={}", percent_encode(auth
.ticket
.as_bytes(), DEFAULT_ENCODE_SET
));
558 req
.headers_mut().insert("Cookie", HeaderValue
::from_str(&enc_ticket
).unwrap());
560 let resp
= client
.request(req
).await?
;
561 let status
= resp
.status();
562 if !status
.is_success() {
563 HttpClient
::api_response(resp
)
564 .map(|_
| Err(format_err
!("unknown error")))
568 .map_err(Error
::from
)
569 .try_fold(output
, move |acc
, chunk
| async
move {
570 acc
.write_all(&chunk
)?
;
584 ) -> Result
<Value
, Error
> {
586 let path
= path
.trim_matches('
/'
);
587 let mut url
= format
!("https://{}:{}/{}", &self.server
, self.port
, path
);
589 if let Some(data
) = data
{
590 let query
= tools
::json_object_to_query(data
).unwrap();
592 url
.push_str(&query
);
595 let url
: Uri
= url
.parse().unwrap();
597 let req
= Request
::builder()
600 .header("User-Agent", "proxmox-backup-client/1.0")
601 .header("Content-Type", content_type
)
602 .body(body
).unwrap();
604 self.request(req
).await
607 pub async
fn start_h2_connection(
609 mut req
: Request
<Body
>,
610 protocol_name
: String
,
611 ) -> Result
<(H2Client
, futures
::future
::AbortHandle
), Error
> {
613 let client
= self.client
.clone();
614 let auth
= self.login().await?
;
616 if auth
.auth_id
.is_token() {
617 let enc_api_token
= format
!("PBSAPIToken {}:{}", auth
.auth_id
, percent_encode(auth
.ticket
.as_bytes(), DEFAULT_ENCODE_SET
));
618 req
.headers_mut().insert("Authorization", HeaderValue
::from_str(&enc_api_token
).unwrap());
620 let enc_ticket
= format
!("PBSAuthCookie={}", percent_encode(auth
.ticket
.as_bytes(), DEFAULT_ENCODE_SET
));
621 req
.headers_mut().insert("Cookie", HeaderValue
::from_str(&enc_ticket
).unwrap());
622 req
.headers_mut().insert("CSRFPreventionToken", HeaderValue
::from_str(&auth
.token
).unwrap());
625 req
.headers_mut().insert("UPGRADE", HeaderValue
::from_str(&protocol_name
).unwrap());
627 let resp
= client
.request(req
).await?
;
628 let status
= resp
.status();
630 if status
!= http
::StatusCode
::SWITCHING_PROTOCOLS
{
631 Self::api_response(resp
).await?
;
632 bail
!("unknown error");
640 let max_window_size
= (1 << 31) - 2;
642 let (h2
, connection
) = h2
::client
::Builder
::new()
643 .initial_connection_window_size(max_window_size
)
644 .initial_window_size(max_window_size
)
645 .max_frame_size(4*1024*1024)
649 let connection
= connection
650 .map_err(|_
| eprintln
!("HTTP/2.0 connection failed"));
652 let (connection
, abort
) = futures
::future
::abortable(connection
);
653 // A cancellable future returns an Option which is None when cancelled and
654 // Some when it finished instead, since we don't care about the return type we
655 // need to map it away:
656 let connection
= connection
.map(|_
| ());
658 // Spawn a new task to drive the connection state
659 tokio
::spawn(connection
);
661 // Wait until the `SendRequest` handle has available capacity.
662 let c
= h2
.ready().await?
;
663 Ok((H2Client
::new(c
), abort
))
666 async
fn credentials(
667 client
: Client
<HttpsConnector
>,
672 ) -> Result
<AuthInfo
, Error
> {
673 let data
= json
!({ "username": username, "password": password }
);
674 let req
= Self::request_builder(&server
, port
, "POST", "/api2/json/access/ticket", Some(data
))?
;
675 let cred
= Self::api_request(client
, req
).await?
;
676 let auth
= AuthInfo
{
677 auth_id
: cred
["data"]["username"].as_str().unwrap().parse()?
,
678 ticket
: cred
["data"]["ticket"].as_str().unwrap().to_owned(),
679 token
: cred
["data"]["CSRFPreventionToken"].as_str().unwrap().to_owned(),
685 async
fn api_response(response
: Response
<Body
>) -> Result
<Value
, Error
> {
686 let status
= response
.status();
687 let data
= hyper
::body
::to_bytes(response
.into_body()).await?
;
689 let text
= String
::from_utf8(data
.to_vec()).unwrap();
690 if status
.is_success() {
694 let value
: Value
= serde_json
::from_str(&text
)?
;
698 Err(Error
::from(HttpError
::new(status
, text
)))
702 async
fn api_request(
703 client
: Client
<HttpsConnector
>,
705 ) -> Result
<Value
, Error
> {
708 .map_err(Error
::from
)
709 .and_then(Self::api_response
)
713 // Read-only access to server property
714 pub fn server(&self) -> &str {
718 pub fn port(&self) -> u16 {
722 pub fn request_builder(server
: &str, port
: u16, method
: &str, path
: &str, data
: Option
<Value
>) -> Result
<Request
<Body
>, Error
> {
723 let path
= path
.trim_matches('
/'
);
724 let url
: Uri
= format
!("https://{}:{}/{}", server
, port
, path
).parse()?
;
726 if let Some(data
) = data
{
727 if method
== "POST" {
728 let request
= Request
::builder()
731 .header("User-Agent", "proxmox-backup-client/1.0")
732 .header(hyper
::header
::CONTENT_TYPE
, "application/json")
733 .body(Body
::from(data
.to_string()))?
;
736 let query
= tools
::json_object_to_query(data
)?
;
737 let url
: Uri
= format
!("https://{}:{}/{}?{}", server
, port
, path
, query
).parse()?
;
738 let request
= Request
::builder()
741 .header("User-Agent", "proxmox-backup-client/1.0")
742 .header(hyper
::header
::CONTENT_TYPE
, "application/x-www-form-urlencoded")
743 .body(Body
::empty())?
;
748 let request
= Request
::builder()
751 .header("User-Agent", "proxmox-backup-client/1.0")
752 .header(hyper
::header
::CONTENT_TYPE
, "application/x-www-form-urlencoded")
753 .body(Body
::empty())?
;
759 impl Drop
for HttpClient
{
761 self.ticket_abort
.abort();
767 pub struct H2Client
{
768 h2
: h2
::client
::SendRequest
<bytes
::Bytes
>,
773 pub fn new(h2
: h2
::client
::SendRequest
<bytes
::Bytes
>) -> Self {
781 ) -> Result
<Value
, Error
> {
782 let req
= Self::request_builder("localhost", "GET", path
, param
, None
).unwrap();
783 self.request(req
).await
790 ) -> Result
<Value
, Error
> {
791 let req
= Self::request_builder("localhost", "PUT", path
, param
, None
).unwrap();
792 self.request(req
).await
799 ) -> Result
<Value
, Error
> {
800 let req
= Self::request_builder("localhost", "POST", path
, param
, None
).unwrap();
801 self.request(req
).await
804 pub async
fn download
<W
: Write
+ Send
>(
807 param
: Option
<Value
>,
809 ) -> Result
<(), Error
> {
810 let request
= Self::request_builder("localhost", "GET", path
, param
, None
).unwrap();
812 let response_future
= self.send_request(request
, None
).await?
;
814 let resp
= response_future
.await?
;
816 let status
= resp
.status();
817 if !status
.is_success() {
818 H2Client
::h2api_response(resp
).await?
; // raise error
822 let mut body
= resp
.into_body();
823 while let Some(chunk
) = body
.data().await
{
825 body
.flow_control().release_capacity(chunk
.len())?
;
826 output
.write_all(&chunk
)?
;
834 method
: &str, // POST or PUT
836 param
: Option
<Value
>,
839 ) -> Result
<Value
, Error
> {
840 let request
= Self::request_builder("localhost", method
, path
, param
, Some(content_type
)).unwrap();
842 let mut send_request
= self.h2
.clone().ready().await?
;
844 let (response
, stream
) = send_request
.send_request(request
, false).unwrap();
846 PipeToSendStream
::new(bytes
::Bytes
::from(data
), stream
).await?
;
849 .map_err(Error
::from
)
850 .and_then(Self::h2api_response
)
856 request
: Request
<()>,
857 ) -> Result
<Value
, Error
> {
859 self.send_request(request
, None
)
860 .and_then(move |response
| {
862 .map_err(Error
::from
)
863 .and_then(Self::h2api_response
)
870 request
: Request
<()>,
871 data
: Option
<bytes
::Bytes
>,
872 ) -> impl Future
<Output
= Result
<h2
::client
::ResponseFuture
, Error
>> {
876 .map_err(Error
::from
)
877 .and_then(move |mut send_request
| async
move {
878 if let Some(data
) = data
{
879 let (response
, stream
) = send_request
.send_request(request
, false).unwrap();
880 PipeToSendStream
::new(data
, stream
).await?
;
883 let (response
, _stream
) = send_request
.send_request(request
, true).unwrap();
889 pub async
fn h2api_response(
890 response
: Response
<h2
::RecvStream
>,
891 ) -> Result
<Value
, Error
> {
892 let status
= response
.status();
894 let (_head
, mut body
) = response
.into_parts();
896 let mut data
= Vec
::new();
897 while let Some(chunk
) = body
.data().await
{
899 // Whenever data is received, the caller is responsible for
900 // releasing capacity back to the server once it has freed
901 // the data from memory.
902 // Let the server send more data.
903 body
.flow_control().release_capacity(chunk
.len())?
;
907 let text
= String
::from_utf8(data
.to_vec()).unwrap();
908 if status
.is_success() {
912 let mut value
: Value
= serde_json
::from_str(&text
)?
;
913 if let Some(map
) = value
.as_object_mut() {
914 if let Some(data
) = map
.remove("data") {
918 bail
!("got result without data property");
921 Err(Error
::from(HttpError
::new(status
, text
)))
925 // Note: We always encode parameters with the url
926 pub fn request_builder(
930 param
: Option
<Value
>,
931 content_type
: Option
<&str>,
932 ) -> Result
<Request
<()>, Error
> {
933 let path
= path
.trim_matches('
/'
);
935 let content_type
= content_type
.unwrap_or("application/x-www-form-urlencoded");
937 if let Some(param
) = param
{
938 let query
= tools
::json_object_to_query(param
)?
;
939 // We detected problem with hyper around 6000 characters - seo we try to keep on the safe side
940 if query
.len() > 4096 { bail!("h2 query data too large ({} bytes
) - please encode data inside body
", query.len()); }
941 let url: Uri = format!("https
://{}:8007/{}?{}", server, path, query).parse()?;
942 let request
= Request
::builder()
945 .header("User-Agent", "proxmox-backup-client/1.0")
946 .header(hyper
::header
::CONTENT_TYPE
, content_type
)
950 let url
: Uri
= format
!("https://{}:8007/{}", server
, path
).parse()?
;
951 let request
= Request
::builder()
954 .header("User-Agent", "proxmox-backup-client/1.0")
955 .header(hyper
::header
::CONTENT_TYPE
, content_type
)