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}
;
32 /// Timeout used for several HTTP operations that are expected to finish quickly but may block in
33 /// certain error conditions. Keep it generous, to avoid false-positive under high load.
34 const HTTP_TIMEOUT
: Duration
= Duration
::from_secs(2 * 60);
43 pub struct HttpClientOptions
{
44 prefix
: Option
<String
>,
45 password
: Option
<String
>,
46 fingerprint
: Option
<String
>,
49 fingerprint_cache
: bool
,
53 impl HttpClientOptions
{
55 pub fn new_interactive(password
: Option
<String
>, fingerprint
: Option
<String
>) -> Self {
59 fingerprint_cache
: true,
62 prefix
: Some("proxmox-backup".to_string()),
67 pub fn new_non_interactive(password
: String
, fingerprint
: Option
<String
>) -> Self {
69 password
: Some(password
),
75 pub fn prefix(mut self, prefix
: Option
<String
>) -> Self {
80 pub fn password(mut self, password
: Option
<String
>) -> Self {
81 self.password
= password
;
85 pub fn fingerprint(mut self, fingerprint
: Option
<String
>) -> Self {
86 self.fingerprint
= fingerprint
;
90 pub fn interactive(mut self, interactive
: bool
) -> Self {
91 self.interactive
= interactive
;
95 pub fn ticket_cache(mut self, ticket_cache
: bool
) -> Self {
96 self.ticket_cache
= ticket_cache
;
100 pub fn fingerprint_cache(mut self, fingerprint_cache
: bool
) -> Self {
101 self.fingerprint_cache
= fingerprint_cache
;
105 pub fn verify_cert(mut self, verify_cert
: bool
) -> Self {
106 self.verify_cert
= verify_cert
;
111 impl Default
for HttpClientOptions
{
112 fn default() -> Self {
119 fingerprint_cache
: false,
125 /// HTTP(S) API client
126 pub struct HttpClient
{
127 client
: Client
<HttpsConnector
>,
130 fingerprint
: Arc
<Mutex
<Option
<String
>>>,
131 first_auth
: Option
<BroadcastFuture
<()>>,
132 auth
: Arc
<RwLock
<AuthInfo
>>,
133 ticket_abort
: futures
::future
::AbortHandle
,
134 _options
: HttpClientOptions
,
137 /// Delete stored ticket data (logout)
138 pub fn delete_ticket_info(prefix
: &str, server
: &str, username
: &Userid
) -> Result
<(), Error
> {
140 let base
= BaseDirectories
::with_prefix(prefix
)?
;
142 // usually /run/user/<uid>/...
143 let path
= base
.place_runtime_file("tickets")?
;
145 let mode
= nix
::sys
::stat
::Mode
::from_bits_truncate(0o0600);
147 let mut data
= file_get_json(&path
, Some(json
!({}
)))?
;
149 if let Some(map
) = data
[server
].as_object_mut() {
150 map
.remove(username
.as_str());
153 replace_file(path
, data
.to_string().as_bytes(), CreateOptions
::new().perm(mode
))?
;
158 fn store_fingerprint(prefix
: &str, server
: &str, fingerprint
: &str) -> Result
<(), Error
> {
160 let base
= BaseDirectories
::with_prefix(prefix
)?
;
162 // usually ~/.config/<prefix>/fingerprints
163 let path
= base
.place_config_file("fingerprints")?
;
165 let raw
= match std
::fs
::read_to_string(&path
) {
168 if err
.kind() == std
::io
::ErrorKind
::NotFound
{
171 bail
!("unable to read fingerprints from {:?} - {}", path
, err
);
176 let mut result
= String
::new();
178 raw
.split('
\n'
).for_each(|line
| {
179 let items
: Vec
<String
> = line
.split_whitespace().map(String
::from
).collect();
180 if items
.len() == 2 {
181 if items
[0] == server
{
182 // found, add later with new fingerprint
184 result
.push_str(line
);
190 result
.push_str(server
);
192 result
.push_str(fingerprint
);
195 replace_file(path
, result
.as_bytes(), CreateOptions
::new())?
;
200 fn load_fingerprint(prefix
: &str, server
: &str) -> Option
<String
> {
202 let base
= BaseDirectories
::with_prefix(prefix
).ok()?
;
204 // usually ~/.config/<prefix>/fingerprints
205 let path
= base
.place_config_file("fingerprints").ok()?
;
207 let raw
= std
::fs
::read_to_string(&path
).ok()?
;
209 for line
in raw
.split('
\n'
) {
210 let items
: Vec
<String
> = line
.split_whitespace().map(String
::from
).collect();
211 if items
.len() == 2 && items
[0] == server
{
212 return Some(items
[1].clone());
219 fn store_ticket_info(prefix
: &str, server
: &str, username
: &str, ticket
: &str, token
: &str) -> Result
<(), Error
> {
221 let base
= BaseDirectories
::with_prefix(prefix
)?
;
223 // usually /run/user/<uid>/...
224 let path
= base
.place_runtime_file("tickets")?
;
226 let mode
= nix
::sys
::stat
::Mode
::from_bits_truncate(0o0600);
228 let mut data
= file_get_json(&path
, Some(json
!({}
)))?
;
230 let now
= proxmox
::tools
::time
::epoch_i64();
232 data
[server
][username
] = json
!({ "timestamp": now, "ticket": ticket, "token": token}
);
234 let mut new_data
= json
!({}
);
236 let ticket_lifetime
= tools
::ticket
::TICKET_LIFETIME
- 60;
238 let empty
= serde_json
::map
::Map
::new();
239 for (server
, info
) in data
.as_object().unwrap_or(&empty
) {
240 for (user
, uinfo
) in info
.as_object().unwrap_or(&empty
) {
241 if let Some(timestamp
) = uinfo
["timestamp"].as_i64() {
242 let age
= now
- timestamp
;
243 if age
< ticket_lifetime
{
244 new_data
[server
][user
] = uinfo
.clone();
250 replace_file(path
, new_data
.to_string().as_bytes(), CreateOptions
::new().perm(mode
))?
;
255 fn load_ticket_info(prefix
: &str, server
: &str, userid
: &Userid
) -> Option
<(String
, String
)> {
256 let base
= BaseDirectories
::with_prefix(prefix
).ok()?
;
258 // usually /run/user/<uid>/...
259 let path
= base
.place_runtime_file("tickets").ok()?
;
260 let data
= file_get_json(&path
, None
).ok()?
;
261 let now
= proxmox
::tools
::time
::epoch_i64();
262 let ticket_lifetime
= tools
::ticket
::TICKET_LIFETIME
- 60;
263 let uinfo
= data
[server
][userid
.as_str()].as_object()?
;
264 let timestamp
= uinfo
["timestamp"].as_i64()?
;
265 let age
= now
- timestamp
;
267 if age
< ticket_lifetime
{
268 let ticket
= uinfo
["ticket"].as_str()?
;
269 let token
= uinfo
["token"].as_str()?
;
270 Some((ticket
.to_owned(), token
.to_owned()))
281 mut options
: HttpClientOptions
,
282 ) -> Result
<Self, Error
> {
284 let verified_fingerprint
= Arc
::new(Mutex
::new(None
));
286 let mut fingerprint
= options
.fingerprint
.take();
288 if fingerprint
.is_some() {
289 // do not store fingerprints passed via options in cache
290 options
.fingerprint_cache
= false;
291 } else if options
.fingerprint_cache
&& options
.prefix
.is_some() {
292 fingerprint
= load_fingerprint(options
.prefix
.as_ref().unwrap(), server
);
295 let mut ssl_connector_builder
= SslConnector
::builder(SslMethod
::tls()).unwrap();
297 if options
.verify_cert
{
298 let server
= server
.to_string();
299 let verified_fingerprint
= verified_fingerprint
.clone();
300 let interactive
= options
.interactive
;
301 let fingerprint_cache
= options
.fingerprint_cache
;
302 let prefix
= options
.prefix
.clone();
303 ssl_connector_builder
.set_verify_callback(openssl
::ssl
::SslVerifyMode
::PEER
, move |valid
, ctx
| {
304 let (valid
, fingerprint
) = Self::verify_callback(valid
, ctx
, fingerprint
.clone(), interactive
);
306 if let Some(fingerprint
) = fingerprint
{
307 if fingerprint_cache
&& prefix
.is_some() {
308 if let Err(err
) = store_fingerprint(
309 prefix
.as_ref().unwrap(), &server
, &fingerprint
) {
310 eprintln
!("{}", err
);
313 *verified_fingerprint
.lock().unwrap() = Some(fingerprint
);
319 ssl_connector_builder
.set_verify(openssl
::ssl
::SslVerifyMode
::NONE
);
322 let mut httpc
= HttpConnector
::new();
323 httpc
.set_nodelay(true); // important for h2 download performance!
324 httpc
.enforce_http(false); // we want https...
326 httpc
.set_connect_timeout(Some(std
::time
::Duration
::new(10, 0)));
327 let https
= HttpsConnector
::with_connector(httpc
, ssl_connector_builder
.build());
329 let client
= Client
::builder()
330 //.http2_initial_stream_window_size( (1 << 31) - 2)
331 //.http2_initial_connection_window_size( (1 << 31) - 2)
332 .build
::<_
, Body
>(https
);
334 let password
= options
.password
.take();
335 let use_ticket_cache
= options
.ticket_cache
&& options
.prefix
.is_some();
337 let password
= if let Some(password
) = password
{
340 let userid
= if auth_id
.is_token() {
341 bail
!("API token secret must be provided!");
345 let mut ticket_info
= None
;
346 if use_ticket_cache
{
347 ticket_info
= load_ticket_info(options
.prefix
.as_ref().unwrap(), server
, userid
);
349 if let Some((ticket
, _token
)) = ticket_info
{
352 Self::get_password(userid
, options
.interactive
)?
356 let auth
= Arc
::new(RwLock
::new(AuthInfo
{
357 auth_id
: auth_id
.clone(),
358 ticket
: password
.clone(),
359 token
: "".to_string(),
362 let server2
= server
.to_string();
363 let client2
= client
.clone();
364 let auth2
= auth
.clone();
365 let prefix2
= options
.prefix
.clone();
367 let renewal_future
= async
move {
369 tokio
::time
::sleep(Duration
::new(60*15, 0)).await
; // 15 minutes
370 let (auth_id
, ticket
) = {
371 let authinfo
= auth2
.read().unwrap().clone();
372 (authinfo
.auth_id
, authinfo
.ticket
)
374 match Self::credentials(client2
.clone(), server2
.clone(), port
, auth_id
.user().clone(), ticket
).await
{
376 if use_ticket_cache
&& prefix2
.is_some() {
377 let _
= store_ticket_info(prefix2
.as_ref().unwrap(), &server2
, &auth
.auth_id
.to_string(), &auth
.ticket
, &auth
.token
);
379 *auth2
.write().unwrap() = auth
;
382 eprintln
!("re-authentication failed: {}", err
);
389 let (renewal_future
, ticket_abort
) = futures
::future
::abortable(renewal_future
);
391 let login_future
= Self::credentials(
395 auth_id
.user().clone(),
398 let server
= server
.to_string();
399 let prefix
= options
.prefix
.clone();
400 let authinfo
= auth
.clone();
403 if use_ticket_cache
&& prefix
.is_some() {
404 let _
= store_ticket_info(prefix
.as_ref().unwrap(), &server
, &auth
.auth_id
.to_string(), &auth
.ticket
, &auth
.token
);
406 *authinfo
.write().unwrap() = auth
;
407 tokio
::spawn(renewal_future
);
411 let first_auth
= if auth_id
.is_token() {
412 // TODO check access here?
415 Some(BroadcastFuture
::new(Box
::new(login_future
)))
420 server
: String
::from(server
),
422 fingerprint
: verified_fingerprint
,
432 /// Login is done on demand, so this is only required if you need
433 /// access to authentication data in 'AuthInfo'.
435 /// Note: tickets a periodially re-newed, so one can use this
436 /// to query changed ticket.
437 pub async
fn login(&self) -> Result
<AuthInfo
, Error
> {
438 if let Some(future
) = &self.first_auth
{
439 future
.listen().await?
;
442 let authinfo
= self.auth
.read().unwrap();
446 /// Returns the optional fingerprint passed to the new() constructor.
447 pub fn fingerprint(&self) -> Option
<String
> {
448 (*self.fingerprint
.lock().unwrap()).clone()
451 fn get_password(username
: &Userid
, interactive
: bool
) -> Result
<String
, Error
> {
452 // If we're on a TTY, query the user for a password
453 if interactive
&& tty
::stdin_isatty() {
454 let msg
= format
!("Password for \"{}\": ", username
);
455 return Ok(String
::from_utf8(tty
::read_password(&msg
)?
)?
);
458 bail
!("no password input mechanism available");
463 &mut X509StoreContextRef
,
464 expected_fingerprint
: Option
<String
>,
466 ) -> (bool
, Option
<String
>) {
467 if valid { return (true, None); }
469 let cert
= match ctx
.current_cert() {
471 None
=> return (false, None
),
474 let depth
= ctx
.error_depth();
475 if depth
!= 0 { return (false, None); }
477 let fp
= match cert
.digest(openssl
::hash
::MessageDigest
::sha256()) {
479 Err(_
) => return (false, None
), // should not happen
481 let fp_string
= proxmox
::tools
::digest_to_hex(&fp
);
482 let fp_string
= fp_string
.as_bytes().chunks(2).map(|v
| std
::str::from_utf8(v
).unwrap())
483 .collect
::<Vec
<&str>>().join(":");
485 if let Some(expected_fingerprint
) = expected_fingerprint
{
486 if expected_fingerprint
.to_lowercase() == fp_string
{
487 return (true, Some(fp_string
));
489 return (false, None
);
493 // If we're on a TTY, query the user
494 if interactive
&& tty
::stdin_isatty() {
495 println
!("fingerprint: {}", fp_string
);
497 print
!("Are you sure you want to continue connecting? (y/n): ");
498 let _
= std
::io
::stdout().flush();
499 use std
::io
::{BufRead, BufReader}
;
500 let mut line
= String
::new();
501 match BufReader
::new(std
::io
::stdin()).read_line(&mut line
) {
503 let trimmed
= line
.trim();
504 if trimmed
== "y" || trimmed
== "Y" {
505 return (true, Some(fp_string
));
506 } else if trimmed
== "n" || trimmed
== "N" {
507 return (false, None
);
512 Err(_
) => return (false, None
),
519 pub async
fn request(&self, mut req
: Request
<Body
>) -> Result
<Value
, Error
> {
521 let client
= self.client
.clone();
523 let auth
= self.login().await?
;
524 if auth
.auth_id
.is_token() {
525 let enc_api_token
= format
!("PBSAPIToken {}:{}", auth
.auth_id
, percent_encode(auth
.ticket
.as_bytes(), DEFAULT_ENCODE_SET
));
526 req
.headers_mut().insert("Authorization", HeaderValue
::from_str(&enc_api_token
).unwrap());
528 let enc_ticket
= format
!("PBSAuthCookie={}", percent_encode(auth
.ticket
.as_bytes(), DEFAULT_ENCODE_SET
));
529 req
.headers_mut().insert("Cookie", HeaderValue
::from_str(&enc_ticket
).unwrap());
530 req
.headers_mut().insert("CSRFPreventionToken", HeaderValue
::from_str(&auth
.token
).unwrap());
533 Self::api_request(client
, req
).await
540 ) -> Result
<Value
, Error
> {
541 let req
= Self::request_builder(&self.server
, self.port
, "GET", path
, data
)?
;
542 self.request(req
).await
549 ) -> Result
<Value
, Error
> {
550 let req
= Self::request_builder(&self.server
, self.port
, "DELETE", path
, data
)?
;
551 self.request(req
).await
558 ) -> Result
<Value
, Error
> {
559 let req
= Self::request_builder(&self.server
, self.port
, "POST", path
, data
)?
;
560 self.request(req
).await
567 ) -> Result
<Value
, Error
> {
568 let req
= Self::request_builder(&self.server
, self.port
, "PUT", path
, data
)?
;
569 self.request(req
).await
572 pub async
fn download(
575 output
: &mut (dyn Write
+ Send
),
576 ) -> Result
<(), Error
> {
577 let mut req
= Self::request_builder(&self.server
, self.port
, "GET", path
, None
)?
;
579 let client
= self.client
.clone();
581 let auth
= self.login().await?
;
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());
586 let resp
= tokio
::time
::timeout(
591 .map_err(|_
| format_err
!("http download request timed out"))??
;
592 let status
= resp
.status();
593 if !status
.is_success() {
594 HttpClient
::api_response(resp
)
595 .map(|_
| Err(format_err
!("unknown error")))
599 .map_err(Error
::from
)
600 .try_fold(output
, move |acc
, chunk
| async
move {
601 acc
.write_all(&chunk
)?
;
615 ) -> Result
<Value
, Error
> {
617 let path
= path
.trim_matches('
/'
);
618 let mut url
= format
!("https://{}:{}/{}", &self.server
, self.port
, path
);
620 if let Some(data
) = data
{
621 let query
= tools
::json_object_to_query(data
).unwrap();
623 url
.push_str(&query
);
626 let url
: Uri
= url
.parse().unwrap();
628 let req
= Request
::builder()
631 .header("User-Agent", "proxmox-backup-client/1.0")
632 .header("Content-Type", content_type
)
633 .body(body
).unwrap();
635 self.request(req
).await
638 pub async
fn start_h2_connection(
640 mut req
: Request
<Body
>,
641 protocol_name
: String
,
642 ) -> Result
<(H2Client
, futures
::future
::AbortHandle
), Error
> {
644 let client
= self.client
.clone();
645 let auth
= self.login().await?
;
647 if auth
.auth_id
.is_token() {
648 let enc_api_token
= format
!("PBSAPIToken {}:{}", auth
.auth_id
, percent_encode(auth
.ticket
.as_bytes(), DEFAULT_ENCODE_SET
));
649 req
.headers_mut().insert("Authorization", HeaderValue
::from_str(&enc_api_token
).unwrap());
651 let enc_ticket
= format
!("PBSAuthCookie={}", percent_encode(auth
.ticket
.as_bytes(), DEFAULT_ENCODE_SET
));
652 req
.headers_mut().insert("Cookie", HeaderValue
::from_str(&enc_ticket
).unwrap());
653 req
.headers_mut().insert("CSRFPreventionToken", HeaderValue
::from_str(&auth
.token
).unwrap());
656 req
.headers_mut().insert("UPGRADE", HeaderValue
::from_str(&protocol_name
).unwrap());
658 let resp
= tokio
::time
::timeout(
663 .map_err(|_
| format_err
!("http upgrade request timed out"))??
;
664 let status
= resp
.status();
666 if status
!= http
::StatusCode
::SWITCHING_PROTOCOLS
{
667 Self::api_response(resp
).await?
;
668 bail
!("unknown error");
671 let upgraded
= hyper
::upgrade
::on(resp
).await?
;
673 let max_window_size
= (1 << 31) - 2;
675 let (h2
, connection
) = h2
::client
::Builder
::new()
676 .initial_connection_window_size(max_window_size
)
677 .initial_window_size(max_window_size
)
678 .max_frame_size(4*1024*1024)
682 let connection
= connection
683 .map_err(|_
| eprintln
!("HTTP/2.0 connection failed"));
685 let (connection
, abort
) = futures
::future
::abortable(connection
);
686 // A cancellable future returns an Option which is None when cancelled and
687 // Some when it finished instead, since we don't care about the return type we
688 // need to map it away:
689 let connection
= connection
.map(|_
| ());
691 // Spawn a new task to drive the connection state
692 tokio
::spawn(connection
);
694 // Wait until the `SendRequest` handle has available capacity.
695 let c
= h2
.ready().await?
;
696 Ok((H2Client
::new(c
), abort
))
699 async
fn credentials(
700 client
: Client
<HttpsConnector
>,
705 ) -> Result
<AuthInfo
, Error
> {
706 let data
= json
!({ "username": username, "password": password }
);
707 let req
= Self::request_builder(&server
, port
, "POST", "/api2/json/access/ticket", Some(data
))?
;
708 let cred
= Self::api_request(client
, req
).await?
;
709 let auth
= AuthInfo
{
710 auth_id
: cred
["data"]["username"].as_str().unwrap().parse()?
,
711 ticket
: cred
["data"]["ticket"].as_str().unwrap().to_owned(),
712 token
: cred
["data"]["CSRFPreventionToken"].as_str().unwrap().to_owned(),
718 async
fn api_response(response
: Response
<Body
>) -> Result
<Value
, Error
> {
719 let status
= response
.status();
720 let data
= hyper
::body
::to_bytes(response
.into_body()).await?
;
722 let text
= String
::from_utf8(data
.to_vec()).unwrap();
723 if status
.is_success() {
727 let value
: Value
= serde_json
::from_str(&text
)?
;
731 Err(Error
::from(HttpError
::new(status
, text
)))
735 async
fn api_request(
736 client
: Client
<HttpsConnector
>,
738 ) -> Result
<Value
, Error
> {
741 tokio
::time
::timeout(
746 .map_err(|_
| format_err
!("http request timed out"))??
750 // Read-only access to server property
751 pub fn server(&self) -> &str {
755 pub fn port(&self) -> u16 {
759 pub fn request_builder(server
: &str, port
: u16, method
: &str, path
: &str, data
: Option
<Value
>) -> Result
<Request
<Body
>, Error
> {
760 let path
= path
.trim_matches('
/'
);
761 let url
: Uri
= format
!("https://{}:{}/{}", server
, port
, path
).parse()?
;
763 if let Some(data
) = data
{
764 if method
== "POST" {
765 let request
= Request
::builder()
768 .header("User-Agent", "proxmox-backup-client/1.0")
769 .header(hyper
::header
::CONTENT_TYPE
, "application/json")
770 .body(Body
::from(data
.to_string()))?
;
773 let query
= tools
::json_object_to_query(data
)?
;
774 let url
: Uri
= format
!("https://{}:{}/{}?{}", server
, port
, path
, query
).parse()?
;
775 let request
= Request
::builder()
778 .header("User-Agent", "proxmox-backup-client/1.0")
779 .header(hyper
::header
::CONTENT_TYPE
, "application/x-www-form-urlencoded")
780 .body(Body
::empty())?
;
785 let request
= Request
::builder()
788 .header("User-Agent", "proxmox-backup-client/1.0")
789 .header(hyper
::header
::CONTENT_TYPE
, "application/x-www-form-urlencoded")
790 .body(Body
::empty())?
;
796 impl Drop
for HttpClient
{
798 self.ticket_abort
.abort();
804 pub struct H2Client
{
805 h2
: h2
::client
::SendRequest
<bytes
::Bytes
>,
810 pub fn new(h2
: h2
::client
::SendRequest
<bytes
::Bytes
>) -> Self {
818 ) -> Result
<Value
, Error
> {
819 let req
= Self::request_builder("localhost", "GET", path
, param
, None
).unwrap();
820 self.request(req
).await
827 ) -> Result
<Value
, Error
> {
828 let req
= Self::request_builder("localhost", "PUT", path
, param
, None
).unwrap();
829 self.request(req
).await
836 ) -> Result
<Value
, Error
> {
837 let req
= Self::request_builder("localhost", "POST", path
, param
, None
).unwrap();
838 self.request(req
).await
841 pub async
fn download
<W
: Write
+ Send
>(
844 param
: Option
<Value
>,
846 ) -> Result
<(), Error
> {
847 let request
= Self::request_builder("localhost", "GET", path
, param
, None
).unwrap();
849 let response_future
= self.send_request(request
, None
).await?
;
851 let resp
= response_future
.await?
;
853 let status
= resp
.status();
854 if !status
.is_success() {
855 H2Client
::h2api_response(resp
).await?
; // raise error
859 let mut body
= resp
.into_body();
860 while let Some(chunk
) = body
.data().await
{
862 body
.flow_control().release_capacity(chunk
.len())?
;
863 output
.write_all(&chunk
)?
;
871 method
: &str, // POST or PUT
873 param
: Option
<Value
>,
876 ) -> Result
<Value
, Error
> {
877 let request
= Self::request_builder("localhost", method
, path
, param
, Some(content_type
)).unwrap();
879 let mut send_request
= self.h2
.clone().ready().await?
;
881 let (response
, stream
) = send_request
.send_request(request
, false).unwrap();
883 PipeToSendStream
::new(bytes
::Bytes
::from(data
), stream
).await?
;
886 .map_err(Error
::from
)
887 .and_then(Self::h2api_response
)
893 request
: Request
<()>,
894 ) -> Result
<Value
, Error
> {
896 self.send_request(request
, None
)
897 .and_then(move |response
| {
899 .map_err(Error
::from
)
900 .and_then(Self::h2api_response
)
907 request
: Request
<()>,
908 data
: Option
<bytes
::Bytes
>,
909 ) -> impl Future
<Output
= Result
<h2
::client
::ResponseFuture
, Error
>> {
913 .map_err(Error
::from
)
914 .and_then(move |mut send_request
| async
move {
915 if let Some(data
) = data
{
916 let (response
, stream
) = send_request
.send_request(request
, false).unwrap();
917 PipeToSendStream
::new(data
, stream
).await?
;
920 let (response
, _stream
) = send_request
.send_request(request
, true).unwrap();
926 pub async
fn h2api_response(
927 response
: Response
<h2
::RecvStream
>,
928 ) -> Result
<Value
, Error
> {
929 let status
= response
.status();
931 let (_head
, mut body
) = response
.into_parts();
933 let mut data
= Vec
::new();
934 while let Some(chunk
) = body
.data().await
{
936 // Whenever data is received, the caller is responsible for
937 // releasing capacity back to the server once it has freed
938 // the data from memory.
939 // Let the server send more data.
940 body
.flow_control().release_capacity(chunk
.len())?
;
944 let text
= String
::from_utf8(data
.to_vec()).unwrap();
945 if status
.is_success() {
949 let mut value
: Value
= serde_json
::from_str(&text
)?
;
950 if let Some(map
) = value
.as_object_mut() {
951 if let Some(data
) = map
.remove("data") {
955 bail
!("got result without data property");
958 Err(Error
::from(HttpError
::new(status
, text
)))
962 // Note: We always encode parameters with the url
963 pub fn request_builder(
967 param
: Option
<Value
>,
968 content_type
: Option
<&str>,
969 ) -> Result
<Request
<()>, Error
> {
970 let path
= path
.trim_matches('
/'
);
972 let content_type
= content_type
.unwrap_or("application/x-www-form-urlencoded");
974 if let Some(param
) = param
{
975 let query
= tools
::json_object_to_query(param
)?
;
976 // We detected problem with hyper around 6000 characters - seo we try to keep on the safe side
977 if query
.len() > 4096 { bail!("h2 query data too large ({} bytes
) - please encode data inside body
", query.len()); }
978 let url: Uri = format!("https
://{}:8007/{}?{}", server, path, query).parse()?;
979 let request
= Request
::builder()
982 .header("User-Agent", "proxmox-backup-client/1.0")
983 .header(hyper
::header
::CONTENT_TYPE
, content_type
)
987 let url
: Uri
= format
!("https://{}:8007/{}", server
, path
).parse()?
;
988 let request
= Request
::builder()
991 .header("User-Agent", "proxmox-backup-client/1.0")
992 .header(hyper
::header
::CONTENT_TYPE
, content_type
)