2 use std
::task
::{Context, Poll}
;
3 use std
::sync
::{Arc, Mutex, RwLock}
;
4 use std
::time
::Duration
;
6 use anyhow
::{bail, format_err, Error}
;
9 use http
::header
::HeaderValue
;
10 use http
::{Request, Response}
;
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
;
19 api
::error
::HttpError
,
22 fs
::{file_get_json, replace_file, CreateOptions}
,
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}
;
38 pub struct HttpClientOptions
{
39 prefix
: Option
<String
>,
40 password
: Option
<String
>,
41 fingerprint
: Option
<String
>,
44 fingerprint_cache
: bool
,
48 impl HttpClientOptions
{
50 pub fn new() -> Self {
57 fingerprint_cache
: false,
62 pub fn prefix(mut self, prefix
: Option
<String
>) -> Self {
67 pub fn password(mut self, password
: Option
<String
>) -> Self {
68 self.password
= password
;
72 pub fn fingerprint(mut self, fingerprint
: Option
<String
>) -> Self {
73 self.fingerprint
= fingerprint
;
77 pub fn interactive(mut self, interactive
: bool
) -> Self {
78 self.interactive
= interactive
;
82 pub fn ticket_cache(mut self, ticket_cache
: bool
) -> Self {
83 self.ticket_cache
= ticket_cache
;
87 pub fn fingerprint_cache(mut self, fingerprint_cache
: bool
) -> Self {
88 self.fingerprint_cache
= fingerprint_cache
;
92 pub fn verify_cert(mut self, verify_cert
: bool
) -> Self {
93 self.verify_cert
= verify_cert
;
98 /// HTTP(S) API client
99 pub struct HttpClient
{
100 client
: Client
<HttpsConnector
>,
103 fingerprint
: Arc
<Mutex
<Option
<String
>>>,
104 first_auth
: BroadcastFuture
<()>,
105 auth
: Arc
<RwLock
<AuthInfo
>>,
106 ticket_abort
: futures
::future
::AbortHandle
,
107 _options
: HttpClientOptions
,
110 /// Delete stored ticket data (logout)
111 pub fn delete_ticket_info(prefix
: &str, server
: &str, username
: &Userid
) -> Result
<(), Error
> {
113 let base
= BaseDirectories
::with_prefix(prefix
)?
;
115 // usually /run/user/<uid>/...
116 let path
= base
.place_runtime_file("tickets")?
;
118 let mode
= nix
::sys
::stat
::Mode
::from_bits_truncate(0o0600);
120 let mut data
= file_get_json(&path
, Some(json
!({}
)))?
;
122 if let Some(map
) = data
[server
].as_object_mut() {
123 map
.remove(username
.as_str());
126 replace_file(path
, data
.to_string().as_bytes(), CreateOptions
::new().perm(mode
))?
;
131 fn store_fingerprint(prefix
: &str, server
: &str, fingerprint
: &str) -> Result
<(), Error
> {
133 let base
= BaseDirectories
::with_prefix(prefix
)?
;
135 // usually ~/.config/<prefix>/fingerprints
136 let path
= base
.place_config_file("fingerprints")?
;
138 let raw
= match std
::fs
::read_to_string(&path
) {
141 if err
.kind() == std
::io
::ErrorKind
::NotFound
{
144 bail
!("unable to read fingerprints from {:?} - {}", path
, err
);
149 let mut result
= String
::new();
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
157 result
.push_str(line
);
163 result
.push_str(server
);
165 result
.push_str(fingerprint
);
168 replace_file(path
, result
.as_bytes(), CreateOptions
::new())?
;
173 fn load_fingerprint(prefix
: &str, server
: &str) -> Option
<String
> {
175 let base
= BaseDirectories
::with_prefix(prefix
).ok()?
;
177 // usually ~/.config/<prefix>/fingerprints
178 let path
= base
.place_config_file("fingerprints").ok()?
;
180 let raw
= std
::fs
::read_to_string(&path
).ok()?
;
182 for line
in raw
.split('
\n'
) {
183 let items
: Vec
<String
> = line
.split_whitespace().map(String
::from
).collect();
184 if items
.len() == 2 {
185 if &items
[0] == server
{
186 return Some(items
[1].clone());
194 fn store_ticket_info(prefix
: &str, server
: &str, username
: &str, ticket
: &str, token
: &str) -> Result
<(), Error
> {
196 let base
= BaseDirectories
::with_prefix(prefix
)?
;
198 // usually /run/user/<uid>/...
199 let path
= base
.place_runtime_file("tickets")?
;
201 let mode
= nix
::sys
::stat
::Mode
::from_bits_truncate(0o0600);
203 let mut data
= file_get_json(&path
, Some(json
!({}
)))?
;
205 let now
= proxmox
::tools
::time
::epoch_i64();
207 data
[server
][username
] = json
!({ "timestamp": now, "ticket": ticket, "token": token}
);
209 let mut new_data
= json
!({}
);
211 let ticket_lifetime
= tools
::ticket
::TICKET_LIFETIME
- 60;
213 let empty
= serde_json
::map
::Map
::new();
214 for (server
, info
) in data
.as_object().unwrap_or(&empty
) {
215 for (_user
, uinfo
) in info
.as_object().unwrap_or(&empty
) {
216 if let Some(timestamp
) = uinfo
["timestamp"].as_i64() {
217 let age
= now
- timestamp
;
218 if age
< ticket_lifetime
{
219 new_data
[server
][username
] = uinfo
.clone();
225 replace_file(path
, new_data
.to_string().as_bytes(), CreateOptions
::new().perm(mode
))?
;
230 fn load_ticket_info(prefix
: &str, server
: &str, userid
: &Userid
) -> Option
<(String
, String
)> {
231 let base
= BaseDirectories
::with_prefix(prefix
).ok()?
;
233 // usually /run/user/<uid>/...
234 let path
= base
.place_runtime_file("tickets").ok()?
;
235 let data
= file_get_json(&path
, None
).ok()?
;
236 let now
= proxmox
::tools
::time
::epoch_i64();
237 let ticket_lifetime
= tools
::ticket
::TICKET_LIFETIME
- 60;
238 let uinfo
= data
[server
][userid
.as_str()].as_object()?
;
239 let timestamp
= uinfo
["timestamp"].as_i64()?
;
240 let age
= now
- timestamp
;
242 if age
< ticket_lifetime
{
243 let ticket
= uinfo
["ticket"].as_str()?
;
244 let token
= uinfo
["token"].as_str()?
;
245 Some((ticket
.to_owned(), token
.to_owned()))
256 mut options
: HttpClientOptions
,
257 ) -> Result
<Self, Error
> {
259 let verified_fingerprint
= Arc
::new(Mutex
::new(None
));
261 let mut fingerprint
= options
.fingerprint
.take();
263 if fingerprint
.is_some() {
264 // do not store fingerprints passed via options in cache
265 options
.fingerprint_cache
= false;
266 } else if options
.fingerprint_cache
&& options
.prefix
.is_some() {
267 fingerprint
= load_fingerprint(options
.prefix
.as_ref().unwrap(), server
);
270 let mut ssl_connector_builder
= SslConnector
::builder(SslMethod
::tls()).unwrap();
272 if options
.verify_cert
{
273 let server
= server
.to_string();
274 let verified_fingerprint
= verified_fingerprint
.clone();
275 let interactive
= options
.interactive
;
276 let fingerprint_cache
= options
.fingerprint_cache
;
277 let prefix
= options
.prefix
.clone();
278 ssl_connector_builder
.set_verify_callback(openssl
::ssl
::SslVerifyMode
::PEER
, move |valid
, ctx
| {
279 let (valid
, fingerprint
) = Self::verify_callback(valid
, ctx
, fingerprint
.clone(), interactive
);
281 if let Some(fingerprint
) = fingerprint
{
282 if fingerprint_cache
&& prefix
.is_some() {
283 if let Err(err
) = store_fingerprint(
284 prefix
.as_ref().unwrap(), &server
, &fingerprint
) {
285 eprintln
!("{}", err
);
288 *verified_fingerprint
.lock().unwrap() = Some(fingerprint
);
294 ssl_connector_builder
.set_verify(openssl
::ssl
::SslVerifyMode
::NONE
);
297 let mut httpc
= hyper
::client
::HttpConnector
::new();
298 httpc
.set_nodelay(true); // important for h2 download performance!
299 httpc
.enforce_http(false); // we want https...
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 mut ticket_info
= None
;
315 if use_ticket_cache
{
316 ticket_info
= load_ticket_info(options
.prefix
.as_ref().unwrap(), server
, userid
);
318 if let Some((ticket
, _token
)) = ticket_info
{
321 Self::get_password(userid
, options
.interactive
)?
325 let auth
= Arc
::new(RwLock
::new(AuthInfo
{
326 userid
: userid
.clone(),
327 ticket
: password
.clone(),
328 token
: "".to_string(),
331 let server2
= server
.to_string();
332 let client2
= client
.clone();
333 let auth2
= auth
.clone();
334 let prefix2
= options
.prefix
.clone();
336 let renewal_future
= async
move {
338 tokio
::time
::delay_for(Duration
::new(60*15, 0)).await
; // 15 minutes
339 let (userid
, ticket
) = {
340 let authinfo
= auth2
.read().unwrap().clone();
341 (authinfo
.userid
, authinfo
.ticket
)
343 match Self::credentials(client2
.clone(), server2
.clone(), port
, userid
, ticket
).await
{
345 if use_ticket_cache
& &prefix2
.is_some() {
346 let _
= store_ticket_info(prefix2
.as_ref().unwrap(), &server2
, &auth
.userid
.to_string(), &auth
.ticket
, &auth
.token
);
348 *auth2
.write().unwrap() = auth
;
351 eprintln
!("re-authentication failed: {}", err
);
358 let (renewal_future
, ticket_abort
) = futures
::future
::abortable(renewal_future
);
360 let login_future
= Self::credentials(
367 let server
= server
.to_string();
368 let prefix
= options
.prefix
.clone();
369 let authinfo
= auth
.clone();
372 if use_ticket_cache
& &prefix
.is_some() {
373 let _
= store_ticket_info(prefix
.as_ref().unwrap(), &server
, &auth
.userid
.to_string(), &auth
.ticket
, &auth
.token
);
375 *authinfo
.write().unwrap() = auth
;
376 tokio
::spawn(renewal_future
);
382 server
: String
::from(server
),
384 fingerprint
: verified_fingerprint
,
387 first_auth
: BroadcastFuture
::new(Box
::new(login_future
)),
394 /// Login is done on demand, so this is only required if you need
395 /// access to authentication data in 'AuthInfo'.
396 pub async
fn login(&self) -> Result
<AuthInfo
, Error
> {
397 self.first_auth
.listen().await?
;
398 let authinfo
= self.auth
.read().unwrap();
402 /// Returns the optional fingerprint passed to the new() constructor.
403 pub fn fingerprint(&self) -> Option
<String
> {
404 (*self.fingerprint
.lock().unwrap()).clone()
407 fn get_password(username
: &Userid
, interactive
: bool
) -> Result
<String
, Error
> {
408 // If we're on a TTY, query the user for a password
409 if interactive
&& tty
::stdin_isatty() {
410 let msg
= format
!("Password for \"{}\": ", username
);
411 return Ok(String
::from_utf8(tty
::read_password(&msg
)?
)?
);
414 bail
!("no password input mechanism available");
419 &mut X509StoreContextRef
,
420 expected_fingerprint
: Option
<String
>,
422 ) -> (bool
, Option
<String
>) {
423 if valid { return (true, None); }
425 let cert
= match ctx
.current_cert() {
427 None
=> return (false, None
),
430 let depth
= ctx
.error_depth();
431 if depth
!= 0 { return (false, None); }
433 let fp
= match cert
.digest(openssl
::hash
::MessageDigest
::sha256()) {
435 Err(_
) => return (false, None
), // should not happen
437 let fp_string
= proxmox
::tools
::digest_to_hex(&fp
);
438 let fp_string
= fp_string
.as_bytes().chunks(2).map(|v
| std
::str::from_utf8(v
).unwrap())
439 .collect
::<Vec
<&str>>().join(":");
441 if let Some(expected_fingerprint
) = expected_fingerprint
{
442 if expected_fingerprint
.to_lowercase() == fp_string
{
443 return (true, Some(fp_string
));
445 return (false, None
);
449 // If we're on a TTY, query the user
450 if interactive
&& tty
::stdin_isatty() {
451 println
!("fingerprint: {}", fp_string
);
453 print
!("Are you sure you want to continue connecting? (y/n): ");
454 let _
= std
::io
::stdout().flush();
455 use std
::io
::{BufRead, BufReader}
;
456 let mut line
= String
::new();
457 match BufReader
::new(std
::io
::stdin()).read_line(&mut line
) {
459 let trimmed
= line
.trim();
460 if trimmed
== "y" || trimmed
== "Y" {
461 return (true, Some(fp_string
));
462 } else if trimmed
== "n" || trimmed
== "N" {
463 return (false, None
);
468 Err(_
) => return (false, None
),
475 pub async
fn request(&self, mut req
: Request
<Body
>) -> Result
<Value
, Error
> {
477 let client
= self.client
.clone();
479 let auth
= self.login().await?
;
481 let enc_ticket
= format
!("PBSAuthCookie={}", percent_encode(auth
.ticket
.as_bytes(), DEFAULT_ENCODE_SET
));
482 req
.headers_mut().insert("Cookie", HeaderValue
::from_str(&enc_ticket
).unwrap());
483 req
.headers_mut().insert("CSRFPreventionToken", HeaderValue
::from_str(&auth
.token
).unwrap());
485 Self::api_request(client
, req
).await
492 ) -> Result
<Value
, Error
> {
493 let req
= Self::request_builder(&self.server
, self.port
, "GET", path
, data
)?
;
494 self.request(req
).await
501 ) -> Result
<Value
, Error
> {
502 let req
= Self::request_builder(&self.server
, self.port
, "DELETE", path
, data
)?
;
503 self.request(req
).await
510 ) -> Result
<Value
, Error
> {
511 let req
= Self::request_builder(&self.server
, self.port
, "POST", path
, data
)?
;
512 self.request(req
).await
515 pub async
fn download(
518 output
: &mut (dyn Write
+ Send
),
519 ) -> Result
<(), Error
> {
520 let mut req
= Self::request_builder(&self.server
, self.port
, "GET", path
, None
)?
;
522 let client
= self.client
.clone();
524 let auth
= self.login().await?
;
526 let enc_ticket
= format
!("PBSAuthCookie={}", percent_encode(auth
.ticket
.as_bytes(), DEFAULT_ENCODE_SET
));
527 req
.headers_mut().insert("Cookie", HeaderValue
::from_str(&enc_ticket
).unwrap());
529 let resp
= client
.request(req
).await?
;
530 let status
= resp
.status();
531 if !status
.is_success() {
532 HttpClient
::api_response(resp
)
533 .map(|_
| Err(format_err
!("unknown error")))
537 .map_err(Error
::from
)
538 .try_fold(output
, move |acc
, chunk
| async
move {
539 acc
.write_all(&chunk
)?
;
553 ) -> Result
<Value
, Error
> {
555 let path
= path
.trim_matches('
/'
);
556 let mut url
= format
!("https://{}:{}/{}", &self.server
, self.port
, path
);
558 if let Some(data
) = data
{
559 let query
= tools
::json_object_to_query(data
).unwrap();
561 url
.push_str(&query
);
564 let url
: Uri
= url
.parse().unwrap();
566 let req
= Request
::builder()
569 .header("User-Agent", "proxmox-backup-client/1.0")
570 .header("Content-Type", content_type
)
571 .body(body
).unwrap();
573 self.request(req
).await
576 pub async
fn start_h2_connection(
578 mut req
: Request
<Body
>,
579 protocol_name
: String
,
580 ) -> Result
<(H2Client
, futures
::future
::AbortHandle
), Error
> {
582 let auth
= self.login().await?
;
583 let client
= self.client
.clone();
585 let enc_ticket
= format
!("PBSAuthCookie={}", percent_encode(auth
.ticket
.as_bytes(), DEFAULT_ENCODE_SET
));
586 req
.headers_mut().insert("Cookie", HeaderValue
::from_str(&enc_ticket
).unwrap());
587 req
.headers_mut().insert("UPGRADE", HeaderValue
::from_str(&protocol_name
).unwrap());
589 let resp
= client
.request(req
).await?
;
590 let status
= resp
.status();
592 if status
!= http
::StatusCode
::SWITCHING_PROTOCOLS
{
593 Self::api_response(resp
).await?
;
594 bail
!("unknown error");
602 let max_window_size
= (1 << 31) - 2;
604 let (h2
, connection
) = h2
::client
::Builder
::new()
605 .initial_connection_window_size(max_window_size
)
606 .initial_window_size(max_window_size
)
607 .max_frame_size(4*1024*1024)
611 let connection
= connection
612 .map_err(|_
| panic
!("HTTP/2.0 connection failed"));
614 let (connection
, abort
) = futures
::future
::abortable(connection
);
615 // A cancellable future returns an Option which is None when cancelled and
616 // Some when it finished instead, since we don't care about the return type we
617 // need to map it away:
618 let connection
= connection
.map(|_
| ());
620 // Spawn a new task to drive the connection state
621 tokio
::spawn(connection
);
623 // Wait until the `SendRequest` handle has available capacity.
624 let c
= h2
.ready().await?
;
625 Ok((H2Client
::new(c
), abort
))
628 async
fn credentials(
629 client
: Client
<HttpsConnector
>,
634 ) -> Result
<AuthInfo
, Error
> {
635 let data
= json
!({ "username": username, "password": password }
);
636 let req
= Self::request_builder(&server
, port
, "POST", "/api2/json/access/ticket", Some(data
))?
;
637 let cred
= Self::api_request(client
, req
).await?
;
638 let auth
= AuthInfo
{
639 userid
: cred
["data"]["username"].as_str().unwrap().parse()?
,
640 ticket
: cred
["data"]["ticket"].as_str().unwrap().to_owned(),
641 token
: cred
["data"]["CSRFPreventionToken"].as_str().unwrap().to_owned(),
647 async
fn api_response(response
: Response
<Body
>) -> Result
<Value
, Error
> {
648 let status
= response
.status();
649 let data
= hyper
::body
::to_bytes(response
.into_body()).await?
;
651 let text
= String
::from_utf8(data
.to_vec()).unwrap();
652 if status
.is_success() {
656 let value
: Value
= serde_json
::from_str(&text
)?
;
660 Err(Error
::from(HttpError
::new(status
, text
)))
664 async
fn api_request(
665 client
: Client
<HttpsConnector
>,
667 ) -> Result
<Value
, Error
> {
670 .map_err(Error
::from
)
671 .and_then(Self::api_response
)
675 // Read-only access to server property
676 pub fn server(&self) -> &str {
680 pub fn port(&self) -> u16 {
684 pub fn request_builder(server
: &str, port
: u16, method
: &str, path
: &str, data
: Option
<Value
>) -> Result
<Request
<Body
>, Error
> {
685 let path
= path
.trim_matches('
/'
);
686 let url
: Uri
= format
!("https://{}:{}/{}", server
, port
, path
).parse()?
;
688 if let Some(data
) = data
{
689 if method
== "POST" {
690 let request
= Request
::builder()
693 .header("User-Agent", "proxmox-backup-client/1.0")
694 .header(hyper
::header
::CONTENT_TYPE
, "application/json")
695 .body(Body
::from(data
.to_string()))?
;
698 let query
= tools
::json_object_to_query(data
)?
;
699 let url
: Uri
= format
!("https://{}:{}/{}?{}", server
, port
, path
, query
).parse()?
;
700 let request
= Request
::builder()
703 .header("User-Agent", "proxmox-backup-client/1.0")
704 .header(hyper
::header
::CONTENT_TYPE
, "application/x-www-form-urlencoded")
705 .body(Body
::empty())?
;
710 let request
= Request
::builder()
713 .header("User-Agent", "proxmox-backup-client/1.0")
714 .header(hyper
::header
::CONTENT_TYPE
, "application/x-www-form-urlencoded")
715 .body(Body
::empty())?
;
721 impl Drop
for HttpClient
{
723 self.ticket_abort
.abort();
729 pub struct H2Client
{
730 h2
: h2
::client
::SendRequest
<bytes
::Bytes
>,
735 pub fn new(h2
: h2
::client
::SendRequest
<bytes
::Bytes
>) -> Self {
743 ) -> Result
<Value
, Error
> {
744 let req
= Self::request_builder("localhost", "GET", path
, param
, None
).unwrap();
745 self.request(req
).await
752 ) -> Result
<Value
, Error
> {
753 let req
= Self::request_builder("localhost", "PUT", path
, param
, None
).unwrap();
754 self.request(req
).await
761 ) -> Result
<Value
, Error
> {
762 let req
= Self::request_builder("localhost", "POST", path
, param
, None
).unwrap();
763 self.request(req
).await
766 pub async
fn download
<W
: Write
+ Send
>(
769 param
: Option
<Value
>,
771 ) -> Result
<(), Error
> {
772 let request
= Self::request_builder("localhost", "GET", path
, param
, None
).unwrap();
774 let response_future
= self.send_request(request
, None
).await?
;
776 let resp
= response_future
.await?
;
778 let status
= resp
.status();
779 if !status
.is_success() {
780 H2Client
::h2api_response(resp
).await?
; // raise error
784 let mut body
= resp
.into_body();
785 while let Some(chunk
) = body
.data().await
{
787 body
.flow_control().release_capacity(chunk
.len())?
;
788 output
.write_all(&chunk
)?
;
796 method
: &str, // POST or PUT
798 param
: Option
<Value
>,
801 ) -> Result
<Value
, Error
> {
802 let request
= Self::request_builder("localhost", method
, path
, param
, Some(content_type
)).unwrap();
804 let mut send_request
= self.h2
.clone().ready().await?
;
806 let (response
, stream
) = send_request
.send_request(request
, false).unwrap();
808 PipeToSendStream
::new(bytes
::Bytes
::from(data
), stream
).await?
;
811 .map_err(Error
::from
)
812 .and_then(Self::h2api_response
)
818 request
: Request
<()>,
819 ) -> Result
<Value
, Error
> {
821 self.send_request(request
, None
)
822 .and_then(move |response
| {
824 .map_err(Error
::from
)
825 .and_then(Self::h2api_response
)
832 request
: Request
<()>,
833 data
: Option
<bytes
::Bytes
>,
834 ) -> impl Future
<Output
= Result
<h2
::client
::ResponseFuture
, Error
>> {
838 .map_err(Error
::from
)
839 .and_then(move |mut send_request
| async
move {
840 if let Some(data
) = data
{
841 let (response
, stream
) = send_request
.send_request(request
, false).unwrap();
842 PipeToSendStream
::new(data
, stream
).await?
;
845 let (response
, _stream
) = send_request
.send_request(request
, true).unwrap();
851 pub async
fn h2api_response(
852 response
: Response
<h2
::RecvStream
>,
853 ) -> Result
<Value
, Error
> {
854 let status
= response
.status();
856 let (_head
, mut body
) = response
.into_parts();
858 let mut data
= Vec
::new();
859 while let Some(chunk
) = body
.data().await
{
861 // Whenever data is received, the caller is responsible for
862 // releasing capacity back to the server once it has freed
863 // the data from memory.
864 // Let the server send more data.
865 body
.flow_control().release_capacity(chunk
.len())?
;
869 let text
= String
::from_utf8(data
.to_vec()).unwrap();
870 if status
.is_success() {
874 let mut value
: Value
= serde_json
::from_str(&text
)?
;
875 if let Some(map
) = value
.as_object_mut() {
876 if let Some(data
) = map
.remove("data") {
880 bail
!("got result without data property");
883 Err(Error
::from(HttpError
::new(status
, text
)))
887 // Note: We always encode parameters with the url
888 pub fn request_builder(
892 param
: Option
<Value
>,
893 content_type
: Option
<&str>,
894 ) -> Result
<Request
<()>, Error
> {
895 let path
= path
.trim_matches('
/'
);
897 let content_type
= content_type
.unwrap_or("application/x-www-form-urlencoded");
899 if let Some(param
) = param
{
900 let query
= tools
::json_object_to_query(param
)?
;
901 // We detected problem with hyper around 6000 characters - seo we try to keep on the safe side
902 if query
.len() > 4096 { bail!("h2 query data too large ({} bytes
) - please encode data inside body
", query.len()); }
903 let url: Uri = format!("https
://{}:8007/{}?{}", server, path, query).parse()?;
904 let request
= Request
::builder()
907 .header("User-Agent", "proxmox-backup-client/1.0")
908 .header(hyper
::header
::CONTENT_TYPE
, content_type
)
912 let url
: Uri
= format
!("https://{}:8007/{}", server
, path
).parse()?
;
913 let request
= Request
::builder()
916 .header("User-Agent", "proxmox-backup-client/1.0")
917 .header(hyper
::header
::CONTENT_TYPE
, content_type
)
926 pub struct HttpsConnector
{
928 ssl_connector
: std
::sync
::Arc
<SslConnector
>,
931 impl HttpsConnector
{
932 pub fn with_connector(mut http
: HttpConnector
, ssl_connector
: SslConnector
) -> Self {
933 http
.enforce_http(false);
937 ssl_connector
: std
::sync
::Arc
::new(ssl_connector
),
942 type MaybeTlsStream
= EitherStream
<
943 tokio
::net
::TcpStream
,
944 tokio_openssl
::SslStream
<tokio
::net
::TcpStream
>,
947 impl hyper
::service
::Service
<Uri
> for HttpsConnector
{
948 type Response
= MaybeTlsStream
;
950 type Future
= std
::pin
::Pin
<Box
<
951 dyn Future
<Output
= Result
<Self::Response
, Self::Error
>> + Send
+ '
static
954 fn poll_ready(&mut self, _
: &mut Context
<'_
>) -> Poll
<Result
<(), Self::Error
>> {
955 // This connector is always ready, but others might not be.
959 fn call(&mut self, dst
: Uri
) -> Self::Future
{
960 let mut this
= self.clone();
964 .ok_or_else(|| format_err
!("missing URL scheme"))?
968 .ok_or_else(|| format_err
!("missing hostname in destination url?"))?
971 let config
= this
.ssl_connector
.configure();
972 let conn
= this
.http
.call(dst
).await?
;
974 let conn
= tokio_openssl
::connect(config?
, &host
, conn
).await?
;
975 Ok(MaybeTlsStream
::Right(conn
))
977 Ok(MaybeTlsStream
::Left(conn
))