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}
;
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);
46 pub struct HttpClientOptions
{
47 prefix
: Option
<String
>,
48 password
: Option
<String
>,
49 fingerprint
: Option
<String
>,
52 fingerprint_cache
: bool
,
56 impl HttpClientOptions
{
58 pub fn new_interactive(password
: Option
<String
>, fingerprint
: Option
<String
>) -> Self {
62 fingerprint_cache
: true,
65 prefix
: Some("proxmox-backup".to_string()),
70 pub fn new_non_interactive(password
: String
, fingerprint
: Option
<String
>) -> Self {
72 password
: Some(password
),
78 pub fn prefix(mut self, prefix
: Option
<String
>) -> Self {
83 pub fn password(mut self, password
: Option
<String
>) -> Self {
84 self.password
= password
;
88 pub fn fingerprint(mut self, fingerprint
: Option
<String
>) -> Self {
89 self.fingerprint
= fingerprint
;
93 pub fn interactive(mut self, interactive
: bool
) -> Self {
94 self.interactive
= interactive
;
98 pub fn ticket_cache(mut self, ticket_cache
: bool
) -> Self {
99 self.ticket_cache
= ticket_cache
;
103 pub fn fingerprint_cache(mut self, fingerprint_cache
: bool
) -> Self {
104 self.fingerprint_cache
= fingerprint_cache
;
108 pub fn verify_cert(mut self, verify_cert
: bool
) -> Self {
109 self.verify_cert
= verify_cert
;
114 impl Default
for HttpClientOptions
{
115 fn default() -> Self {
122 fingerprint_cache
: false,
128 /// HTTP(S) API client
129 pub struct HttpClient
{
130 client
: Client
<HttpsConnector
>,
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
,
140 /// Delete stored ticket data (logout)
141 pub fn delete_ticket_info(prefix
: &str, server
: &str, username
: &Userid
) -> Result
<(), Error
> {
143 let base
= BaseDirectories
::with_prefix(prefix
)?
;
145 // usually /run/user/<uid>/...
146 let path
= base
.place_runtime_file("tickets")?
;
148 let mode
= nix
::sys
::stat
::Mode
::from_bits_truncate(0o0600);
150 let mut data
= file_get_json(&path
, Some(json
!({}
)))?
;
152 if let Some(map
) = data
[server
].as_object_mut() {
153 map
.remove(username
.as_str());
156 replace_file(path
, data
.to_string().as_bytes(), CreateOptions
::new().perm(mode
))?
;
161 fn store_fingerprint(prefix
: &str, server
: &str, fingerprint
: &str) -> Result
<(), Error
> {
163 let base
= BaseDirectories
::with_prefix(prefix
)?
;
165 // usually ~/.config/<prefix>/fingerprints
166 let path
= base
.place_config_file("fingerprints")?
;
168 let raw
= match std
::fs
::read_to_string(&path
) {
171 if err
.kind() == std
::io
::ErrorKind
::NotFound
{
174 bail
!("unable to read fingerprints from {:?} - {}", path
, err
);
179 let mut result
= String
::new();
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
187 result
.push_str(line
);
193 result
.push_str(server
);
195 result
.push_str(fingerprint
);
198 replace_file(path
, result
.as_bytes(), CreateOptions
::new())?
;
203 fn load_fingerprint(prefix
: &str, server
: &str) -> Option
<String
> {
205 let base
= BaseDirectories
::with_prefix(prefix
).ok()?
;
207 // usually ~/.config/<prefix>/fingerprints
208 let path
= base
.place_config_file("fingerprints").ok()?
;
210 let raw
= std
::fs
::read_to_string(&path
).ok()?
;
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());
222 fn store_ticket_info(prefix
: &str, server
: &str, username
: &str, ticket
: &str, token
: &str) -> Result
<(), Error
> {
224 let base
= BaseDirectories
::with_prefix(prefix
)?
;
226 // usually /run/user/<uid>/...
227 let path
= base
.place_runtime_file("tickets")?
;
229 let mode
= nix
::sys
::stat
::Mode
::from_bits_truncate(0o0600);
231 let mut data
= file_get_json(&path
, Some(json
!({}
)))?
;
233 let now
= proxmox
::tools
::time
::epoch_i64();
235 data
[server
][username
] = json
!({ "timestamp": now, "ticket": ticket, "token": token}
);
237 let mut new_data
= json
!({}
);
239 let ticket_lifetime
= tools
::ticket
::TICKET_LIFETIME
- 60;
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();
253 replace_file(path
, new_data
.to_string().as_bytes(), CreateOptions
::new().perm(mode
))?
;
258 fn load_ticket_info(prefix
: &str, server
: &str, userid
: &Userid
) -> Option
<(String
, String
)> {
259 let base
= BaseDirectories
::with_prefix(prefix
).ok()?
;
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
;
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()))
279 fn build_uri(server
: &str, port
: u16, path
: &str, query
: Option
<String
>) -> Result
<Uri
, Error
> {
282 .authority(build_authority(server
, port
)?
)
283 .path_and_query(match query
{
284 Some(query
) => format
!("/{}?{}", path
, query
),
285 None
=> format
!("/{}", path
),
288 .map_err(|err
| format_err
!("error building uri - {}", err
))
296 mut options
: HttpClientOptions
,
297 ) -> Result
<Self, Error
> {
299 let verified_fingerprint
= Arc
::new(Mutex
::new(None
));
301 let mut expected_fingerprint
= options
.fingerprint
.take();
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
);
310 let mut ssl_connector_builder
= SslConnector
::builder(SslMethod
::tls()).unwrap();
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
);
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
);
328 *verified_fingerprint
.lock().unwrap() = Some(fingerprint
);
334 ssl_connector_builder
.set_verify(openssl
::ssl
::SslVerifyMode
::NONE
);
337 let mut httpc
= HttpConnector
::new();
338 httpc
.set_nodelay(true); // important for h2 download performance!
339 httpc
.enforce_http(false); // we want https...
341 httpc
.set_connect_timeout(Some(std
::time
::Duration
::new(10, 0)));
342 let https
= HttpsConnector
::with_connector(httpc
, ssl_connector_builder
.build());
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
);
349 let password
= options
.password
.take();
350 let use_ticket_cache
= options
.ticket_cache
&& options
.prefix
.is_some();
352 let password
= if let Some(password
) = password
{
355 let userid
= if auth_id
.is_token() {
356 bail
!("API token secret must be provided!");
360 let mut ticket_info
= None
;
361 if use_ticket_cache
{
362 ticket_info
= load_ticket_info(options
.prefix
.as_ref().unwrap(), server
, userid
);
364 if let Some((ticket
, _token
)) = ticket_info
{
367 Self::get_password(userid
, options
.interactive
)?
371 let auth
= Arc
::new(RwLock
::new(AuthInfo
{
372 auth_id
: auth_id
.clone(),
373 ticket
: password
.clone(),
374 token
: "".to_string(),
377 let server2
= server
.to_string();
378 let client2
= client
.clone();
379 let auth2
= auth
.clone();
380 let prefix2
= options
.prefix
.clone();
382 let renewal_future
= async
move {
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
)
389 match Self::credentials(client2
.clone(), server2
.clone(), port
, auth_id
.user().clone(), ticket
).await
{
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
);
394 *auth2
.write().unwrap() = auth
;
397 eprintln
!("re-authentication failed: {}", err
);
404 let (renewal_future
, ticket_abort
) = futures
::future
::abortable(renewal_future
);
406 let login_future
= Self::credentials(
410 auth_id
.user().clone(),
413 let server
= server
.to_string();
414 let prefix
= options
.prefix
.clone();
415 let authinfo
= auth
.clone();
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
);
421 *authinfo
.write().unwrap() = auth
;
422 tokio
::spawn(renewal_future
);
426 let first_auth
= if auth_id
.is_token() {
427 // TODO check access here?
430 Some(BroadcastFuture
::new(Box
::new(login_future
)))
435 server
: String
::from(server
),
437 fingerprint
: verified_fingerprint
,
447 /// Login is done on demand, so this is only required if you need
448 /// access to authentication data in 'AuthInfo'.
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?
;
457 let authinfo
= self.auth
.read().unwrap();
461 /// Returns the optional fingerprint passed to the new() constructor.
462 pub fn fingerprint(&self) -> Option
<String
> {
463 (*self.fingerprint
.lock().unwrap()).clone()
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
)?
)?
);
473 bail
!("no password input mechanism available");
478 ctx
: &mut X509StoreContextRef
,
479 expected_fingerprint
: Option
<&String
>,
481 ) -> (bool
, Option
<String
>) {
482 if valid { return (true, None); }
484 let cert
= match ctx
.current_cert() {
486 None
=> return (false, None
),
489 let depth
= ctx
.error_depth();
490 if depth
!= 0 { return (false, None); }
492 let fp
= match cert
.digest(openssl
::hash
::MessageDigest
::sha256()) {
494 Err(_
) => return (false, None
), // should not happen
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(":");
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
));
505 eprintln
!("WARNING: certificate fingerprint does not match expected fingerprint!");
506 eprintln
!("expected: {}", expected_fingerprint
);
510 // If we're on a TTY, query the user
511 if interactive
&& tty
::stdin_isatty() {
512 println
!("fingerprint: {}", fp_string
);
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
) {
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
);
529 Err(_
) => return (false, None
),
536 pub async
fn request(&self, mut req
: Request
<Body
>) -> Result
<Value
, Error
> {
538 let client
= self.client
.clone();
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());
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());
550 Self::api_request(client
, req
).await
557 ) -> Result
<Value
, Error
> {
558 let req
= Self::request_builder(&self.server
, self.port
, "GET", path
, data
)?
;
559 self.request(req
).await
566 ) -> Result
<Value
, Error
> {
567 let req
= Self::request_builder(&self.server
, self.port
, "DELETE", path
, data
)?
;
568 self.request(req
).await
575 ) -> Result
<Value
, Error
> {
576 let req
= Self::request_builder(&self.server
, self.port
, "POST", path
, data
)?
;
577 self.request(req
).await
584 ) -> Result
<Value
, Error
> {
585 let req
= Self::request_builder(&self.server
, self.port
, "PUT", path
, data
)?
;
586 self.request(req
).await
589 pub async
fn download(
592 output
: &mut (dyn Write
+ Send
),
593 ) -> Result
<(), Error
> {
594 let mut req
= Self::request_builder(&self.server
, self.port
, "GET", path
, None
)?
;
596 let client
= self.client
.clone();
598 let auth
= self.login().await?
;
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());
603 let resp
= tokio
::time
::timeout(
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")))
616 .map_err(Error
::from
)
617 .try_fold(output
, move |acc
, chunk
| async
move {
618 acc
.write_all(&chunk
)?
;
632 ) -> Result
<Value
, Error
> {
634 let query
= match data
{
635 Some(data
) => Some(tools
::json_object_to_query(data
)?
),
638 let url
= build_uri(&self.server
, self.port
, path
, query
)?
;
640 let req
= Request
::builder()
643 .header("User-Agent", "proxmox-backup-client/1.0")
644 .header("Content-Type", content_type
)
645 .body(body
).unwrap();
647 self.request(req
).await
650 pub async
fn start_h2_connection(
652 mut req
: Request
<Body
>,
653 protocol_name
: String
,
654 ) -> Result
<(H2Client
, futures
::future
::AbortHandle
), Error
> {
656 let client
= self.client
.clone();
657 let auth
= self.login().await?
;
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());
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());
668 req
.headers_mut().insert("UPGRADE", HeaderValue
::from_str(&protocol_name
).unwrap());
670 let resp
= tokio
::time
::timeout(
675 .map_err(|_
| format_err
!("http upgrade request timed out"))??
;
676 let status
= resp
.status();
678 if status
!= http
::StatusCode
::SWITCHING_PROTOCOLS
{
679 Self::api_response(resp
).await?
;
680 bail
!("unknown error");
683 let upgraded
= hyper
::upgrade
::on(resp
).await?
;
685 let max_window_size
= (1 << 31) - 2;
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)
694 let connection
= connection
695 .map_err(|_
| eprintln
!("HTTP/2.0 connection failed"));
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(|_
| ());
703 // Spawn a new task to drive the connection state
704 tokio
::spawn(connection
);
706 // Wait until the `SendRequest` handle has available capacity.
707 let c
= h2
.ready().await?
;
708 Ok((H2Client
::new(c
), abort
))
711 async
fn credentials(
712 client
: Client
<HttpsConnector
>,
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(),
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?
;
734 let text
= String
::from_utf8(data
.to_vec()).unwrap();
735 if status
.is_success() {
739 let value
: Value
= serde_json
::from_str(&text
)?
;
743 Err(Error
::from(HttpError
::new(status
, text
)))
747 async
fn api_request(
748 client
: Client
<HttpsConnector
>,
750 ) -> Result
<Value
, Error
> {
753 tokio
::time
::timeout(
758 .map_err(|_
| format_err
!("http request timed out"))??
762 // Read-only access to server property
763 pub fn server(&self) -> &str {
767 pub fn port(&self) -> u16 {
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()
778 .header("User-Agent", "proxmox-backup-client/1.0")
779 .header(hyper
::header
::CONTENT_TYPE
, "application/json")
780 .body(Body
::from(data
.to_string()))?
;
783 let query
= tools
::json_object_to_query(data
)?
;
784 let url
= build_uri(server
, port
, path
, Some(query
))?
;
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())?
;
794 let url
= build_uri(server
, port
, path
, None
)?
;
795 let request
= Request
::builder()
798 .header("User-Agent", "proxmox-backup-client/1.0")
799 .header(hyper
::header
::CONTENT_TYPE
, "application/x-www-form-urlencoded")
800 .body(Body
::empty())?
;
807 impl Drop
for HttpClient
{
809 self.ticket_abort
.abort();
815 pub struct H2Client
{
816 h2
: h2
::client
::SendRequest
<bytes
::Bytes
>,
821 pub fn new(h2
: h2
::client
::SendRequest
<bytes
::Bytes
>) -> Self {
829 ) -> Result
<Value
, Error
> {
830 let req
= Self::request_builder("localhost", "GET", path
, param
, None
).unwrap();
831 self.request(req
).await
838 ) -> Result
<Value
, Error
> {
839 let req
= Self::request_builder("localhost", "PUT", path
, param
, None
).unwrap();
840 self.request(req
).await
847 ) -> Result
<Value
, Error
> {
848 let req
= Self::request_builder("localhost", "POST", path
, param
, None
).unwrap();
849 self.request(req
).await
852 pub async
fn download
<W
: Write
+ Send
>(
855 param
: Option
<Value
>,
857 ) -> Result
<(), Error
> {
858 let request
= Self::request_builder("localhost", "GET", path
, param
, None
).unwrap();
860 let response_future
= self.send_request(request
, None
).await?
;
862 let resp
= response_future
.await?
;
864 let status
= resp
.status();
865 if !status
.is_success() {
866 H2Client
::h2api_response(resp
).await?
; // raise error
870 let mut body
= resp
.into_body();
871 while let Some(chunk
) = body
.data().await
{
873 body
.flow_control().release_capacity(chunk
.len())?
;
874 output
.write_all(&chunk
)?
;
882 method
: &str, // POST or PUT
884 param
: Option
<Value
>,
887 ) -> Result
<Value
, Error
> {
888 let request
= Self::request_builder("localhost", method
, path
, param
, Some(content_type
)).unwrap();
890 let mut send_request
= self.h2
.clone().ready().await?
;
892 let (response
, stream
) = send_request
.send_request(request
, false).unwrap();
894 PipeToSendStream
::new(bytes
::Bytes
::from(data
), stream
).await?
;
897 .map_err(Error
::from
)
898 .and_then(Self::h2api_response
)
904 request
: Request
<()>,
905 ) -> Result
<Value
, Error
> {
907 self.send_request(request
, None
)
908 .and_then(move |response
| {
910 .map_err(Error
::from
)
911 .and_then(Self::h2api_response
)
918 request
: Request
<()>,
919 data
: Option
<bytes
::Bytes
>,
920 ) -> impl Future
<Output
= Result
<h2
::client
::ResponseFuture
, Error
>> {
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?
;
931 let (response
, _stream
) = send_request
.send_request(request
, true).unwrap();
937 pub async
fn h2api_response(
938 response
: Response
<h2
::RecvStream
>,
939 ) -> Result
<Value
, Error
> {
940 let status
= response
.status();
942 let (_head
, mut body
) = response
.into_parts();
944 let mut data
= Vec
::new();
945 while let Some(chunk
) = body
.data().await
{
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())?
;
955 let text
= String
::from_utf8(data
.to_vec()).unwrap();
956 if status
.is_success() {
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") {
966 bail
!("got result without data property");
969 Err(Error
::from(HttpError
::new(status
, text
)))
973 // Note: We always encode parameters with the url
974 pub fn request_builder(
978 param
: Option
<Value
>,
979 content_type
: Option
<&str>,
980 ) -> Result
<Request
<()>, Error
> {
981 let path
= path
.trim_matches('
/'
);
983 let content_type
= content_type
.unwrap_or("application/x-www-form-urlencoded");
984 let query
= match 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());
996 let url
= build_uri(server
, 8007, path
, query
)?
;
997 let request
= Request
::builder()
1000 .header("User-Agent", "proxmox-backup-client/1.0")
1001 .header(hyper
::header
::CONTENT_TYPE
, content_type
)