2 use std
::task
::{Context, Poll}
;
3 use std
::sync
::{Arc, Mutex}
;
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
;
21 fs
::{file_get_json, replace_file, CreateOptions}
,
25 use super::pipe_to_stream
::PipeToSendStream
;
26 use crate::tools
::async_io
::EitherStream
;
27 use crate::tools
::{self, BroadcastFuture, DEFAULT_ENCODE_SET}
;
36 pub struct HttpClientOptions
{
37 prefix
: Option
<String
>,
38 password
: Option
<String
>,
39 password_env
: Option
<String
>,
40 fingerprint
: Option
<String
>,
43 fingerprint_cache
: bool
,
47 impl HttpClientOptions
{
49 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 password_env(mut self, password_env
: Option
<String
>) -> Self {
73 self.password_env
= password_env
;
77 pub fn fingerprint(mut self, fingerprint
: Option
<String
>) -> Self {
78 self.fingerprint
= fingerprint
;
82 pub fn interactive(mut self, interactive
: bool
) -> Self {
83 self.interactive
= interactive
;
87 pub fn ticket_cache(mut self, ticket_cache
: bool
) -> Self {
88 self.ticket_cache
= ticket_cache
;
92 pub fn fingerprint_cache(mut self, fingerprint_cache
: bool
) -> Self {
93 self.fingerprint_cache
= fingerprint_cache
;
97 pub fn verify_cert(mut self, verify_cert
: bool
) -> Self {
98 self.verify_cert
= verify_cert
;
103 /// HTTP(S) API client
104 pub struct HttpClient
{
105 client
: Client
<HttpsConnector
>,
107 fingerprint
: Arc
<Mutex
<Option
<String
>>>,
108 auth
: BroadcastFuture
<AuthInfo
>,
109 _options
: HttpClientOptions
,
112 /// Delete stored ticket data (logout)
113 pub fn delete_ticket_info(prefix
: &str, server
: &str, username
: &str) -> Result
<(), Error
> {
115 let base
= BaseDirectories
::with_prefix(prefix
)?
;
117 // usually /run/user/<uid>/...
118 let path
= base
.place_runtime_file("tickets")?
;
120 let mode
= nix
::sys
::stat
::Mode
::from_bits_truncate(0o0600);
122 let mut data
= file_get_json(&path
, Some(json
!({}
)))?
;
124 if let Some(map
) = data
[server
].as_object_mut() {
125 map
.remove(username
);
128 replace_file(path
, data
.to_string().as_bytes(), CreateOptions
::new().perm(mode
))?
;
133 fn store_fingerprint(prefix
: &str, server
: &str, fingerprint
: &str) -> Result
<(), Error
> {
135 let base
= BaseDirectories
::with_prefix(prefix
)?
;
137 // usually ~/.config/<prefix>/fingerprints
138 let path
= base
.place_config_file("fingerprints")?
;
140 let raw
= match std
::fs
::read_to_string(&path
) {
143 if err
.kind() == std
::io
::ErrorKind
::NotFound
{
146 bail
!("unable to read fingerprints from {:?} - {}", path
, err
);
151 let mut result
= String
::new();
153 raw
.split('
\n'
).for_each(|line
| {
154 let items
: Vec
<String
> = line
.split_whitespace().map(String
::from
).collect();
155 if items
.len() == 2 {
156 if &items
[0] == server
{
157 // found, add later with new fingerprint
159 result
.push_str(line
);
165 result
.push_str(server
);
167 result
.push_str(fingerprint
);
170 replace_file(path
, result
.as_bytes(), CreateOptions
::new())?
;
175 fn load_fingerprint(prefix
: &str, server
: &str) -> Option
<String
> {
177 let base
= BaseDirectories
::with_prefix(prefix
).ok()?
;
179 // usually ~/.config/<prefix>/fingerprints
180 let path
= base
.place_config_file("fingerprints").ok()?
;
182 let raw
= std
::fs
::read_to_string(&path
).ok()?
;
184 for line
in raw
.split('
\n'
) {
185 let items
: Vec
<String
> = line
.split_whitespace().map(String
::from
).collect();
186 if items
.len() == 2 {
187 if &items
[0] == server
{
188 return Some(items
[1].clone());
196 fn store_ticket_info(prefix
: &str, server
: &str, username
: &str, ticket
: &str, token
: &str) -> Result
<(), Error
> {
198 let base
= BaseDirectories
::with_prefix(prefix
)?
;
200 // usually /run/user/<uid>/...
201 let path
= base
.place_runtime_file("tickets")?
;
203 let mode
= nix
::sys
::stat
::Mode
::from_bits_truncate(0o0600);
205 let mut data
= file_get_json(&path
, Some(json
!({}
)))?
;
207 let now
= Utc
::now().timestamp();
209 data
[server
][username
] = json
!({ "timestamp": now, "ticket": ticket, "token": token}
);
211 let mut new_data
= json
!({}
);
213 let ticket_lifetime
= tools
::ticket
::TICKET_LIFETIME
- 60;
215 let empty
= serde_json
::map
::Map
::new();
216 for (server
, info
) in data
.as_object().unwrap_or(&empty
) {
217 for (_user
, uinfo
) in info
.as_object().unwrap_or(&empty
) {
218 if let Some(timestamp
) = uinfo
["timestamp"].as_i64() {
219 let age
= now
- timestamp
;
220 if age
< ticket_lifetime
{
221 new_data
[server
][username
] = uinfo
.clone();
227 replace_file(path
, new_data
.to_string().as_bytes(), CreateOptions
::new().perm(mode
))?
;
232 fn load_ticket_info(prefix
: &str, server
: &str, username
: &str) -> Option
<(String
, String
)> {
233 let base
= BaseDirectories
::with_prefix(prefix
).ok()?
;
235 // usually /run/user/<uid>/...
236 let path
= base
.place_runtime_file("tickets").ok()?
;
237 let data
= file_get_json(&path
, None
).ok()?
;
238 let now
= Utc
::now().timestamp();
239 let ticket_lifetime
= tools
::ticket
::TICKET_LIFETIME
- 60;
240 let uinfo
= data
[server
][username
].as_object()?
;
241 let timestamp
= uinfo
["timestamp"].as_i64()?
;
242 let age
= now
- timestamp
;
244 if age
< ticket_lifetime
{
245 let ticket
= uinfo
["ticket"].as_str()?
;
246 let token
= uinfo
["token"].as_str()?
;
247 Some((ticket
.to_owned(), token
.to_owned()))
255 pub fn new(server
: &str, username
: &str, mut options
: HttpClientOptions
) -> Result
<Self, Error
> {
257 let verified_fingerprint
= Arc
::new(Mutex
::new(None
));
259 let mut fingerprint
= options
.fingerprint
.take();
260 if options
.fingerprint_cache
&& fingerprint
.is_none() && options
.prefix
.is_some() {
261 fingerprint
= load_fingerprint(options
.prefix
.as_ref().unwrap(), server
);
264 let mut ssl_connector_builder
= SslConnector
::builder(SslMethod
::tls()).unwrap();
266 if options
.verify_cert
{
267 let server
= server
.to_string();
268 let verified_fingerprint
= verified_fingerprint
.clone();
269 let interactive
= options
.interactive
;
270 let fingerprint_cache
= options
.fingerprint_cache
;
271 let prefix
= options
.prefix
.clone();
272 ssl_connector_builder
.set_verify_callback(openssl
::ssl
::SslVerifyMode
::PEER
, move |valid
, ctx
| {
273 let (valid
, fingerprint
) = Self::verify_callback(valid
, ctx
, fingerprint
.clone(), interactive
);
275 if let Some(fingerprint
) = fingerprint
{
276 if fingerprint_cache
&& prefix
.is_some() {
277 if let Err(err
) = store_fingerprint(
278 prefix
.as_ref().unwrap(), &server
, &fingerprint
) {
279 eprintln
!("{}", err
);
282 *verified_fingerprint
.lock().unwrap() = Some(fingerprint
);
288 ssl_connector_builder
.set_verify(openssl
::ssl
::SslVerifyMode
::NONE
);
291 let mut httpc
= hyper
::client
::HttpConnector
::new();
292 httpc
.set_nodelay(true); // important for h2 download performance!
293 httpc
.set_recv_buffer_size(Some(1024*1024)); //important for h2 download performance!
294 httpc
.enforce_http(false); // we want https...
296 let https
= HttpsConnector
::with_connector(httpc
, ssl_connector_builder
.build());
298 let client
= Client
::builder()
299 //.http2_initial_stream_window_size( (1 << 31) - 2)
300 //.http2_initial_connection_window_size( (1 << 31) - 2)
301 .build
::<_
, Body
>(https
);
303 let password
= options
.password
.take();
304 let use_ticket_cache
= options
.ticket_cache
&& options
.prefix
.is_some();
306 let password
= if let Some(password
) = password
{
309 let mut ticket_info
= None
;
310 if use_ticket_cache
{
311 ticket_info
= load_ticket_info(options
.prefix
.as_ref().unwrap(), server
, username
);
313 if let Some((ticket
, _token
)) = ticket_info
{
316 Self::get_password(&username
, options
.interactive
, options
.password_env
.clone())?
320 let login_future
= Self::credentials(
326 let server
= server
.to_string();
327 let prefix
= options
.prefix
.clone();
330 if use_ticket_cache
& &prefix
.is_some() {
331 let _
= store_ticket_info(prefix
.as_ref().unwrap(), &server
, &auth
.username
, &auth
.ticket
, &auth
.token
);
340 server
: String
::from(server
),
341 fingerprint
: verified_fingerprint
,
342 auth
: BroadcastFuture
::new(Box
::new(login_future
)),
349 /// Login is done on demand, so this is onyl required if you need
350 /// access to authentication data in 'AuthInfo'.
351 pub async
fn login(&self) -> Result
<AuthInfo
, Error
> {
352 self.auth
.listen().await
355 /// Returns the optional fingerprint passed to the new() constructor.
356 pub fn fingerprint(&self) -> Option
<String
> {
357 (*self.fingerprint
.lock().unwrap()).clone()
360 fn get_password(username
: &str, interactive
: bool
, password_env
: Option
<String
>) -> Result
<String
, Error
> {
361 if let Some(password_env
) = password_env
{
362 use std
::env
::VarError
::*;
363 match std
::env
::var(&password_env
) {
364 Ok(p
) => return Ok(p
),
365 Err(NotUnicode(_
)) => bail
!(format
!("{} contains bad characters", password_env
)),
367 // Try another method
372 // If we're on a TTY, query the user for a password
373 if interactive
&& tty
::stdin_isatty() {
374 let msg
= format
!("Password for \"{}\": ", username
);
375 return Ok(String
::from_utf8(tty
::read_password(&msg
)?
)?
);
378 bail
!("no password input mechanism available");
383 &mut X509StoreContextRef
,
384 expected_fingerprint
: Option
<String
>,
386 ) -> (bool
, Option
<String
>) {
387 if valid { return (true, None); }
389 let cert
= match ctx
.current_cert() {
391 None
=> return (false, None
),
394 let depth
= ctx
.error_depth();
395 if depth
!= 0 { return (false, None); }
397 let fp
= match cert
.digest(openssl
::hash
::MessageDigest
::sha256()) {
399 Err(_
) => return (false, None
), // should not happen
401 let fp_string
= proxmox
::tools
::digest_to_hex(&fp
);
402 let fp_string
= fp_string
.as_bytes().chunks(2).map(|v
| std
::str::from_utf8(v
).unwrap())
403 .collect
::<Vec
<&str>>().join(":");
405 if let Some(expected_fingerprint
) = expected_fingerprint
{
406 if expected_fingerprint
== fp_string
{
407 return (true, Some(fp_string
));
409 return (false, None
);
413 // If we're on a TTY, query the user
414 if interactive
&& tty
::stdin_isatty() {
415 println
!("fingerprint: {}", fp_string
);
417 print
!("Want to trust? (y/n): ");
418 let _
= std
::io
::stdout().flush();
419 let mut buf
= [0u8; 1];
421 match std
::io
::stdin().read_exact(&mut buf
) {
423 if buf
[0] == b'y'
|| buf
[0] == b'Y'
{
424 return (true, Some(fp_string
));
425 } else if buf
[0] == b'n'
|| buf
[0] == b'N'
{
426 return (false, None
);
430 return (false, None
);
438 pub async
fn request(&self, mut req
: Request
<Body
>) -> Result
<Value
, Error
> {
440 let client
= self.client
.clone();
442 let auth
= self.login().await?
;
444 let enc_ticket
= format
!("PBSAuthCookie={}", percent_encode(auth
.ticket
.as_bytes(), DEFAULT_ENCODE_SET
));
445 req
.headers_mut().insert("Cookie", HeaderValue
::from_str(&enc_ticket
).unwrap());
446 req
.headers_mut().insert("CSRFPreventionToken", HeaderValue
::from_str(&auth
.token
).unwrap());
448 Self::api_request(client
, req
).await
455 ) -> Result
<Value
, Error
> {
456 let req
= Self::request_builder(&self.server
, "GET", path
, data
).unwrap();
457 self.request(req
).await
464 ) -> Result
<Value
, Error
> {
465 let req
= Self::request_builder(&self.server
, "DELETE", path
, data
).unwrap();
466 self.request(req
).await
473 ) -> Result
<Value
, Error
> {
474 let req
= Self::request_builder(&self.server
, "POST", path
, data
).unwrap();
475 self.request(req
).await
478 pub async
fn download(
481 output
: &mut (dyn Write
+ Send
),
482 ) -> Result
<(), Error
> {
483 let mut req
= Self::request_builder(&self.server
, "GET", path
, None
).unwrap();
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());
492 let resp
= client
.request(req
).await?
;
493 let status
= resp
.status();
494 if !status
.is_success() {
495 HttpClient
::api_response(resp
)
496 .map(|_
| Err(format_err
!("unknown error")))
500 .map_err(Error
::from
)
501 .try_fold(output
, move |acc
, chunk
| async
move {
502 acc
.write_all(&chunk
)?
;
516 ) -> Result
<Value
, Error
> {
518 let path
= path
.trim_matches('
/'
);
519 let mut url
= format
!("https://{}:8007/{}", &self.server
, path
);
521 if let Some(data
) = data
{
522 let query
= tools
::json_object_to_query(data
).unwrap();
524 url
.push_str(&query
);
527 let url
: Uri
= url
.parse().unwrap();
529 let req
= Request
::builder()
532 .header("User-Agent", "proxmox-backup-client/1.0")
533 .header("Content-Type", content_type
)
534 .body(body
).unwrap();
536 self.request(req
).await
539 pub async
fn start_h2_connection(
541 mut req
: Request
<Body
>,
542 protocol_name
: String
,
543 ) -> Result
<(H2Client
, futures
::future
::AbortHandle
), Error
> {
545 let auth
= self.login().await?
;
546 let client
= self.client
.clone();
548 let enc_ticket
= format
!("PBSAuthCookie={}", percent_encode(auth
.ticket
.as_bytes(), DEFAULT_ENCODE_SET
));
549 req
.headers_mut().insert("Cookie", HeaderValue
::from_str(&enc_ticket
).unwrap());
550 req
.headers_mut().insert("UPGRADE", HeaderValue
::from_str(&protocol_name
).unwrap());
552 let resp
= client
.request(req
).await?
;
553 let status
= resp
.status();
555 if status
!= http
::StatusCode
::SWITCHING_PROTOCOLS
{
556 Self::api_response(resp
).await?
;
557 bail
!("unknown error");
565 let max_window_size
= (1 << 31) - 2;
567 let (h2
, connection
) = h2
::client
::Builder
::new()
568 .initial_connection_window_size(max_window_size
)
569 .initial_window_size(max_window_size
)
570 .max_frame_size(4*1024*1024)
574 let connection
= connection
575 .map_err(|_
| panic
!("HTTP/2.0 connection failed"));
577 let (connection
, abort
) = futures
::future
::abortable(connection
);
578 // A cancellable future returns an Option which is None when cancelled and
579 // Some when it finished instead, since we don't care about the return type we
580 // need to map it away:
581 let connection
= connection
.map(|_
| ());
583 // Spawn a new task to drive the connection state
584 tokio
::spawn(connection
);
586 // Wait until the `SendRequest` handle has available capacity.
587 let c
= h2
.ready().await?
;
588 Ok((H2Client
::new(c
), abort
))
591 async
fn credentials(
592 client
: Client
<HttpsConnector
>,
596 ) -> Result
<AuthInfo
, Error
> {
597 let data
= json
!({ "username": username, "password": password }
);
598 let req
= Self::request_builder(&server
, "POST", "/api2/json/access/ticket", Some(data
)).unwrap();
599 let cred
= Self::api_request(client
, req
).await?
;
600 let auth
= AuthInfo
{
601 username
: cred
["data"]["username"].as_str().unwrap().to_owned(),
602 ticket
: cred
["data"]["ticket"].as_str().unwrap().to_owned(),
603 token
: cred
["data"]["CSRFPreventionToken"].as_str().unwrap().to_owned(),
609 async
fn api_response(response
: Response
<Body
>) -> Result
<Value
, Error
> {
610 let status
= response
.status();
611 let data
= hyper
::body
::to_bytes(response
.into_body()).await?
;
613 let text
= String
::from_utf8(data
.to_vec()).unwrap();
614 if status
.is_success() {
618 let value
: Value
= serde_json
::from_str(&text
)?
;
622 bail
!("HTTP Error {}: {}", status
, text
);
626 async
fn api_request(
627 client
: Client
<HttpsConnector
>,
629 ) -> Result
<Value
, Error
> {
632 .map_err(Error
::from
)
633 .and_then(Self::api_response
)
637 // Read-only access to server property
638 pub fn server(&self) -> &str {
642 pub fn request_builder(server
: &str, method
: &str, path
: &str, data
: Option
<Value
>) -> Result
<Request
<Body
>, Error
> {
643 let path
= path
.trim_matches('
/'
);
644 let url
: Uri
= format
!("https://{}:8007/{}", server
, path
).parse()?
;
646 if let Some(data
) = data
{
647 if method
== "POST" {
648 let request
= Request
::builder()
651 .header("User-Agent", "proxmox-backup-client/1.0")
652 .header(hyper
::header
::CONTENT_TYPE
, "application/json")
653 .body(Body
::from(data
.to_string()))?
;
656 let query
= tools
::json_object_to_query(data
)?
;
657 let url
: Uri
= format
!("https://{}:8007/{}?{}", server
, path
, query
).parse()?
;
658 let request
= Request
::builder()
661 .header("User-Agent", "proxmox-backup-client/1.0")
662 .header(hyper
::header
::CONTENT_TYPE
, "application/x-www-form-urlencoded")
663 .body(Body
::empty())?
;
668 let request
= Request
::builder()
671 .header("User-Agent", "proxmox-backup-client/1.0")
672 .header(hyper
::header
::CONTENT_TYPE
, "application/x-www-form-urlencoded")
673 .body(Body
::empty())?
;
681 pub struct H2Client
{
682 h2
: h2
::client
::SendRequest
<bytes
::Bytes
>,
687 pub fn new(h2
: h2
::client
::SendRequest
<bytes
::Bytes
>) -> Self {
695 ) -> Result
<Value
, Error
> {
696 let req
= Self::request_builder("localhost", "GET", path
, param
, None
).unwrap();
697 self.request(req
).await
704 ) -> Result
<Value
, Error
> {
705 let req
= Self::request_builder("localhost", "PUT", path
, param
, None
).unwrap();
706 self.request(req
).await
713 ) -> Result
<Value
, Error
> {
714 let req
= Self::request_builder("localhost", "POST", path
, param
, None
).unwrap();
715 self.request(req
).await
718 pub async
fn download
<W
: Write
+ Send
>(
721 param
: Option
<Value
>,
723 ) -> Result
<W
, Error
> {
724 let request
= Self::request_builder("localhost", "GET", path
, param
, None
).unwrap();
726 let response_future
= self.send_request(request
, None
).await?
;
728 let resp
= response_future
.await?
;
730 let status
= resp
.status();
731 if !status
.is_success() {
732 H2Client
::h2api_response(resp
).await?
; // raise error
736 let mut body
= resp
.into_body();
737 while let Some(chunk
) = body
.data().await
{
739 body
.flow_control().release_capacity(chunk
.len())?
;
740 output
.write_all(&chunk
)?
;
748 method
: &str, // POST or PUT
750 param
: Option
<Value
>,
753 ) -> Result
<Value
, Error
> {
754 let request
= Self::request_builder("localhost", method
, path
, param
, Some(content_type
)).unwrap();
756 let mut send_request
= self.h2
.clone().ready().await?
;
758 let (response
, stream
) = send_request
.send_request(request
, false).unwrap();
760 PipeToSendStream
::new(bytes
::Bytes
::from(data
), stream
).await?
;
763 .map_err(Error
::from
)
764 .and_then(Self::h2api_response
)
770 request
: Request
<()>,
771 ) -> Result
<Value
, Error
> {
773 self.send_request(request
, None
)
774 .and_then(move |response
| {
776 .map_err(Error
::from
)
777 .and_then(Self::h2api_response
)
784 request
: Request
<()>,
785 data
: Option
<bytes
::Bytes
>,
786 ) -> impl Future
<Output
= Result
<h2
::client
::ResponseFuture
, Error
>> {
790 .map_err(Error
::from
)
791 .and_then(move |mut send_request
| async
move {
792 if let Some(data
) = data
{
793 let (response
, stream
) = send_request
.send_request(request
, false).unwrap();
794 PipeToSendStream
::new(data
, stream
).await?
;
797 let (response
, _stream
) = send_request
.send_request(request
, true).unwrap();
803 pub async
fn h2api_response(
804 response
: Response
<h2
::RecvStream
>,
805 ) -> Result
<Value
, Error
> {
806 let status
= response
.status();
808 let (_head
, mut body
) = response
.into_parts();
810 let mut data
= Vec
::new();
811 while let Some(chunk
) = body
.data().await
{
813 // Whenever data is received, the caller is responsible for
814 // releasing capacity back to the server once it has freed
815 // the data from memory.
816 // Let the server send more data.
817 body
.flow_control().release_capacity(chunk
.len())?
;
821 let text
= String
::from_utf8(data
.to_vec()).unwrap();
822 if status
.is_success() {
826 let mut value
: Value
= serde_json
::from_str(&text
)?
;
827 if let Some(map
) = value
.as_object_mut() {
828 if let Some(data
) = map
.remove("data") {
832 bail
!("got result without data property");
835 bail
!("HTTP Error {}: {}", status
, text
);
839 // Note: We always encode parameters with the url
840 pub fn request_builder(
844 param
: Option
<Value
>,
845 content_type
: Option
<&str>,
846 ) -> Result
<Request
<()>, Error
> {
847 let path
= path
.trim_matches('
/'
);
849 let content_type
= content_type
.unwrap_or("application/x-www-form-urlencoded");
851 if let Some(param
) = param
{
852 let query
= tools
::json_object_to_query(param
)?
;
853 // We detected problem with hyper around 6000 characters - seo we try to keep on the safe side
854 if query
.len() > 4096 { bail!("h2 query data too large ({} bytes
) - please encode data inside body
", query.len()); }
855 let url: Uri = format!("https
://{}:8007/{}?{}", server, path, query).parse()?;
856 let request
= Request
::builder()
859 .header("User-Agent", "proxmox-backup-client/1.0")
860 .header(hyper
::header
::CONTENT_TYPE
, content_type
)
864 let url
: Uri
= format
!("https://{}:8007/{}", server
, path
).parse()?
;
865 let request
= Request
::builder()
868 .header("User-Agent", "proxmox-backup-client/1.0")
869 .header(hyper
::header
::CONTENT_TYPE
, content_type
)
878 pub struct HttpsConnector
{
880 ssl_connector
: std
::sync
::Arc
<SslConnector
>,
883 impl HttpsConnector
{
884 pub fn with_connector(mut http
: HttpConnector
, ssl_connector
: SslConnector
) -> Self {
885 http
.enforce_http(false);
889 ssl_connector
: std
::sync
::Arc
::new(ssl_connector
),
894 type MaybeTlsStream
= EitherStream
<
895 tokio
::net
::TcpStream
,
896 tokio_openssl
::SslStream
<tokio
::net
::TcpStream
>,
899 impl hyper
::service
::Service
<Uri
> for HttpsConnector
{
900 type Response
= MaybeTlsStream
;
902 type Future
= std
::pin
::Pin
<Box
<
903 dyn Future
<Output
= Result
<Self::Response
, Self::Error
>> + Send
+ '
static
906 fn poll_ready(&mut self, _
: &mut Context
<'_
>) -> Poll
<Result
<(), Self::Error
>> {
907 // This connector is always ready, but others might not be.
911 fn call(&mut self, dst
: Uri
) -> Self::Future
{
912 let mut this
= self.clone();
916 .ok_or_else(|| format_err
!("missing URL scheme"))?
920 .ok_or_else(|| format_err
!("missing hostname in destination url?"))?
923 let config
= this
.ssl_connector
.configure();
924 let conn
= this
.http
.call(dst
).await?
;
926 let conn
= tokio_openssl
::connect(config?
, &host
, conn
).await?
;
927 Ok(MaybeTlsStream
::Right(conn
))
929 Ok(MaybeTlsStream
::Left(conn
))