Line data Source code
1 : use std::io;
2 : use std::net::{IpAddr, SocketAddr};
3 : use std::sync::Arc;
4 : use std::time::Duration;
5 :
6 : use async_trait::async_trait;
7 : use ed25519_dalek::SigningKey;
8 : use hyper_util::rt::{TokioExecutor, TokioIo, TokioTimer};
9 : use jose_jwk::jose_b64;
10 : use postgres_client::config::SslMode;
11 : use rand::rngs::OsRng;
12 : use rustls::pki_types::{DnsName, ServerName};
13 : use tokio::net::{TcpStream, lookup_host};
14 : use tokio_rustls::TlsConnector;
15 : use tracing::field::display;
16 : use tracing::{debug, info};
17 :
18 : use super::AsyncRW;
19 : use super::conn_pool::poll_client;
20 : use super::conn_pool_lib::{Client, ConnInfo, EndpointConnPool, GlobalConnPool};
21 : use super::http_conn_pool::{self, HttpConnPool, Send, poll_http2_client};
22 : use super::local_conn_pool::{self, EXT_NAME, EXT_SCHEMA, EXT_VERSION, LocalConnPool};
23 : use crate::auth::backend::local::StaticAuthRules;
24 : use crate::auth::backend::{ComputeCredentialKeys, ComputeCredentials, ComputeUserInfo};
25 : use crate::auth::{self, AuthError};
26 : use crate::compute_ctl::{
27 : ComputeCtlError, ExtensionInstallRequest, Privilege, SetRoleGrantsRequest,
28 : };
29 : use crate::config::{ComputeConfig, ProxyConfig};
30 : use crate::context::RequestContext;
31 : use crate::control_plane::CachedNodeInfo;
32 : use crate::control_plane::client::ApiLockError;
33 : use crate::control_plane::errors::{GetAuthInfoError, WakeComputeError};
34 : use crate::control_plane::locks::ApiLocks;
35 : use crate::error::{ErrorKind, ReportableError, UserFacingError};
36 : use crate::intern::EndpointIdInt;
37 : use crate::proxy::connect_compute::ConnectMechanism;
38 : use crate::proxy::retry::{CouldRetry, ShouldRetryWakeCompute};
39 : use crate::rate_limiter::EndpointRateLimiter;
40 : use crate::types::{EndpointId, Host, LOCAL_PROXY_SUFFIX};
41 :
42 : pub(crate) struct PoolingBackend {
43 : pub(crate) http_conn_pool: Arc<GlobalConnPool<Send, HttpConnPool<Send>>>,
44 : pub(crate) local_pool: Arc<LocalConnPool<postgres_client::Client>>,
45 : pub(crate) pool:
46 : Arc<GlobalConnPool<postgres_client::Client, EndpointConnPool<postgres_client::Client>>>,
47 :
48 : pub(crate) config: &'static ProxyConfig,
49 : pub(crate) auth_backend: &'static crate::auth::Backend<'static, ()>,
50 : pub(crate) endpoint_rate_limiter: Arc<EndpointRateLimiter>,
51 : }
52 :
53 : impl PoolingBackend {
54 0 : pub(crate) async fn authenticate_with_password(
55 0 : &self,
56 0 : ctx: &RequestContext,
57 0 : user_info: &ComputeUserInfo,
58 0 : password: &[u8],
59 0 : ) -> Result<ComputeCredentials, AuthError> {
60 0 : ctx.set_auth_method(crate::context::AuthMethod::Cleartext);
61 0 :
62 0 : let user_info = user_info.clone();
63 0 : let backend = self.auth_backend.as_ref().map(|()| user_info.clone());
64 0 : let access_control = backend.get_endpoint_access_control(ctx).await?;
65 0 : access_control.check(
66 0 : ctx,
67 0 : self.config.authentication_config.ip_allowlist_check_enabled,
68 0 : self.config.authentication_config.is_vpc_acccess_proxy,
69 0 : )?;
70 :
71 0 : access_control.connection_attempt_rate_limit(
72 0 : ctx,
73 0 : &user_info.endpoint,
74 0 : &self.endpoint_rate_limiter,
75 0 : )?;
76 :
77 0 : let role_access = backend.get_role_secret(ctx).await?;
78 0 : let Some(secret) = role_access.secret else {
79 : // If we don't have an authentication secret, for the http flow we can just return an error.
80 0 : info!("authentication info not found");
81 0 : return Err(AuthError::password_failed(&*user_info.user));
82 : };
83 :
84 0 : let ep = EndpointIdInt::from(&user_info.endpoint);
85 0 : let auth_outcome = crate::auth::validate_password_and_exchange(
86 0 : &self.config.authentication_config.thread_pool,
87 0 : ep,
88 0 : password,
89 0 : secret,
90 0 : )
91 0 : .await?;
92 0 : let res = match auth_outcome {
93 0 : crate::sasl::Outcome::Success(key) => {
94 0 : info!("user successfully authenticated");
95 0 : Ok(key)
96 : }
97 0 : crate::sasl::Outcome::Failure(reason) => {
98 0 : info!("auth backend failed with an error: {reason}");
99 0 : Err(AuthError::password_failed(&*user_info.user))
100 : }
101 : };
102 0 : res.map(|key| ComputeCredentials {
103 0 : info: user_info,
104 0 : keys: key,
105 0 : })
106 0 : }
107 :
108 0 : pub(crate) async fn authenticate_with_jwt(
109 0 : &self,
110 0 : ctx: &RequestContext,
111 0 : user_info: &ComputeUserInfo,
112 0 : jwt: String,
113 0 : ) -> Result<ComputeCredentials, AuthError> {
114 0 : ctx.set_auth_method(crate::context::AuthMethod::Jwt);
115 0 :
116 0 : match &self.auth_backend {
117 0 : crate::auth::Backend::ControlPlane(console, ()) => {
118 0 : self.config
119 0 : .authentication_config
120 0 : .jwks_cache
121 0 : .check_jwt(
122 0 : ctx,
123 0 : user_info.endpoint.clone(),
124 0 : &user_info.user,
125 0 : &**console,
126 0 : &jwt,
127 0 : )
128 0 : .await?;
129 :
130 0 : Ok(ComputeCredentials {
131 0 : info: user_info.clone(),
132 0 : keys: crate::auth::backend::ComputeCredentialKeys::None,
133 0 : })
134 : }
135 : crate::auth::Backend::Local(_) => {
136 0 : let keys = self
137 0 : .config
138 0 : .authentication_config
139 0 : .jwks_cache
140 0 : .check_jwt(
141 0 : ctx,
142 0 : user_info.endpoint.clone(),
143 0 : &user_info.user,
144 0 : &StaticAuthRules,
145 0 : &jwt,
146 0 : )
147 0 : .await?;
148 :
149 0 : Ok(ComputeCredentials {
150 0 : info: user_info.clone(),
151 0 : keys,
152 0 : })
153 : }
154 : }
155 0 : }
156 :
157 : // Wake up the destination if needed. Code here is a bit involved because
158 : // we reuse the code from the usual proxy and we need to prepare few structures
159 : // that this code expects.
160 : #[tracing::instrument(skip_all, fields(
161 : pid = tracing::field::Empty,
162 : compute_id = tracing::field::Empty,
163 : conn_id = tracing::field::Empty,
164 : ))]
165 : pub(crate) async fn connect_to_compute(
166 : &self,
167 : ctx: &RequestContext,
168 : conn_info: ConnInfo,
169 : keys: ComputeCredentials,
170 : force_new: bool,
171 : ) -> Result<Client<postgres_client::Client>, HttpConnError> {
172 : let maybe_client = if force_new {
173 : debug!("pool: pool is disabled");
174 : None
175 : } else {
176 : debug!("pool: looking for an existing connection");
177 : self.pool.get(ctx, &conn_info)?
178 : };
179 :
180 : if let Some(client) = maybe_client {
181 : return Ok(client);
182 : }
183 : let conn_id = uuid::Uuid::new_v4();
184 : tracing::Span::current().record("conn_id", display(conn_id));
185 : info!(%conn_id, "pool: opening a new connection '{conn_info}'");
186 0 : let backend = self.auth_backend.as_ref().map(|()| keys.info);
187 : crate::proxy::connect_compute::connect_to_compute(
188 : ctx,
189 : &TokioMechanism {
190 : conn_id,
191 : conn_info,
192 : pool: self.pool.clone(),
193 : locks: &self.config.connect_compute_locks,
194 : keys: keys.keys,
195 : },
196 : &backend,
197 : self.config.wake_compute_retry_config,
198 : &self.config.connect_to_compute,
199 : )
200 : .await
201 : }
202 :
203 : // Wake up the destination if needed
204 : #[tracing::instrument(skip_all, fields(
205 : compute_id = tracing::field::Empty,
206 : conn_id = tracing::field::Empty,
207 : ))]
208 : pub(crate) async fn connect_to_local_proxy(
209 : &self,
210 : ctx: &RequestContext,
211 : conn_info: ConnInfo,
212 : ) -> Result<http_conn_pool::Client<Send>, HttpConnError> {
213 : debug!("pool: looking for an existing connection");
214 : if let Ok(Some(client)) = self.http_conn_pool.get(ctx, &conn_info) {
215 : return Ok(client);
216 : }
217 :
218 : let conn_id = uuid::Uuid::new_v4();
219 : tracing::Span::current().record("conn_id", display(conn_id));
220 : debug!(%conn_id, "pool: opening a new connection '{conn_info}'");
221 0 : let backend = self.auth_backend.as_ref().map(|()| ComputeUserInfo {
222 0 : user: conn_info.user_info.user.clone(),
223 0 : endpoint: EndpointId::from(format!(
224 0 : "{}{LOCAL_PROXY_SUFFIX}",
225 0 : conn_info.user_info.endpoint.normalize()
226 0 : )),
227 0 : options: conn_info.user_info.options.clone(),
228 0 : });
229 : crate::proxy::connect_compute::connect_to_compute(
230 : ctx,
231 : &HyperMechanism {
232 : conn_id,
233 : conn_info,
234 : pool: self.http_conn_pool.clone(),
235 : locks: &self.config.connect_compute_locks,
236 : },
237 : &backend,
238 : self.config.wake_compute_retry_config,
239 : &self.config.connect_to_compute,
240 : )
241 : .await
242 : }
243 :
244 : /// Connect to postgres over localhost.
245 : ///
246 : /// We expect postgres to be started here, so we won't do any retries.
247 : ///
248 : /// # Panics
249 : ///
250 : /// Panics if called with a non-local_proxy backend.
251 : #[tracing::instrument(skip_all, fields(
252 : pid = tracing::field::Empty,
253 : conn_id = tracing::field::Empty,
254 : ))]
255 : pub(crate) async fn connect_to_local_postgres(
256 : &self,
257 : ctx: &RequestContext,
258 : conn_info: ConnInfo,
259 : ) -> Result<Client<postgres_client::Client>, HttpConnError> {
260 : if let Some(client) = self.local_pool.get(ctx, &conn_info)? {
261 : return Ok(client);
262 : }
263 :
264 : let local_backend = match &self.auth_backend {
265 : auth::Backend::ControlPlane(_, ()) => {
266 : unreachable!("only local_proxy can connect to local postgres")
267 : }
268 : auth::Backend::Local(local) => local,
269 : };
270 :
271 : if !self.local_pool.initialized(&conn_info) {
272 : // only install and grant usage one at a time.
273 : let _permit = local_backend
274 : .initialize
275 : .acquire()
276 : .await
277 : .expect("semaphore should never be closed");
278 :
279 : // check again for race
280 : if !self.local_pool.initialized(&conn_info) {
281 : local_backend
282 : .compute_ctl
283 : .install_extension(&ExtensionInstallRequest {
284 : extension: EXT_NAME,
285 : database: conn_info.dbname.clone(),
286 : version: EXT_VERSION,
287 : })
288 : .await?;
289 :
290 : local_backend
291 : .compute_ctl
292 : .grant_role(&SetRoleGrantsRequest {
293 : schema: EXT_SCHEMA,
294 : privileges: vec![Privilege::Usage],
295 : database: conn_info.dbname.clone(),
296 : role: conn_info.user_info.user.clone(),
297 : })
298 : .await?;
299 :
300 : self.local_pool.set_initialized(&conn_info);
301 : }
302 : }
303 :
304 : let conn_id = uuid::Uuid::new_v4();
305 : tracing::Span::current().record("conn_id", display(conn_id));
306 : info!(%conn_id, "local_pool: opening a new connection '{conn_info}'");
307 :
308 : let (key, jwk) = create_random_jwk();
309 :
310 : let mut config = local_backend
311 : .node_info
312 : .conn_info
313 : .to_postgres_client_config();
314 : config
315 : .user(&conn_info.user_info.user)
316 : .dbname(&conn_info.dbname)
317 : .set_param(
318 : "options",
319 : &format!(
320 : "-c pg_session_jwt.jwk={}",
321 : serde_json::to_string(&jwk).expect("serializing jwk to json should not fail")
322 : ),
323 : );
324 :
325 : let pause = ctx.latency_timer_pause(crate::metrics::Waiting::Compute);
326 : let (client, connection) = config.connect(&postgres_client::NoTls).await?;
327 : drop(pause);
328 :
329 : let pid = client.get_process_id();
330 : tracing::Span::current().record("pid", pid);
331 :
332 : let mut handle = local_conn_pool::poll_client(
333 : self.local_pool.clone(),
334 : ctx,
335 : conn_info,
336 : client,
337 : connection,
338 : key,
339 : conn_id,
340 : local_backend.node_info.aux.clone(),
341 : );
342 :
343 : {
344 : let (client, mut discard) = handle.inner();
345 : debug!("setting up backend session state");
346 :
347 : // initiates the auth session
348 : if let Err(e) = client.batch_execute("select auth.init();").await {
349 : discard.discard();
350 : return Err(e.into());
351 : }
352 :
353 : info!("backend session state initialized");
354 : }
355 :
356 : Ok(handle)
357 : }
358 : }
359 :
360 0 : fn create_random_jwk() -> (SigningKey, jose_jwk::Key) {
361 0 : let key = SigningKey::generate(&mut OsRng);
362 0 :
363 0 : let jwk = jose_jwk::Key::Okp(jose_jwk::Okp {
364 0 : crv: jose_jwk::OkpCurves::Ed25519,
365 0 : x: jose_b64::serde::Bytes::from(key.verifying_key().to_bytes().to_vec()),
366 0 : d: None,
367 0 : });
368 0 :
369 0 : (key, jwk)
370 0 : }
371 :
372 : #[derive(Debug, thiserror::Error)]
373 : pub(crate) enum HttpConnError {
374 : #[error("pooled connection closed at inconsistent state")]
375 : ConnectionClosedAbruptly(#[from] tokio::sync::watch::error::SendError<uuid::Uuid>),
376 : #[error("could not connect to postgres in compute")]
377 : PostgresConnectionError(#[from] postgres_client::Error),
378 : #[error("could not connect to local-proxy in compute")]
379 : LocalProxyConnectionError(#[from] LocalProxyConnError),
380 : #[error("could not parse JWT payload")]
381 : JwtPayloadError(serde_json::Error),
382 :
383 : #[error("could not install extension: {0}")]
384 : ComputeCtl(#[from] ComputeCtlError),
385 : #[error("could not get auth info")]
386 : GetAuthInfo(#[from] GetAuthInfoError),
387 : #[error("user not authenticated")]
388 : AuthError(#[from] AuthError),
389 : #[error("wake_compute returned error")]
390 : WakeCompute(#[from] WakeComputeError),
391 : #[error("error acquiring resource permit: {0}")]
392 : TooManyConnectionAttempts(#[from] ApiLockError),
393 : }
394 :
395 : #[derive(Debug, thiserror::Error)]
396 : pub(crate) enum LocalProxyConnError {
397 : #[error("error with connection to local-proxy")]
398 : Io(#[source] std::io::Error),
399 : #[error("could not establish h2 connection")]
400 : H2(#[from] hyper::Error),
401 : }
402 :
403 : impl ReportableError for HttpConnError {
404 0 : fn get_error_kind(&self) -> ErrorKind {
405 0 : match self {
406 0 : HttpConnError::ConnectionClosedAbruptly(_) => ErrorKind::Compute,
407 0 : HttpConnError::PostgresConnectionError(p) => p.get_error_kind(),
408 0 : HttpConnError::LocalProxyConnectionError(_) => ErrorKind::Compute,
409 0 : HttpConnError::ComputeCtl(_) => ErrorKind::Service,
410 0 : HttpConnError::JwtPayloadError(_) => ErrorKind::User,
411 0 : HttpConnError::GetAuthInfo(a) => a.get_error_kind(),
412 0 : HttpConnError::AuthError(a) => a.get_error_kind(),
413 0 : HttpConnError::WakeCompute(w) => w.get_error_kind(),
414 0 : HttpConnError::TooManyConnectionAttempts(w) => w.get_error_kind(),
415 : }
416 0 : }
417 : }
418 :
419 : impl UserFacingError for HttpConnError {
420 0 : fn to_string_client(&self) -> String {
421 0 : match self {
422 0 : HttpConnError::ConnectionClosedAbruptly(_) => self.to_string(),
423 0 : HttpConnError::PostgresConnectionError(p) => p.to_string(),
424 0 : HttpConnError::LocalProxyConnectionError(p) => p.to_string(),
425 0 : HttpConnError::ComputeCtl(_) => "could not set up the JWT authorization database extension".to_string(),
426 0 : HttpConnError::JwtPayloadError(p) => p.to_string(),
427 0 : HttpConnError::GetAuthInfo(c) => c.to_string_client(),
428 0 : HttpConnError::AuthError(c) => c.to_string_client(),
429 0 : HttpConnError::WakeCompute(c) => c.to_string_client(),
430 : HttpConnError::TooManyConnectionAttempts(_) => {
431 0 : "Failed to acquire permit to connect to the database. Too many database connection attempts are currently ongoing.".to_owned()
432 : }
433 : }
434 0 : }
435 : }
436 :
437 : impl CouldRetry for HttpConnError {
438 0 : fn could_retry(&self) -> bool {
439 0 : match self {
440 0 : HttpConnError::PostgresConnectionError(e) => e.could_retry(),
441 0 : HttpConnError::LocalProxyConnectionError(e) => e.could_retry(),
442 0 : HttpConnError::ComputeCtl(_) => false,
443 0 : HttpConnError::ConnectionClosedAbruptly(_) => false,
444 0 : HttpConnError::JwtPayloadError(_) => false,
445 0 : HttpConnError::GetAuthInfo(_) => false,
446 0 : HttpConnError::AuthError(_) => false,
447 0 : HttpConnError::WakeCompute(_) => false,
448 0 : HttpConnError::TooManyConnectionAttempts(_) => false,
449 : }
450 0 : }
451 : }
452 : impl ShouldRetryWakeCompute for HttpConnError {
453 0 : fn should_retry_wake_compute(&self) -> bool {
454 0 : match self {
455 0 : HttpConnError::PostgresConnectionError(e) => e.should_retry_wake_compute(),
456 : // we never checked cache validity
457 0 : HttpConnError::TooManyConnectionAttempts(_) => false,
458 0 : _ => true,
459 : }
460 0 : }
461 : }
462 :
463 : impl ReportableError for LocalProxyConnError {
464 0 : fn get_error_kind(&self) -> ErrorKind {
465 0 : match self {
466 0 : LocalProxyConnError::Io(_) => ErrorKind::Compute,
467 0 : LocalProxyConnError::H2(_) => ErrorKind::Compute,
468 : }
469 0 : }
470 : }
471 :
472 : impl UserFacingError for LocalProxyConnError {
473 0 : fn to_string_client(&self) -> String {
474 0 : "Could not establish HTTP connection to the database".to_string()
475 0 : }
476 : }
477 :
478 : impl CouldRetry for LocalProxyConnError {
479 0 : fn could_retry(&self) -> bool {
480 0 : match self {
481 0 : LocalProxyConnError::Io(_) => false,
482 0 : LocalProxyConnError::H2(_) => false,
483 : }
484 0 : }
485 : }
486 : impl ShouldRetryWakeCompute for LocalProxyConnError {
487 0 : fn should_retry_wake_compute(&self) -> bool {
488 0 : match self {
489 0 : LocalProxyConnError::Io(_) => false,
490 0 : LocalProxyConnError::H2(_) => false,
491 : }
492 0 : }
493 : }
494 :
495 : struct TokioMechanism {
496 : pool: Arc<GlobalConnPool<postgres_client::Client, EndpointConnPool<postgres_client::Client>>>,
497 : conn_info: ConnInfo,
498 : conn_id: uuid::Uuid,
499 : keys: ComputeCredentialKeys,
500 :
501 : /// connect_to_compute concurrency lock
502 : locks: &'static ApiLocks<Host>,
503 : }
504 :
505 : #[async_trait]
506 : impl ConnectMechanism for TokioMechanism {
507 : type Connection = Client<postgres_client::Client>;
508 : type ConnectError = HttpConnError;
509 : type Error = HttpConnError;
510 :
511 0 : async fn connect_once(
512 0 : &self,
513 0 : ctx: &RequestContext,
514 0 : node_info: &CachedNodeInfo,
515 0 : compute_config: &ComputeConfig,
516 0 : ) -> Result<Self::Connection, Self::ConnectError> {
517 0 : let permit = self.locks.get_permit(&node_info.conn_info.host).await?;
518 :
519 0 : let mut config = node_info.conn_info.to_postgres_client_config();
520 0 : let config = config
521 0 : .user(&self.conn_info.user_info.user)
522 0 : .dbname(&self.conn_info.dbname)
523 0 : .connect_timeout(compute_config.timeout);
524 :
525 0 : if let ComputeCredentialKeys::AuthKeys(auth_keys) = self.keys {
526 0 : config.auth_keys(auth_keys);
527 0 : }
528 :
529 0 : let pause = ctx.latency_timer_pause(crate::metrics::Waiting::Compute);
530 0 : let res = config.connect(compute_config).await;
531 0 : drop(pause);
532 0 : let (client, connection) = permit.release_result(res)?;
533 :
534 0 : tracing::Span::current().record("pid", tracing::field::display(client.get_process_id()));
535 0 : tracing::Span::current().record(
536 0 : "compute_id",
537 0 : tracing::field::display(&node_info.aux.compute_id),
538 0 : );
539 :
540 0 : if let Some(query_id) = ctx.get_testodrome_id() {
541 0 : info!("latency={}, query_id={}", ctx.get_proxy_latency(), query_id);
542 0 : }
543 :
544 0 : Ok(poll_client(
545 0 : self.pool.clone(),
546 0 : ctx,
547 0 : self.conn_info.clone(),
548 0 : client,
549 0 : connection,
550 0 : self.conn_id,
551 0 : node_info.aux.clone(),
552 0 : ))
553 0 : }
554 : }
555 :
556 : struct HyperMechanism {
557 : pool: Arc<GlobalConnPool<Send, HttpConnPool<Send>>>,
558 : conn_info: ConnInfo,
559 : conn_id: uuid::Uuid,
560 :
561 : /// connect_to_compute concurrency lock
562 : locks: &'static ApiLocks<Host>,
563 : }
564 :
565 : #[async_trait]
566 : impl ConnectMechanism for HyperMechanism {
567 : type Connection = http_conn_pool::Client<Send>;
568 : type ConnectError = HttpConnError;
569 : type Error = HttpConnError;
570 :
571 0 : async fn connect_once(
572 0 : &self,
573 0 : ctx: &RequestContext,
574 0 : node_info: &CachedNodeInfo,
575 0 : config: &ComputeConfig,
576 0 : ) -> Result<Self::Connection, Self::ConnectError> {
577 0 : let host_addr = node_info.conn_info.host_addr;
578 0 : let host = &node_info.conn_info.host;
579 0 : let permit = self.locks.get_permit(host).await?;
580 :
581 0 : let pause = ctx.latency_timer_pause(crate::metrics::Waiting::Compute);
582 :
583 0 : let tls = if node_info.conn_info.ssl_mode == SslMode::Disable {
584 0 : None
585 : } else {
586 0 : Some(&config.tls)
587 : };
588 :
589 0 : let port = node_info.conn_info.port;
590 0 : let res = connect_http2(host_addr, host, port, config.timeout, tls).await;
591 0 : drop(pause);
592 0 : let (client, connection) = permit.release_result(res)?;
593 :
594 0 : tracing::Span::current().record(
595 0 : "compute_id",
596 0 : tracing::field::display(&node_info.aux.compute_id),
597 0 : );
598 :
599 0 : if let Some(query_id) = ctx.get_testodrome_id() {
600 0 : info!("latency={}, query_id={}", ctx.get_proxy_latency(), query_id);
601 0 : }
602 :
603 0 : Ok(poll_http2_client(
604 0 : self.pool.clone(),
605 0 : ctx,
606 0 : &self.conn_info,
607 0 : client,
608 0 : connection,
609 0 : self.conn_id,
610 0 : node_info.aux.clone(),
611 0 : ))
612 0 : }
613 : }
614 :
615 0 : async fn connect_http2(
616 0 : host_addr: Option<IpAddr>,
617 0 : host: &str,
618 0 : port: u16,
619 0 : timeout: Duration,
620 0 : tls: Option<&Arc<rustls::ClientConfig>>,
621 0 : ) -> Result<(http_conn_pool::Send, http_conn_pool::Connect), LocalProxyConnError> {
622 0 : let addrs = match host_addr {
623 0 : Some(addr) => vec![SocketAddr::new(addr, port)],
624 0 : None => lookup_host((host, port))
625 0 : .await
626 0 : .map_err(LocalProxyConnError::Io)?
627 0 : .collect(),
628 : };
629 0 : let mut last_err = None;
630 0 :
631 0 : let mut addrs = addrs.into_iter();
632 0 : let stream = loop {
633 0 : let Some(addr) = addrs.next() else {
634 0 : return Err(last_err.unwrap_or_else(|| {
635 0 : LocalProxyConnError::Io(io::Error::new(
636 0 : io::ErrorKind::InvalidInput,
637 0 : "could not resolve any addresses",
638 0 : ))
639 0 : }));
640 : };
641 :
642 0 : match tokio::time::timeout(timeout, TcpStream::connect(addr)).await {
643 0 : Ok(Ok(stream)) => {
644 0 : stream.set_nodelay(true).map_err(LocalProxyConnError::Io)?;
645 0 : break stream;
646 : }
647 0 : Ok(Err(e)) => {
648 0 : last_err = Some(LocalProxyConnError::Io(e));
649 0 : }
650 0 : Err(e) => {
651 0 : last_err = Some(LocalProxyConnError::Io(io::Error::new(
652 0 : io::ErrorKind::TimedOut,
653 0 : e,
654 0 : )));
655 0 : }
656 : }
657 : };
658 :
659 0 : let stream = if let Some(tls) = tls {
660 0 : let host = DnsName::try_from(host)
661 0 : .map_err(io::Error::other)
662 0 : .map_err(LocalProxyConnError::Io)?
663 0 : .to_owned();
664 0 : let stream = TlsConnector::from(tls.clone())
665 0 : .connect(ServerName::DnsName(host), stream)
666 0 : .await
667 0 : .map_err(LocalProxyConnError::Io)?;
668 0 : Box::pin(stream) as AsyncRW
669 : } else {
670 0 : Box::pin(stream) as AsyncRW
671 : };
672 :
673 0 : let (client, connection) = hyper::client::conn::http2::Builder::new(TokioExecutor::new())
674 0 : .timer(TokioTimer::new())
675 0 : .keep_alive_interval(Duration::from_secs(20))
676 0 : .keep_alive_while_idle(true)
677 0 : .keep_alive_timeout(Duration::from_secs(5))
678 0 : .handshake(TokioIo::new(stream))
679 0 : .await?;
680 :
681 0 : Ok((client, connection))
682 0 : }
|