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 && &items
[0] == server
{
185 return Some(items
[1].clone());
192 fn store_ticket_info(prefix
: &str, server
: &str, username
: &str, ticket
: &str, token
: &str) -> Result
<(), Error
> {
194 let base
= BaseDirectories
::with_prefix(prefix
)?
;
196 // usually /run/user/<uid>/...
197 let path
= base
.place_runtime_file("tickets")?
;
199 let mode
= nix
::sys
::stat
::Mode
::from_bits_truncate(0o0600);
201 let mut data
= file_get_json(&path
, Some(json
!({}
)))?
;
203 let now
= proxmox
::tools
::time
::epoch_i64();
205 data
[server
][username
] = json
!({ "timestamp": now, "ticket": ticket, "token": token}
);
207 let mut new_data
= json
!({}
);
209 let ticket_lifetime
= tools
::ticket
::TICKET_LIFETIME
- 60;
211 let empty
= serde_json
::map
::Map
::new();
212 for (server
, info
) in data
.as_object().unwrap_or(&empty
) {
213 for (_user
, uinfo
) in info
.as_object().unwrap_or(&empty
) {
214 if let Some(timestamp
) = uinfo
["timestamp"].as_i64() {
215 let age
= now
- timestamp
;
216 if age
< ticket_lifetime
{
217 new_data
[server
][username
] = uinfo
.clone();
223 replace_file(path
, new_data
.to_string().as_bytes(), CreateOptions
::new().perm(mode
))?
;
228 fn load_ticket_info(prefix
: &str, server
: &str, userid
: &Userid
) -> Option
<(String
, String
)> {
229 let base
= BaseDirectories
::with_prefix(prefix
).ok()?
;
231 // usually /run/user/<uid>/...
232 let path
= base
.place_runtime_file("tickets").ok()?
;
233 let data
= file_get_json(&path
, None
).ok()?
;
234 let now
= proxmox
::tools
::time
::epoch_i64();
235 let ticket_lifetime
= tools
::ticket
::TICKET_LIFETIME
- 60;
236 let uinfo
= data
[server
][userid
.as_str()].as_object()?
;
237 let timestamp
= uinfo
["timestamp"].as_i64()?
;
238 let age
= now
- timestamp
;
240 if age
< ticket_lifetime
{
241 let ticket
= uinfo
["ticket"].as_str()?
;
242 let token
= uinfo
["token"].as_str()?
;
243 Some((ticket
.to_owned(), token
.to_owned()))
254 mut options
: HttpClientOptions
,
255 ) -> Result
<Self, Error
> {
257 let verified_fingerprint
= Arc
::new(Mutex
::new(None
));
259 let mut fingerprint
= options
.fingerprint
.take();
261 if fingerprint
.is_some() {
262 // do not store fingerprints passed via options in cache
263 options
.fingerprint_cache
= false;
264 } else if options
.fingerprint_cache
&& options
.prefix
.is_some() {
265 fingerprint
= load_fingerprint(options
.prefix
.as_ref().unwrap(), server
);
268 let mut ssl_connector_builder
= SslConnector
::builder(SslMethod
::tls()).unwrap();
270 if options
.verify_cert
{
271 let server
= server
.to_string();
272 let verified_fingerprint
= verified_fingerprint
.clone();
273 let interactive
= options
.interactive
;
274 let fingerprint_cache
= options
.fingerprint_cache
;
275 let prefix
= options
.prefix
.clone();
276 ssl_connector_builder
.set_verify_callback(openssl
::ssl
::SslVerifyMode
::PEER
, move |valid
, ctx
| {
277 let (valid
, fingerprint
) = Self::verify_callback(valid
, ctx
, fingerprint
.clone(), interactive
);
279 if let Some(fingerprint
) = fingerprint
{
280 if fingerprint_cache
&& prefix
.is_some() {
281 if let Err(err
) = store_fingerprint(
282 prefix
.as_ref().unwrap(), &server
, &fingerprint
) {
283 eprintln
!("{}", err
);
286 *verified_fingerprint
.lock().unwrap() = Some(fingerprint
);
292 ssl_connector_builder
.set_verify(openssl
::ssl
::SslVerifyMode
::NONE
);
295 let mut httpc
= hyper
::client
::HttpConnector
::new();
296 httpc
.set_nodelay(true); // important for h2 download performance!
297 httpc
.enforce_http(false); // we want https...
299 let https
= HttpsConnector
::with_connector(httpc
, ssl_connector_builder
.build());
301 let client
= Client
::builder()
302 //.http2_initial_stream_window_size( (1 << 31) - 2)
303 //.http2_initial_connection_window_size( (1 << 31) - 2)
304 .build
::<_
, Body
>(https
);
306 let password
= options
.password
.take();
307 let use_ticket_cache
= options
.ticket_cache
&& options
.prefix
.is_some();
309 let password
= if let Some(password
) = password
{
312 let mut ticket_info
= None
;
313 if use_ticket_cache
{
314 ticket_info
= load_ticket_info(options
.prefix
.as_ref().unwrap(), server
, userid
);
316 if let Some((ticket
, _token
)) = ticket_info
{
319 Self::get_password(userid
, options
.interactive
)?
323 let auth
= Arc
::new(RwLock
::new(AuthInfo
{
324 userid
: userid
.clone(),
325 ticket
: password
.clone(),
326 token
: "".to_string(),
329 let server2
= server
.to_string();
330 let client2
= client
.clone();
331 let auth2
= auth
.clone();
332 let prefix2
= options
.prefix
.clone();
334 let renewal_future
= async
move {
336 tokio
::time
::delay_for(Duration
::new(60*15, 0)).await
; // 15 minutes
337 let (userid
, ticket
) = {
338 let authinfo
= auth2
.read().unwrap().clone();
339 (authinfo
.userid
, authinfo
.ticket
)
341 match Self::credentials(client2
.clone(), server2
.clone(), port
, userid
, ticket
).await
{
343 if use_ticket_cache
& &prefix2
.is_some() {
344 let _
= store_ticket_info(prefix2
.as_ref().unwrap(), &server2
, &auth
.userid
.to_string(), &auth
.ticket
, &auth
.token
);
346 *auth2
.write().unwrap() = auth
;
349 eprintln
!("re-authentication failed: {}", err
);
356 let (renewal_future
, ticket_abort
) = futures
::future
::abortable(renewal_future
);
358 let login_future
= Self::credentials(
365 let server
= server
.to_string();
366 let prefix
= options
.prefix
.clone();
367 let authinfo
= auth
.clone();
370 if use_ticket_cache
& &prefix
.is_some() {
371 let _
= store_ticket_info(prefix
.as_ref().unwrap(), &server
, &auth
.userid
.to_string(), &auth
.ticket
, &auth
.token
);
373 *authinfo
.write().unwrap() = auth
;
374 tokio
::spawn(renewal_future
);
380 server
: String
::from(server
),
382 fingerprint
: verified_fingerprint
,
385 first_auth
: BroadcastFuture
::new(Box
::new(login_future
)),
392 /// Login is done on demand, so this is only required if you need
393 /// access to authentication data in 'AuthInfo'.
394 pub async
fn login(&self) -> Result
<AuthInfo
, Error
> {
395 self.first_auth
.listen().await?
;
396 let authinfo
= self.auth
.read().unwrap();
400 /// Returns the optional fingerprint passed to the new() constructor.
401 pub fn fingerprint(&self) -> Option
<String
> {
402 (*self.fingerprint
.lock().unwrap()).clone()
405 fn get_password(username
: &Userid
, interactive
: bool
) -> Result
<String
, Error
> {
406 // If we're on a TTY, query the user for a password
407 if interactive
&& tty
::stdin_isatty() {
408 let msg
= format
!("Password for \"{}\": ", username
);
409 return Ok(String
::from_utf8(tty
::read_password(&msg
)?
)?
);
412 bail
!("no password input mechanism available");
417 &mut X509StoreContextRef
,
418 expected_fingerprint
: Option
<String
>,
420 ) -> (bool
, Option
<String
>) {
421 if valid { return (true, None); }
423 let cert
= match ctx
.current_cert() {
425 None
=> return (false, None
),
428 let depth
= ctx
.error_depth();
429 if depth
!= 0 { return (false, None); }
431 let fp
= match cert
.digest(openssl
::hash
::MessageDigest
::sha256()) {
433 Err(_
) => return (false, None
), // should not happen
435 let fp_string
= proxmox
::tools
::digest_to_hex(&fp
);
436 let fp_string
= fp_string
.as_bytes().chunks(2).map(|v
| std
::str::from_utf8(v
).unwrap())
437 .collect
::<Vec
<&str>>().join(":");
439 if let Some(expected_fingerprint
) = expected_fingerprint
{
440 if expected_fingerprint
.to_lowercase() == fp_string
{
441 return (true, Some(fp_string
));
443 return (false, None
);
447 // If we're on a TTY, query the user
448 if interactive
&& tty
::stdin_isatty() {
449 println
!("fingerprint: {}", fp_string
);
451 print
!("Are you sure you want to continue connecting? (y/n): ");
452 let _
= std
::io
::stdout().flush();
453 use std
::io
::{BufRead, BufReader}
;
454 let mut line
= String
::new();
455 match BufReader
::new(std
::io
::stdin()).read_line(&mut line
) {
457 let trimmed
= line
.trim();
458 if trimmed
== "y" || trimmed
== "Y" {
459 return (true, Some(fp_string
));
460 } else if trimmed
== "n" || trimmed
== "N" {
461 return (false, None
);
466 Err(_
) => return (false, None
),
473 pub async
fn request(&self, mut req
: Request
<Body
>) -> Result
<Value
, Error
> {
475 let client
= self.client
.clone();
477 let auth
= self.login().await?
;
479 let enc_ticket
= format
!("PBSAuthCookie={}", percent_encode(auth
.ticket
.as_bytes(), DEFAULT_ENCODE_SET
));
480 req
.headers_mut().insert("Cookie", HeaderValue
::from_str(&enc_ticket
).unwrap());
481 req
.headers_mut().insert("CSRFPreventionToken", HeaderValue
::from_str(&auth
.token
).unwrap());
483 Self::api_request(client
, req
).await
490 ) -> Result
<Value
, Error
> {
491 let req
= Self::request_builder(&self.server
, self.port
, "GET", path
, data
)?
;
492 self.request(req
).await
499 ) -> Result
<Value
, Error
> {
500 let req
= Self::request_builder(&self.server
, self.port
, "DELETE", path
, data
)?
;
501 self.request(req
).await
508 ) -> Result
<Value
, Error
> {
509 let req
= Self::request_builder(&self.server
, self.port
, "POST", path
, data
)?
;
510 self.request(req
).await
513 pub async
fn download(
516 output
: &mut (dyn Write
+ Send
),
517 ) -> Result
<(), Error
> {
518 let mut req
= Self::request_builder(&self.server
, self.port
, "GET", path
, None
)?
;
520 let client
= self.client
.clone();
522 let auth
= self.login().await?
;
524 let enc_ticket
= format
!("PBSAuthCookie={}", percent_encode(auth
.ticket
.as_bytes(), DEFAULT_ENCODE_SET
));
525 req
.headers_mut().insert("Cookie", HeaderValue
::from_str(&enc_ticket
).unwrap());
527 let resp
= client
.request(req
).await?
;
528 let status
= resp
.status();
529 if !status
.is_success() {
530 HttpClient
::api_response(resp
)
531 .map(|_
| Err(format_err
!("unknown error")))
535 .map_err(Error
::from
)
536 .try_fold(output
, move |acc
, chunk
| async
move {
537 acc
.write_all(&chunk
)?
;
551 ) -> Result
<Value
, Error
> {
553 let path
= path
.trim_matches('
/'
);
554 let mut url
= format
!("https://{}:{}/{}", &self.server
, self.port
, path
);
556 if let Some(data
) = data
{
557 let query
= tools
::json_object_to_query(data
).unwrap();
559 url
.push_str(&query
);
562 let url
: Uri
= url
.parse().unwrap();
564 let req
= Request
::builder()
567 .header("User-Agent", "proxmox-backup-client/1.0")
568 .header("Content-Type", content_type
)
569 .body(body
).unwrap();
571 self.request(req
).await
574 pub async
fn start_h2_connection(
576 mut req
: Request
<Body
>,
577 protocol_name
: String
,
578 ) -> Result
<(H2Client
, futures
::future
::AbortHandle
), Error
> {
580 let auth
= self.login().await?
;
581 let client
= self.client
.clone();
583 let enc_ticket
= format
!("PBSAuthCookie={}", percent_encode(auth
.ticket
.as_bytes(), DEFAULT_ENCODE_SET
));
584 req
.headers_mut().insert("Cookie", HeaderValue
::from_str(&enc_ticket
).unwrap());
585 req
.headers_mut().insert("UPGRADE", HeaderValue
::from_str(&protocol_name
).unwrap());
587 let resp
= client
.request(req
).await?
;
588 let status
= resp
.status();
590 if status
!= http
::StatusCode
::SWITCHING_PROTOCOLS
{
591 Self::api_response(resp
).await?
;
592 bail
!("unknown error");
600 let max_window_size
= (1 << 31) - 2;
602 let (h2
, connection
) = h2
::client
::Builder
::new()
603 .initial_connection_window_size(max_window_size
)
604 .initial_window_size(max_window_size
)
605 .max_frame_size(4*1024*1024)
609 let connection
= connection
610 .map_err(|_
| panic
!("HTTP/2.0 connection failed"));
612 let (connection
, abort
) = futures
::future
::abortable(connection
);
613 // A cancellable future returns an Option which is None when cancelled and
614 // Some when it finished instead, since we don't care about the return type we
615 // need to map it away:
616 let connection
= connection
.map(|_
| ());
618 // Spawn a new task to drive the connection state
619 tokio
::spawn(connection
);
621 // Wait until the `SendRequest` handle has available capacity.
622 let c
= h2
.ready().await?
;
623 Ok((H2Client
::new(c
), abort
))
626 async
fn credentials(
627 client
: Client
<HttpsConnector
>,
632 ) -> Result
<AuthInfo
, Error
> {
633 let data
= json
!({ "username": username, "password": password }
);
634 let req
= Self::request_builder(&server
, port
, "POST", "/api2/json/access/ticket", Some(data
))?
;
635 let cred
= Self::api_request(client
, req
).await?
;
636 let auth
= AuthInfo
{
637 userid
: cred
["data"]["username"].as_str().unwrap().parse()?
,
638 ticket
: cred
["data"]["ticket"].as_str().unwrap().to_owned(),
639 token
: cred
["data"]["CSRFPreventionToken"].as_str().unwrap().to_owned(),
645 async
fn api_response(response
: Response
<Body
>) -> Result
<Value
, Error
> {
646 let status
= response
.status();
647 let data
= hyper
::body
::to_bytes(response
.into_body()).await?
;
649 let text
= String
::from_utf8(data
.to_vec()).unwrap();
650 if status
.is_success() {
654 let value
: Value
= serde_json
::from_str(&text
)?
;
658 Err(Error
::from(HttpError
::new(status
, text
)))
662 async
fn api_request(
663 client
: Client
<HttpsConnector
>,
665 ) -> Result
<Value
, Error
> {
668 .map_err(Error
::from
)
669 .and_then(Self::api_response
)
673 // Read-only access to server property
674 pub fn server(&self) -> &str {
678 pub fn port(&self) -> u16 {
682 pub fn request_builder(server
: &str, port
: u16, method
: &str, path
: &str, data
: Option
<Value
>) -> Result
<Request
<Body
>, Error
> {
683 let path
= path
.trim_matches('
/'
);
684 let url
: Uri
= format
!("https://{}:{}/{}", server
, port
, path
).parse()?
;
686 if let Some(data
) = data
{
687 if method
== "POST" {
688 let request
= Request
::builder()
691 .header("User-Agent", "proxmox-backup-client/1.0")
692 .header(hyper
::header
::CONTENT_TYPE
, "application/json")
693 .body(Body
::from(data
.to_string()))?
;
696 let query
= tools
::json_object_to_query(data
)?
;
697 let url
: Uri
= format
!("https://{}:{}/{}?{}", server
, port
, path
, query
).parse()?
;
698 let request
= Request
::builder()
701 .header("User-Agent", "proxmox-backup-client/1.0")
702 .header(hyper
::header
::CONTENT_TYPE
, "application/x-www-form-urlencoded")
703 .body(Body
::empty())?
;
708 let request
= Request
::builder()
711 .header("User-Agent", "proxmox-backup-client/1.0")
712 .header(hyper
::header
::CONTENT_TYPE
, "application/x-www-form-urlencoded")
713 .body(Body
::empty())?
;
719 impl Drop
for HttpClient
{
721 self.ticket_abort
.abort();
727 pub struct H2Client
{
728 h2
: h2
::client
::SendRequest
<bytes
::Bytes
>,
733 pub fn new(h2
: h2
::client
::SendRequest
<bytes
::Bytes
>) -> Self {
741 ) -> Result
<Value
, Error
> {
742 let req
= Self::request_builder("localhost", "GET", path
, param
, None
).unwrap();
743 self.request(req
).await
750 ) -> Result
<Value
, Error
> {
751 let req
= Self::request_builder("localhost", "PUT", path
, param
, None
).unwrap();
752 self.request(req
).await
759 ) -> Result
<Value
, Error
> {
760 let req
= Self::request_builder("localhost", "POST", path
, param
, None
).unwrap();
761 self.request(req
).await
764 pub async
fn download
<W
: Write
+ Send
>(
767 param
: Option
<Value
>,
769 ) -> Result
<(), Error
> {
770 let request
= Self::request_builder("localhost", "GET", path
, param
, None
).unwrap();
772 let response_future
= self.send_request(request
, None
).await?
;
774 let resp
= response_future
.await?
;
776 let status
= resp
.status();
777 if !status
.is_success() {
778 H2Client
::h2api_response(resp
).await?
; // raise error
782 let mut body
= resp
.into_body();
783 while let Some(chunk
) = body
.data().await
{
785 body
.flow_control().release_capacity(chunk
.len())?
;
786 output
.write_all(&chunk
)?
;
794 method
: &str, // POST or PUT
796 param
: Option
<Value
>,
799 ) -> Result
<Value
, Error
> {
800 let request
= Self::request_builder("localhost", method
, path
, param
, Some(content_type
)).unwrap();
802 let mut send_request
= self.h2
.clone().ready().await?
;
804 let (response
, stream
) = send_request
.send_request(request
, false).unwrap();
806 PipeToSendStream
::new(bytes
::Bytes
::from(data
), stream
).await?
;
809 .map_err(Error
::from
)
810 .and_then(Self::h2api_response
)
816 request
: Request
<()>,
817 ) -> Result
<Value
, Error
> {
819 self.send_request(request
, None
)
820 .and_then(move |response
| {
822 .map_err(Error
::from
)
823 .and_then(Self::h2api_response
)
830 request
: Request
<()>,
831 data
: Option
<bytes
::Bytes
>,
832 ) -> impl Future
<Output
= Result
<h2
::client
::ResponseFuture
, Error
>> {
836 .map_err(Error
::from
)
837 .and_then(move |mut send_request
| async
move {
838 if let Some(data
) = data
{
839 let (response
, stream
) = send_request
.send_request(request
, false).unwrap();
840 PipeToSendStream
::new(data
, stream
).await?
;
843 let (response
, _stream
) = send_request
.send_request(request
, true).unwrap();
849 pub async
fn h2api_response(
850 response
: Response
<h2
::RecvStream
>,
851 ) -> Result
<Value
, Error
> {
852 let status
= response
.status();
854 let (_head
, mut body
) = response
.into_parts();
856 let mut data
= Vec
::new();
857 while let Some(chunk
) = body
.data().await
{
859 // Whenever data is received, the caller is responsible for
860 // releasing capacity back to the server once it has freed
861 // the data from memory.
862 // Let the server send more data.
863 body
.flow_control().release_capacity(chunk
.len())?
;
867 let text
= String
::from_utf8(data
.to_vec()).unwrap();
868 if status
.is_success() {
872 let mut value
: Value
= serde_json
::from_str(&text
)?
;
873 if let Some(map
) = value
.as_object_mut() {
874 if let Some(data
) = map
.remove("data") {
878 bail
!("got result without data property");
881 Err(Error
::from(HttpError
::new(status
, text
)))
885 // Note: We always encode parameters with the url
886 pub fn request_builder(
890 param
: Option
<Value
>,
891 content_type
: Option
<&str>,
892 ) -> Result
<Request
<()>, Error
> {
893 let path
= path
.trim_matches('
/'
);
895 let content_type
= content_type
.unwrap_or("application/x-www-form-urlencoded");
897 if let Some(param
) = param
{
898 let query
= tools
::json_object_to_query(param
)?
;
899 // We detected problem with hyper around 6000 characters - seo we try to keep on the safe side
900 if query
.len() > 4096 { bail!("h2 query data too large ({} bytes
) - please encode data inside body
", query.len()); }
901 let url: Uri = format!("https
://{}:8007/{}?{}", server, path, query).parse()?;
902 let request
= Request
::builder()
905 .header("User-Agent", "proxmox-backup-client/1.0")
906 .header(hyper
::header
::CONTENT_TYPE
, content_type
)
910 let url
: Uri
= format
!("https://{}:8007/{}", server
, path
).parse()?
;
911 let request
= Request
::builder()
914 .header("User-Agent", "proxmox-backup-client/1.0")
915 .header(hyper
::header
::CONTENT_TYPE
, content_type
)
924 pub struct HttpsConnector
{
926 ssl_connector
: std
::sync
::Arc
<SslConnector
>,
929 impl HttpsConnector
{
930 pub fn with_connector(mut http
: HttpConnector
, ssl_connector
: SslConnector
) -> Self {
931 http
.enforce_http(false);
935 ssl_connector
: std
::sync
::Arc
::new(ssl_connector
),
940 type MaybeTlsStream
= EitherStream
<
941 tokio
::net
::TcpStream
,
942 tokio_openssl
::SslStream
<tokio
::net
::TcpStream
>,
945 impl hyper
::service
::Service
<Uri
> for HttpsConnector
{
946 type Response
= MaybeTlsStream
;
948 type Future
= std
::pin
::Pin
<Box
<
949 dyn Future
<Output
= Result
<Self::Response
, Self::Error
>> + Send
+ '
static
952 fn poll_ready(&mut self, _
: &mut Context
<'_
>) -> Poll
<Result
<(), Self::Error
>> {
953 // This connector is always ready, but others might not be.
957 fn call(&mut self, dst
: Uri
) -> Self::Future
{
958 let mut this
= self.clone();
962 .ok_or_else(|| format_err
!("missing URL scheme"))?
966 .ok_or_else(|| format_err
!("missing hostname in destination url?"))?
969 let config
= this
.ssl_connector
.configure();
970 let conn
= this
.http
.call(dst
).await?
;
972 let conn
= tokio_openssl
::connect(config?
, &host
, conn
).await?
;
973 Ok(MaybeTlsStream
::Right(conn
))
975 Ok(MaybeTlsStream
::Left(conn
))