2 use std
::task
::{Context, Poll}
;
3 use std
::sync
::{Arc, Mutex, RwLock}
;
4 use std
::time
::Duration
;
5 use std
::os
::unix
::io
::AsRawFd
;
7 use anyhow
::{bail, format_err, Error}
;
10 use http
::header
::HeaderValue
;
11 use http
::{Request, Response}
;
13 use hyper
::client
::{Client, HttpConnector}
;
14 use openssl
::{ssl::{SslConnector, SslMethod}
, x509
::X509StoreContextRef
};
15 use serde_json
::{json, Value}
;
16 use percent_encoding
::percent_encode
;
17 use xdg
::BaseDirectories
;
20 api
::error
::HttpError
,
23 fs
::{file_get_json, replace_file, CreateOptions}
,
27 use super::pipe_to_stream
::PipeToSendStream
;
28 use crate::api2
::types
::Userid
;
29 use crate::tools
::async_io
::EitherStream
;
36 PROXMOX_BACKUP_TCP_KEEPALIVE_TIME
,
47 pub struct HttpClientOptions
{
48 prefix
: Option
<String
>,
49 password
: Option
<String
>,
50 fingerprint
: Option
<String
>,
53 fingerprint_cache
: bool
,
57 impl HttpClientOptions
{
59 pub fn new() -> Self {
66 fingerprint_cache
: false,
71 pub fn prefix(mut self, prefix
: Option
<String
>) -> Self {
76 pub fn password(mut self, password
: Option
<String
>) -> Self {
77 self.password
= password
;
81 pub fn fingerprint(mut self, fingerprint
: Option
<String
>) -> Self {
82 self.fingerprint
= fingerprint
;
86 pub fn interactive(mut self, interactive
: bool
) -> Self {
87 self.interactive
= interactive
;
91 pub fn ticket_cache(mut self, ticket_cache
: bool
) -> Self {
92 self.ticket_cache
= ticket_cache
;
96 pub fn fingerprint_cache(mut self, fingerprint_cache
: bool
) -> Self {
97 self.fingerprint_cache
= fingerprint_cache
;
101 pub fn verify_cert(mut self, verify_cert
: bool
) -> Self {
102 self.verify_cert
= verify_cert
;
107 /// HTTP(S) API client
108 pub struct HttpClient
{
109 client
: Client
<HttpsConnector
>,
112 fingerprint
: Arc
<Mutex
<Option
<String
>>>,
113 first_auth
: BroadcastFuture
<()>,
114 auth
: Arc
<RwLock
<AuthInfo
>>,
115 ticket_abort
: futures
::future
::AbortHandle
,
116 _options
: HttpClientOptions
,
119 /// Delete stored ticket data (logout)
120 pub fn delete_ticket_info(prefix
: &str, server
: &str, username
: &Userid
) -> Result
<(), Error
> {
122 let base
= BaseDirectories
::with_prefix(prefix
)?
;
124 // usually /run/user/<uid>/...
125 let path
= base
.place_runtime_file("tickets")?
;
127 let mode
= nix
::sys
::stat
::Mode
::from_bits_truncate(0o0600);
129 let mut data
= file_get_json(&path
, Some(json
!({}
)))?
;
131 if let Some(map
) = data
[server
].as_object_mut() {
132 map
.remove(username
.as_str());
135 replace_file(path
, data
.to_string().as_bytes(), CreateOptions
::new().perm(mode
))?
;
140 fn store_fingerprint(prefix
: &str, server
: &str, fingerprint
: &str) -> Result
<(), Error
> {
142 let base
= BaseDirectories
::with_prefix(prefix
)?
;
144 // usually ~/.config/<prefix>/fingerprints
145 let path
= base
.place_config_file("fingerprints")?
;
147 let raw
= match std
::fs
::read_to_string(&path
) {
150 if err
.kind() == std
::io
::ErrorKind
::NotFound
{
153 bail
!("unable to read fingerprints from {:?} - {}", path
, err
);
158 let mut result
= String
::new();
160 raw
.split('
\n'
).for_each(|line
| {
161 let items
: Vec
<String
> = line
.split_whitespace().map(String
::from
).collect();
162 if items
.len() == 2 {
163 if &items
[0] == server
{
164 // found, add later with new fingerprint
166 result
.push_str(line
);
172 result
.push_str(server
);
174 result
.push_str(fingerprint
);
177 replace_file(path
, result
.as_bytes(), CreateOptions
::new())?
;
182 fn load_fingerprint(prefix
: &str, server
: &str) -> Option
<String
> {
184 let base
= BaseDirectories
::with_prefix(prefix
).ok()?
;
186 // usually ~/.config/<prefix>/fingerprints
187 let path
= base
.place_config_file("fingerprints").ok()?
;
189 let raw
= std
::fs
::read_to_string(&path
).ok()?
;
191 for line
in raw
.split('
\n'
) {
192 let items
: Vec
<String
> = line
.split_whitespace().map(String
::from
).collect();
193 if items
.len() == 2 && &items
[0] == server
{
194 return Some(items
[1].clone());
201 fn store_ticket_info(prefix
: &str, server
: &str, username
: &str, ticket
: &str, token
: &str) -> Result
<(), Error
> {
203 let base
= BaseDirectories
::with_prefix(prefix
)?
;
205 // usually /run/user/<uid>/...
206 let path
= base
.place_runtime_file("tickets")?
;
208 let mode
= nix
::sys
::stat
::Mode
::from_bits_truncate(0o0600);
210 let mut data
= file_get_json(&path
, Some(json
!({}
)))?
;
212 let now
= proxmox
::tools
::time
::epoch_i64();
214 data
[server
][username
] = json
!({ "timestamp": now, "ticket": ticket, "token": token}
);
216 let mut new_data
= json
!({}
);
218 let ticket_lifetime
= tools
::ticket
::TICKET_LIFETIME
- 60;
220 let empty
= serde_json
::map
::Map
::new();
221 for (server
, info
) in data
.as_object().unwrap_or(&empty
) {
222 for (user
, uinfo
) in info
.as_object().unwrap_or(&empty
) {
223 if let Some(timestamp
) = uinfo
["timestamp"].as_i64() {
224 let age
= now
- timestamp
;
225 if age
< ticket_lifetime
{
226 new_data
[server
][user
] = uinfo
.clone();
232 replace_file(path
, new_data
.to_string().as_bytes(), CreateOptions
::new().perm(mode
))?
;
237 fn load_ticket_info(prefix
: &str, server
: &str, userid
: &Userid
) -> Option
<(String
, String
)> {
238 let base
= BaseDirectories
::with_prefix(prefix
).ok()?
;
240 // usually /run/user/<uid>/...
241 let path
= base
.place_runtime_file("tickets").ok()?
;
242 let data
= file_get_json(&path
, None
).ok()?
;
243 let now
= proxmox
::tools
::time
::epoch_i64();
244 let ticket_lifetime
= tools
::ticket
::TICKET_LIFETIME
- 60;
245 let uinfo
= data
[server
][userid
.as_str()].as_object()?
;
246 let timestamp
= uinfo
["timestamp"].as_i64()?
;
247 let age
= now
- timestamp
;
249 if age
< ticket_lifetime
{
250 let ticket
= uinfo
["ticket"].as_str()?
;
251 let token
= uinfo
["token"].as_str()?
;
252 Some((ticket
.to_owned(), token
.to_owned()))
263 mut options
: HttpClientOptions
,
264 ) -> Result
<Self, Error
> {
266 let verified_fingerprint
= Arc
::new(Mutex
::new(None
));
268 let mut fingerprint
= options
.fingerprint
.take();
270 if fingerprint
.is_some() {
271 // do not store fingerprints passed via options in cache
272 options
.fingerprint_cache
= false;
273 } else if options
.fingerprint_cache
&& options
.prefix
.is_some() {
274 fingerprint
= load_fingerprint(options
.prefix
.as_ref().unwrap(), server
);
277 let mut ssl_connector_builder
= SslConnector
::builder(SslMethod
::tls()).unwrap();
279 if options
.verify_cert
{
280 let server
= server
.to_string();
281 let verified_fingerprint
= verified_fingerprint
.clone();
282 let interactive
= options
.interactive
;
283 let fingerprint_cache
= options
.fingerprint_cache
;
284 let prefix
= options
.prefix
.clone();
285 ssl_connector_builder
.set_verify_callback(openssl
::ssl
::SslVerifyMode
::PEER
, move |valid
, ctx
| {
286 let (valid
, fingerprint
) = Self::verify_callback(valid
, ctx
, fingerprint
.clone(), interactive
);
288 if let Some(fingerprint
) = fingerprint
{
289 if fingerprint_cache
&& prefix
.is_some() {
290 if let Err(err
) = store_fingerprint(
291 prefix
.as_ref().unwrap(), &server
, &fingerprint
) {
292 eprintln
!("{}", err
);
295 *verified_fingerprint
.lock().unwrap() = Some(fingerprint
);
301 ssl_connector_builder
.set_verify(openssl
::ssl
::SslVerifyMode
::NONE
);
304 let mut httpc
= hyper
::client
::HttpConnector
::new();
305 httpc
.set_nodelay(true); // important for h2 download performance!
306 httpc
.enforce_http(false); // we want https...
308 httpc
.set_connect_timeout(Some(std
::time
::Duration
::new(10, 0)));
309 let https
= HttpsConnector
::with_connector(httpc
, ssl_connector_builder
.build());
311 let client
= Client
::builder()
312 //.http2_initial_stream_window_size( (1 << 31) - 2)
313 //.http2_initial_connection_window_size( (1 << 31) - 2)
314 .build
::<_
, Body
>(https
);
316 let password
= options
.password
.take();
317 let use_ticket_cache
= options
.ticket_cache
&& options
.prefix
.is_some();
319 let password
= if let Some(password
) = password
{
322 let mut ticket_info
= None
;
323 if use_ticket_cache
{
324 ticket_info
= load_ticket_info(options
.prefix
.as_ref().unwrap(), server
, userid
);
326 if let Some((ticket
, _token
)) = ticket_info
{
329 Self::get_password(userid
, options
.interactive
)?
333 let auth
= Arc
::new(RwLock
::new(AuthInfo
{
334 userid
: userid
.clone(),
335 ticket
: password
.clone(),
336 token
: "".to_string(),
339 let server2
= server
.to_string();
340 let client2
= client
.clone();
341 let auth2
= auth
.clone();
342 let prefix2
= options
.prefix
.clone();
344 let renewal_future
= async
move {
346 tokio
::time
::delay_for(Duration
::new(60*15, 0)).await
; // 15 minutes
347 let (userid
, ticket
) = {
348 let authinfo
= auth2
.read().unwrap().clone();
349 (authinfo
.userid
, authinfo
.ticket
)
351 match Self::credentials(client2
.clone(), server2
.clone(), port
, userid
, ticket
).await
{
353 if use_ticket_cache
& &prefix2
.is_some() {
354 let _
= store_ticket_info(prefix2
.as_ref().unwrap(), &server2
, &auth
.userid
.to_string(), &auth
.ticket
, &auth
.token
);
356 *auth2
.write().unwrap() = auth
;
359 eprintln
!("re-authentication failed: {}", err
);
366 let (renewal_future
, ticket_abort
) = futures
::future
::abortable(renewal_future
);
368 let login_future
= Self::credentials(
375 let server
= server
.to_string();
376 let prefix
= options
.prefix
.clone();
377 let authinfo
= auth
.clone();
380 if use_ticket_cache
& &prefix
.is_some() {
381 let _
= store_ticket_info(prefix
.as_ref().unwrap(), &server
, &auth
.userid
.to_string(), &auth
.ticket
, &auth
.token
);
383 *authinfo
.write().unwrap() = auth
;
384 tokio
::spawn(renewal_future
);
390 server
: String
::from(server
),
392 fingerprint
: verified_fingerprint
,
395 first_auth
: BroadcastFuture
::new(Box
::new(login_future
)),
402 /// Login is done on demand, so this is only required if you need
403 /// access to authentication data in 'AuthInfo'.
404 pub async
fn login(&self) -> Result
<AuthInfo
, Error
> {
405 self.first_auth
.listen().await?
;
406 let authinfo
= self.auth
.read().unwrap();
410 /// Returns the optional fingerprint passed to the new() constructor.
411 pub fn fingerprint(&self) -> Option
<String
> {
412 (*self.fingerprint
.lock().unwrap()).clone()
415 fn get_password(username
: &Userid
, interactive
: bool
) -> Result
<String
, Error
> {
416 // If we're on a TTY, query the user for a password
417 if interactive
&& tty
::stdin_isatty() {
418 let msg
= format
!("Password for \"{}\": ", username
);
419 return Ok(String
::from_utf8(tty
::read_password(&msg
)?
)?
);
422 bail
!("no password input mechanism available");
427 &mut X509StoreContextRef
,
428 expected_fingerprint
: Option
<String
>,
430 ) -> (bool
, Option
<String
>) {
431 if valid { return (true, None); }
433 let cert
= match ctx
.current_cert() {
435 None
=> return (false, None
),
438 let depth
= ctx
.error_depth();
439 if depth
!= 0 { return (false, None); }
441 let fp
= match cert
.digest(openssl
::hash
::MessageDigest
::sha256()) {
443 Err(_
) => return (false, None
), // should not happen
445 let fp_string
= proxmox
::tools
::digest_to_hex(&fp
);
446 let fp_string
= fp_string
.as_bytes().chunks(2).map(|v
| std
::str::from_utf8(v
).unwrap())
447 .collect
::<Vec
<&str>>().join(":");
449 if let Some(expected_fingerprint
) = expected_fingerprint
{
450 if expected_fingerprint
.to_lowercase() == fp_string
{
451 return (true, Some(fp_string
));
453 return (false, None
);
457 // If we're on a TTY, query the user
458 if interactive
&& tty
::stdin_isatty() {
459 println
!("fingerprint: {}", fp_string
);
461 print
!("Are you sure you want to continue connecting? (y/n): ");
462 let _
= std
::io
::stdout().flush();
463 use std
::io
::{BufRead, BufReader}
;
464 let mut line
= String
::new();
465 match BufReader
::new(std
::io
::stdin()).read_line(&mut line
) {
467 let trimmed
= line
.trim();
468 if trimmed
== "y" || trimmed
== "Y" {
469 return (true, Some(fp_string
));
470 } else if trimmed
== "n" || trimmed
== "N" {
471 return (false, None
);
476 Err(_
) => return (false, None
),
483 pub async
fn request(&self, mut req
: Request
<Body
>) -> Result
<Value
, Error
> {
485 let client
= self.client
.clone();
487 let auth
= self.login().await?
;
489 let enc_ticket
= format
!("PBSAuthCookie={}", percent_encode(auth
.ticket
.as_bytes(), DEFAULT_ENCODE_SET
));
490 req
.headers_mut().insert("Cookie", HeaderValue
::from_str(&enc_ticket
).unwrap());
491 req
.headers_mut().insert("CSRFPreventionToken", HeaderValue
::from_str(&auth
.token
).unwrap());
493 Self::api_request(client
, req
).await
500 ) -> Result
<Value
, Error
> {
501 let req
= Self::request_builder(&self.server
, self.port
, "GET", path
, data
)?
;
502 self.request(req
).await
509 ) -> Result
<Value
, Error
> {
510 let req
= Self::request_builder(&self.server
, self.port
, "DELETE", path
, data
)?
;
511 self.request(req
).await
518 ) -> Result
<Value
, Error
> {
519 let req
= Self::request_builder(&self.server
, self.port
, "POST", path
, data
)?
;
520 self.request(req
).await
523 pub async
fn download(
526 output
: &mut (dyn Write
+ Send
),
527 ) -> Result
<(), Error
> {
528 let mut req
= Self::request_builder(&self.server
, self.port
, "GET", path
, None
)?
;
530 let client
= self.client
.clone();
532 let auth
= self.login().await?
;
534 let enc_ticket
= format
!("PBSAuthCookie={}", percent_encode(auth
.ticket
.as_bytes(), DEFAULT_ENCODE_SET
));
535 req
.headers_mut().insert("Cookie", HeaderValue
::from_str(&enc_ticket
).unwrap());
537 let resp
= client
.request(req
).await?
;
538 let status
= resp
.status();
539 if !status
.is_success() {
540 HttpClient
::api_response(resp
)
541 .map(|_
| Err(format_err
!("unknown error")))
545 .map_err(Error
::from
)
546 .try_fold(output
, move |acc
, chunk
| async
move {
547 acc
.write_all(&chunk
)?
;
561 ) -> Result
<Value
, Error
> {
563 let path
= path
.trim_matches('
/'
);
564 let mut url
= format
!("https://{}:{}/{}", &self.server
, self.port
, path
);
566 if let Some(data
) = data
{
567 let query
= tools
::json_object_to_query(data
).unwrap();
569 url
.push_str(&query
);
572 let url
: Uri
= url
.parse().unwrap();
574 let req
= Request
::builder()
577 .header("User-Agent", "proxmox-backup-client/1.0")
578 .header("Content-Type", content_type
)
579 .body(body
).unwrap();
581 self.request(req
).await
584 pub async
fn start_h2_connection(
586 mut req
: Request
<Body
>,
587 protocol_name
: String
,
588 ) -> Result
<(H2Client
, futures
::future
::AbortHandle
), Error
> {
590 let auth
= self.login().await?
;
591 let client
= self.client
.clone();
593 let enc_ticket
= format
!("PBSAuthCookie={}", percent_encode(auth
.ticket
.as_bytes(), DEFAULT_ENCODE_SET
));
594 req
.headers_mut().insert("Cookie", HeaderValue
::from_str(&enc_ticket
).unwrap());
595 req
.headers_mut().insert("UPGRADE", HeaderValue
::from_str(&protocol_name
).unwrap());
597 let resp
= client
.request(req
).await?
;
598 let status
= resp
.status();
600 if status
!= http
::StatusCode
::SWITCHING_PROTOCOLS
{
601 Self::api_response(resp
).await?
;
602 bail
!("unknown error");
610 let max_window_size
= (1 << 31) - 2;
612 let (h2
, connection
) = h2
::client
::Builder
::new()
613 .initial_connection_window_size(max_window_size
)
614 .initial_window_size(max_window_size
)
615 .max_frame_size(4*1024*1024)
619 let connection
= connection
620 .map_err(|_
| eprintln
!("HTTP/2.0 connection failed"));
622 let (connection
, abort
) = futures
::future
::abortable(connection
);
623 // A cancellable future returns an Option which is None when cancelled and
624 // Some when it finished instead, since we don't care about the return type we
625 // need to map it away:
626 let connection
= connection
.map(|_
| ());
628 // Spawn a new task to drive the connection state
629 tokio
::spawn(connection
);
631 // Wait until the `SendRequest` handle has available capacity.
632 let c
= h2
.ready().await?
;
633 Ok((H2Client
::new(c
), abort
))
636 async
fn credentials(
637 client
: Client
<HttpsConnector
>,
642 ) -> Result
<AuthInfo
, Error
> {
643 let data
= json
!({ "username": username, "password": password }
);
644 let req
= Self::request_builder(&server
, port
, "POST", "/api2/json/access/ticket", Some(data
))?
;
645 let cred
= Self::api_request(client
, req
).await?
;
646 let auth
= AuthInfo
{
647 userid
: cred
["data"]["username"].as_str().unwrap().parse()?
,
648 ticket
: cred
["data"]["ticket"].as_str().unwrap().to_owned(),
649 token
: cred
["data"]["CSRFPreventionToken"].as_str().unwrap().to_owned(),
655 async
fn api_response(response
: Response
<Body
>) -> Result
<Value
, Error
> {
656 let status
= response
.status();
657 let data
= hyper
::body
::to_bytes(response
.into_body()).await?
;
659 let text
= String
::from_utf8(data
.to_vec()).unwrap();
660 if status
.is_success() {
664 let value
: Value
= serde_json
::from_str(&text
)?
;
668 Err(Error
::from(HttpError
::new(status
, text
)))
672 async
fn api_request(
673 client
: Client
<HttpsConnector
>,
675 ) -> Result
<Value
, Error
> {
678 .map_err(Error
::from
)
679 .and_then(Self::api_response
)
683 // Read-only access to server property
684 pub fn server(&self) -> &str {
688 pub fn port(&self) -> u16 {
692 pub fn request_builder(server
: &str, port
: u16, method
: &str, path
: &str, data
: Option
<Value
>) -> Result
<Request
<Body
>, Error
> {
693 let path
= path
.trim_matches('
/'
);
694 let url
: Uri
= format
!("https://{}:{}/{}", server
, port
, path
).parse()?
;
696 if let Some(data
) = data
{
697 if method
== "POST" {
698 let request
= Request
::builder()
701 .header("User-Agent", "proxmox-backup-client/1.0")
702 .header(hyper
::header
::CONTENT_TYPE
, "application/json")
703 .body(Body
::from(data
.to_string()))?
;
706 let query
= tools
::json_object_to_query(data
)?
;
707 let url
: Uri
= format
!("https://{}:{}/{}?{}", server
, port
, path
, query
).parse()?
;
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())?
;
718 let request
= Request
::builder()
721 .header("User-Agent", "proxmox-backup-client/1.0")
722 .header(hyper
::header
::CONTENT_TYPE
, "application/x-www-form-urlencoded")
723 .body(Body
::empty())?
;
729 impl Drop
for HttpClient
{
731 self.ticket_abort
.abort();
737 pub struct H2Client
{
738 h2
: h2
::client
::SendRequest
<bytes
::Bytes
>,
743 pub fn new(h2
: h2
::client
::SendRequest
<bytes
::Bytes
>) -> Self {
751 ) -> Result
<Value
, Error
> {
752 let req
= Self::request_builder("localhost", "GET", path
, param
, None
).unwrap();
753 self.request(req
).await
760 ) -> Result
<Value
, Error
> {
761 let req
= Self::request_builder("localhost", "PUT", path
, param
, None
).unwrap();
762 self.request(req
).await
769 ) -> Result
<Value
, Error
> {
770 let req
= Self::request_builder("localhost", "POST", path
, param
, None
).unwrap();
771 self.request(req
).await
774 pub async
fn download
<W
: Write
+ Send
>(
777 param
: Option
<Value
>,
779 ) -> Result
<(), Error
> {
780 let request
= Self::request_builder("localhost", "GET", path
, param
, None
).unwrap();
782 let response_future
= self.send_request(request
, None
).await?
;
784 let resp
= response_future
.await?
;
786 let status
= resp
.status();
787 if !status
.is_success() {
788 H2Client
::h2api_response(resp
).await?
; // raise error
792 let mut body
= resp
.into_body();
793 while let Some(chunk
) = body
.data().await
{
795 body
.flow_control().release_capacity(chunk
.len())?
;
796 output
.write_all(&chunk
)?
;
804 method
: &str, // POST or PUT
806 param
: Option
<Value
>,
809 ) -> Result
<Value
, Error
> {
810 let request
= Self::request_builder("localhost", method
, path
, param
, Some(content_type
)).unwrap();
812 let mut send_request
= self.h2
.clone().ready().await?
;
814 let (response
, stream
) = send_request
.send_request(request
, false).unwrap();
816 PipeToSendStream
::new(bytes
::Bytes
::from(data
), stream
).await?
;
819 .map_err(Error
::from
)
820 .and_then(Self::h2api_response
)
826 request
: Request
<()>,
827 ) -> Result
<Value
, Error
> {
829 self.send_request(request
, None
)
830 .and_then(move |response
| {
832 .map_err(Error
::from
)
833 .and_then(Self::h2api_response
)
840 request
: Request
<()>,
841 data
: Option
<bytes
::Bytes
>,
842 ) -> impl Future
<Output
= Result
<h2
::client
::ResponseFuture
, Error
>> {
846 .map_err(Error
::from
)
847 .and_then(move |mut send_request
| async
move {
848 if let Some(data
) = data
{
849 let (response
, stream
) = send_request
.send_request(request
, false).unwrap();
850 PipeToSendStream
::new(data
, stream
).await?
;
853 let (response
, _stream
) = send_request
.send_request(request
, true).unwrap();
859 pub async
fn h2api_response(
860 response
: Response
<h2
::RecvStream
>,
861 ) -> Result
<Value
, Error
> {
862 let status
= response
.status();
864 let (_head
, mut body
) = response
.into_parts();
866 let mut data
= Vec
::new();
867 while let Some(chunk
) = body
.data().await
{
869 // Whenever data is received, the caller is responsible for
870 // releasing capacity back to the server once it has freed
871 // the data from memory.
872 // Let the server send more data.
873 body
.flow_control().release_capacity(chunk
.len())?
;
877 let text
= String
::from_utf8(data
.to_vec()).unwrap();
878 if status
.is_success() {
882 let mut value
: Value
= serde_json
::from_str(&text
)?
;
883 if let Some(map
) = value
.as_object_mut() {
884 if let Some(data
) = map
.remove("data") {
888 bail
!("got result without data property");
891 Err(Error
::from(HttpError
::new(status
, text
)))
895 // Note: We always encode parameters with the url
896 pub fn request_builder(
900 param
: Option
<Value
>,
901 content_type
: Option
<&str>,
902 ) -> Result
<Request
<()>, Error
> {
903 let path
= path
.trim_matches('
/'
);
905 let content_type
= content_type
.unwrap_or("application/x-www-form-urlencoded");
907 if let Some(param
) = param
{
908 let query
= tools
::json_object_to_query(param
)?
;
909 // We detected problem with hyper around 6000 characters - seo we try to keep on the safe side
910 if query
.len() > 4096 { bail!("h2 query data too large ({} bytes
) - please encode data inside body
", query.len()); }
911 let url: Uri = format!("https
://{}:8007/{}?{}", server, path, query).parse()?;
912 let request
= Request
::builder()
915 .header("User-Agent", "proxmox-backup-client/1.0")
916 .header(hyper
::header
::CONTENT_TYPE
, content_type
)
920 let url
: Uri
= format
!("https://{}:8007/{}", server
, path
).parse()?
;
921 let request
= Request
::builder()
924 .header("User-Agent", "proxmox-backup-client/1.0")
925 .header(hyper
::header
::CONTENT_TYPE
, content_type
)
934 pub struct HttpsConnector
{
936 ssl_connector
: std
::sync
::Arc
<SslConnector
>,
939 impl HttpsConnector
{
940 pub fn with_connector(mut http
: HttpConnector
, ssl_connector
: SslConnector
) -> Self {
941 http
.enforce_http(false);
945 ssl_connector
: std
::sync
::Arc
::new(ssl_connector
),
950 type MaybeTlsStream
= EitherStream
<
951 tokio
::net
::TcpStream
,
952 tokio_openssl
::SslStream
<tokio
::net
::TcpStream
>,
955 impl hyper
::service
::Service
<Uri
> for HttpsConnector
{
956 type Response
= MaybeTlsStream
;
958 type Future
= std
::pin
::Pin
<Box
<
959 dyn Future
<Output
= Result
<Self::Response
, Self::Error
>> + Send
+ '
static
962 fn poll_ready(&mut self, _
: &mut Context
<'_
>) -> Poll
<Result
<(), Self::Error
>> {
963 // This connector is always ready, but others might not be.
967 fn call(&mut self, dst
: Uri
) -> Self::Future
{
968 let mut this
= self.clone();
972 .ok_or_else(|| format_err
!("missing URL scheme"))?
976 .ok_or_else(|| format_err
!("missing hostname in destination url?"))?
979 let config
= this
.ssl_connector
.configure();
980 let conn
= this
.http
.call(dst
).await?
;
982 let _
= set_tcp_keepalive(conn
.as_raw_fd(), PROXMOX_BACKUP_TCP_KEEPALIVE_TIME
);
985 let conn
= tokio_openssl
::connect(config?
, &host
, conn
).await?
;
986 Ok(MaybeTlsStream
::Right(conn
))
988 Ok(MaybeTlsStream
::Left(conn
))