Skip to main content

demesne_postgres/
connect.rs

1use crate::dsn::{self, ConnConfig, Roots, SessionAttrs, TlsPlan, Verify};
2use crate::goerr::errno_text;
3use postgres::config::{ChannelBinding, SslMode, SslNegotiation};
4use postgres::{Client, NoTls};
5use rustls::client::WebPkiServerVerifier;
6use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
7use rustls::crypto::{CryptoProvider, verify_tls12_signature, verify_tls13_signature};
8use rustls::pki_types::{CertificateDer, ServerName, UnixTime};
9use rustls::{AlertDescription, CertificateError, ClientConfig, DigitallySignedStruct, RootCertStore, SignatureScheme};
10use std::error::Error as StdError;
11use std::net::{IpAddr, ToSocketAddrs};
12use std::sync::Arc;
13
14const PROTOCOL_3_0: i32 = 3 << 16;
15
16const FIRST_PROTOCOL_3_2_SERVER: i64 = 180_000;
17
18enum Addr {
19    Tcp(IpAddr),
20    Unix(String),
21}
22
23struct Attempt<'a> {
24    addr: Addr,
25    port: u16,
26    address: String,
27    original: &'a str,
28    tls: Option<&'a Arc<TlsPlan>>,
29}
30
31struct Failure {
32    text: String,
33    code: Option<String>,
34    not_preferred: bool,
35}
36
37impl Failure {
38    fn plain(text: impl Into<String>) -> Self {
39        Failure { text: text.into(), code: None, not_preferred: false }
40    }
41}
42
43#[derive(Debug)]
44struct NoVerify(Arc<CryptoProvider>);
45
46impl ServerCertVerifier for NoVerify {
47    fn verify_server_cert(
48        &self,
49        _end_entity: &CertificateDer<'_>,
50        _intermediates: &[CertificateDer<'_>],
51        _server_name: &ServerName<'_>,
52        _ocsp_response: &[u8],
53        _now: UnixTime,
54    ) -> Result<ServerCertVerified, rustls::Error> {
55        Ok(ServerCertVerified::assertion())
56    }
57
58    fn verify_tls12_signature(&self, message: &[u8], cert: &CertificateDer<'_>, dss: &DigitallySignedStruct) -> Result<HandshakeSignatureValid, rustls::Error> {
59        verify_tls12_signature(message, cert, dss, &self.0.signature_verification_algorithms)
60    }
61
62    fn verify_tls13_signature(&self, message: &[u8], cert: &CertificateDer<'_>, dss: &DigitallySignedStruct) -> Result<HandshakeSignatureValid, rustls::Error> {
63        verify_tls13_signature(message, cert, dss, &self.0.signature_verification_algorithms)
64    }
65
66    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
67        self.0.signature_verification_algorithms.supported_schemes()
68    }
69}
70
71#[derive(Debug)]
72struct ChainOnly(Arc<WebPkiServerVerifier>);
73
74impl ServerCertVerifier for ChainOnly {
75    fn verify_server_cert(
76        &self,
77        end_entity: &CertificateDer<'_>,
78        intermediates: &[CertificateDer<'_>],
79        server_name: &ServerName<'_>,
80        ocsp_response: &[u8],
81        now: UnixTime,
82    ) -> Result<ServerCertVerified, rustls::Error> {
83        match self.0.verify_server_cert(end_entity, intermediates, server_name, ocsp_response, now) {
84            Err(rustls::Error::InvalidCertificate(CertificateError::NotValidForName | CertificateError::NotValidForNameContext { .. })) => {
85                Ok(ServerCertVerified::assertion())
86            }
87            other => other,
88        }
89    }
90
91    fn verify_tls12_signature(&self, message: &[u8], cert: &CertificateDer<'_>, dss: &DigitallySignedStruct) -> Result<HandshakeSignatureValid, rustls::Error> {
92        self.0.verify_tls12_signature(message, cert, dss)
93    }
94
95    fn verify_tls13_signature(&self, message: &[u8], cert: &CertificateDer<'_>, dss: &DigitallySignedStruct) -> Result<HandshakeSignatureValid, rustls::Error> {
96        self.0.verify_tls13_signature(message, cert, dss)
97    }
98
99    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
100        self.0.supported_verify_schemes()
101    }
102}
103
104#[derive(Debug)]
105struct NameFirst(Arc<WebPkiServerVerifier>);
106
107impl ServerCertVerifier for NameFirst {
108    fn verify_server_cert(
109        &self,
110        end_entity: &CertificateDer<'_>,
111        intermediates: &[CertificateDer<'_>],
112        server_name: &ServerName<'_>,
113        ocsp_response: &[u8],
114        now: UnixTime,
115    ) -> Result<ServerCertVerified, rustls::Error> {
116        let Ok(cert) = webpki::EndEntityCert::try_from(end_entity) else {
117            return Err(rustls::Error::InvalidCertificate(CertificateError::BadEncoding));
118        };
119        if let Err(webpki::Error::CertNotValidForName(ctx)) = cert.verify_is_valid_for_subject_name(server_name) {
120            return Err(rustls::Error::InvalidCertificate(CertificateError::NotValidForNameContext { expected: ctx.expected, presented: ctx.presented }));
121        }
122        self.0.verify_server_cert(end_entity, intermediates, server_name, ocsp_response, now)
123    }
124
125    fn verify_tls12_signature(&self, message: &[u8], cert: &CertificateDer<'_>, dss: &DigitallySignedStruct) -> Result<HandshakeSignatureValid, rustls::Error> {
126        self.0.verify_tls12_signature(message, cert, dss)
127    }
128
129    fn verify_tls13_signature(&self, message: &[u8], cert: &CertificateDer<'_>, dss: &DigitallySignedStruct) -> Result<HandshakeSignatureValid, rustls::Error> {
130        self.0.verify_tls13_signature(message, cert, dss)
131    }
132
133    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
134        self.0.supported_verify_schemes()
135    }
136}
137
138fn webpki_verifier(roots: &Roots, provider: &Arc<CryptoProvider>) -> Result<Arc<WebPkiServerVerifier>, String> {
139    let mut store = RootCertStore::empty();
140    match roots {
141        Roots::Pem(certs) => {
142            store.add_parsable_certificates(certs.iter().cloned());
143        }
144        Roots::System => {
145            store.add_parsable_certificates(rustls_native_certs::load_native_certs().certs);
146        }
147    }
148    let Ok(verifier) = WebPkiServerVerifier::builder_with_provider(Arc::new(store), Arc::clone(provider)).build() else {
149        return Err("tls: failed to verify certificate: x509: failed to load system roots and no roots provided".to_string());
150    };
151    Ok(verifier)
152}
153
154fn rustls_config(plan: &TlsPlan) -> Result<ClientConfig, String> {
155    let provider = Arc::new(rustls::crypto::ring::default_provider());
156    let verifier: Arc<dyn ServerCertVerifier> = match plan.verify {
157        Verify::None => Arc::new(NoVerify(Arc::clone(&provider))),
158        Verify::Chain => Arc::new(ChainOnly(webpki_verifier(&plan.roots, &provider)?)),
159        Verify::Full => Arc::new(NameFirst(webpki_verifier(&plan.roots, &provider)?)),
160    };
161    let builder = ClientConfig::builder_with_provider(provider)
162        .with_safe_default_protocol_versions()
163        .map_err(|e| format!("tls: {e}"))?
164        .dangerous()
165        .with_custom_certificate_verifier(verifier);
166    let mut cfg = match &plan.client {
167        Some((certs, key)) => builder.with_client_auth_cert(certs.clone(), key.clone_key()).map_err(|e| format!("tls: {e}"))?,
168        None => builder.with_no_client_auth(),
169    };
170    cfg.enable_sni = plan.sni;
171    if plan.direct {
172        cfg.alpn_protocols = vec![b"postgresql".to_vec()];
173    }
174    Ok(cfg)
175}
176
177fn alert_text(a: AlertDescription) -> String {
178    use AlertDescription as A;
179    match a {
180        A::CloseNotify => "close notify".into(),
181        A::UnexpectedMessage => "unexpected message".into(),
182        A::BadRecordMac => "bad record MAC".into(),
183        A::DecryptionFailed => "decryption failed".into(),
184        A::RecordOverflow => "record overflow".into(),
185        A::DecompressionFailure => "decompression failure".into(),
186        A::HandshakeFailure => "handshake failure".into(),
187        A::BadCertificate => "bad certificate".into(),
188        A::UnsupportedCertificate => "unsupported certificate".into(),
189        A::CertificateRevoked => "revoked certificate".into(),
190        A::CertificateExpired => "expired certificate".into(),
191        A::CertificateUnknown => "unknown certificate".into(),
192        A::IllegalParameter => "illegal parameter".into(),
193        A::UnknownCA => "unknown certificate authority".into(),
194        A::AccessDenied => "access denied".into(),
195        A::DecodeError => "error decoding message".into(),
196        A::DecryptError => "error decrypting message".into(),
197        A::ExportRestriction => "export restriction".into(),
198        A::ProtocolVersion => "protocol version not supported".into(),
199        A::InsufficientSecurity => "insufficient security level".into(),
200        A::InternalError => "internal error".into(),
201        A::InappropriateFallback => "inappropriate fallback".into(),
202        A::UserCanceled => "user canceled".into(),
203        A::NoRenegotiation => "no renegotiation".into(),
204        A::MissingExtension => "missing extension".into(),
205        A::UnsupportedExtension => "unsupported extension".into(),
206        A::CertificateUnobtainable => "certificate unobtainable".into(),
207        A::UnrecognisedName => "unrecognized name".into(),
208        A::BadCertificateStatusResponse => "bad certificate status response".into(),
209        A::BadCertificateHashValue => "bad certificate hash value".into(),
210        A::UnknownPSKIdentity => "unknown PSK identity".into(),
211        A::CertificateRequired => "certificate required".into(),
212        A::NoApplicationProtocol => "no application protocol".into(),
213        A::EncryptedClientHelloRequired => "encrypted client hello required".into(),
214        other => format!("alert({})", u8::from(other)),
215    }
216}
217
218fn hostname_error(host: &str, presented: &[String]) -> String {
219    let inner = |p: &str, pre: &str, post: &str| p.strip_prefix(pre).and_then(|r| r.strip_suffix(post)).map(str::to_string);
220    let dns: Vec<String> = presented.iter().filter_map(|p| inner(p, "DnsName(\"", "\")")).collect();
221    let ips: Vec<String> = presented.iter().filter_map(|p| inner(p, "IpAddress(", ")")).collect();
222    if host.parse::<IpAddr>().is_ok() {
223        if ips.is_empty() {
224            return format!("x509: cannot validate certificate for {host} because it doesn't contain any IP SANs");
225        }
226        return format!("x509: certificate is valid for {}, not {host}", ips.join(", "));
227    }
228    if dns.is_empty() {
229        return format!("x509: certificate is not valid for any names, but wanted to match {host}");
230    }
231    format!("x509: certificate is valid for {}, not {host}", dns.join(", "))
232}
233
234fn go_tls_error(e: &rustls::Error, verify: Verify, host: &str) -> String {
235    match e {
236        rustls::Error::InvalidCertificate(c) => {
237            let body = match c {
238                CertificateError::UnknownIssuer => "x509: certificate signed by unknown authority".to_string(),
239                CertificateError::NotValidForName => hostname_error(host, &[]),
240                CertificateError::NotValidForNameContext { presented, .. } => hostname_error(host, presented),
241                CertificateError::Expired
242                | CertificateError::ExpiredContext { .. }
243                | CertificateError::NotValidYet
244                | CertificateError::NotValidYetContext { .. } => "x509: certificate has expired or is not yet valid".to_string(),
245                other => format!("x509: {other:?}"),
246            };
247            match verify {
248                Verify::Chain => body,
249                _ => format!("tls: failed to verify certificate: {body}"),
250            }
251        }
252        rustls::Error::AlertReceived(a) => format!("remote error: tls: {}", alert_text(*a)),
253        other => format!("tls: {other}"),
254    }
255}
256
257fn find_in_chain<'a, T: StdError + 'static>(e: &'a (dyn StdError + 'static)) -> Option<&'a T> {
258    let mut cur: Option<&(dyn StdError + 'static)> = Some(e);
259    while let Some(c) = cur {
260        if let Some(t) = c.downcast_ref::<T>() {
261            return Some(t);
262        }
263        if let Some(io) = c.downcast_ref::<std::io::Error>()
264            && let Some(inner) = io.get_ref()
265            && let Some(t) = inner.downcast_ref::<T>()
266        {
267            return Some(t);
268        }
269        cur = c.source();
270    }
271    None
272}
273
274fn chain_text(e: &(dyn StdError + 'static)) -> String {
275    let mut out = e.to_string();
276    let mut cur = e.source();
277    while let Some(c) = cur {
278        out.push_str(": ");
279        out.push_str(&c.to_string());
280        cur = c.source();
281    }
282    out
283}
284
285fn classify(e: &postgres::Error, a: &Attempt) -> Failure {
286    if let Some(db) = e.as_db_error() {
287        return Failure {
288            text: format!("server error: {}: {} (SQLSTATE {})", db.severity(), db.message(), db.code().code()),
289            code: Some(db.code().code().to_string()),
290            not_preferred: false,
291        };
292    }
293    let top = e.to_string();
294    let source = e.source();
295    if top.starts_with("error connecting to server") {
296        let net = match a.addr {
297            Addr::Tcp(_) => "tcp",
298            Addr::Unix(_) => "unix",
299        };
300        return Failure::plain(match source.and_then(find_in_chain::<std::io::Error>) {
301            Some(io) if io.kind() == std::io::ErrorKind::TimedOut && io.raw_os_error().is_none() => {
302                "dial error: timeout: context deadline exceeded".to_string()
303            }
304            Some(io) => format!("dial error: dial {net} {}: connect: {}", a.address, errno_text(io)),
305            None => "dial error".to_string(),
306        });
307    }
308    if top.starts_with("error performing TLS handshake") {
309        if source.is_some_and(|s| s.to_string() == "server does not support TLS") {
310            return Failure::plain("tls error: server refused TLS connection");
311        }
312        let verify = a.tls.map_or(Verify::None, |p| p.verify);
313        if let Some(r) = source.and_then(find_in_chain::<rustls::Error>) {
314            return Failure::plain(format!("failed to write startup message: write failed: {}", go_tls_error(r, verify, a.original)));
315        }
316        return Failure::plain(format!("failed to write startup message: write failed: {}", source.map(chain_text).unwrap_or_default()));
317    }
318    Failure::plain(format!("failed to receive message: {}", chain_text(e)))
319}
320
321fn first_cell(client: &mut Client, sql: &str) -> Result<String, String> {
322    for msg in client.simple_query(sql).map_err(|e| crate::query_error(&e))? {
323        if let postgres::SimpleQueryMessage::Row(row) = msg {
324            return Ok(row.get(0).unwrap_or("").to_string());
325        }
326    }
327    Ok(String::new())
328}
329
330fn validate(client: &mut Client, attrs: SessionAttrs, ignore_not_preferred: bool) -> Result<(), Failure> {
331    let fail = |m: String| Failure::plain(format!("ValidateConnect failed: {m}"));
332    let check = |client: &mut Client, sql: &str| first_cell(client, sql).map_err(fail);
333    match attrs {
334        SessionAttrs::Any => Ok(()),
335        SessionAttrs::ReadWrite => match check(client, "show transaction_read_only")?.as_str() {
336            "on" => Err(fail("read only connection".into())),
337            _ => Ok(()),
338        },
339        SessionAttrs::ReadOnly => match check(client, "show transaction_read_only")?.as_str() {
340            "on" => Ok(()),
341            _ => Err(fail("connection is not read only".into())),
342        },
343        SessionAttrs::Standby => match check(client, "select pg_is_in_recovery()")?.as_str() {
344            "t" => Ok(()),
345            _ => Err(fail("server is not in hot standby mode".into())),
346        },
347        SessionAttrs::Primary => match check(client, "select pg_is_in_recovery()")?.as_str() {
348            "t" => Err(fail("server is in standby mode".into())),
349            _ => Ok(()),
350        },
351        SessionAttrs::PreferStandby => match check(client, "select pg_is_in_recovery()")?.as_str() {
352            "t" => Ok(()),
353            _ if ignore_not_preferred => Ok(()),
354            _ => {
355                let mut f = fail("server is not in hot standby mode".into());
356                f.not_preferred = true;
357                Err(f)
358            }
359        },
360    }
361}
362
363fn attempt(cfg: &ConnConfig, a: &Attempt, ignore_not_preferred: bool) -> Result<Client, Failure> {
364    let mut pc = postgres::Config::new();
365    pc.user(&cfg.user);
366    pc.password(cfg.password.as_bytes());
367    if !cfg.database.is_empty() {
368        pc.dbname(&cfg.database);
369    }
370    let (options, app) = cfg.startup_options();
371    if let Some(o) = &options {
372        pc.options(o);
373    }
374    if let Some(n) = &app {
375        pc.application_name(n);
376    }
377    match &a.addr {
378        #[cfg(unix)]
379        Addr::Unix(dir) => {
380            pc.host_path(dir);
381        }
382        #[cfg(not(unix))]
383        Addr::Unix(_) => {
384            return Err(Failure::plain(format!("dial error: dial unix {}: connect: unix sockets are not supported on this platform", a.address)));
385        }
386        Addr::Tcp(ip) => {
387            pc.host(a.original);
388            pc.hostaddr(*ip);
389        }
390    }
391    pc.port(a.port);
392    if let Some(t) = cfg.connect_timeout
393        && !t.is_zero()
394    {
395        pc.connect_timeout(t);
396    }
397    pc.channel_binding(match cfg.channel_binding {
398        ChannelBinding::Require => ChannelBinding::Prefer,
399        other => other,
400    });
401    let connected = match a.tls {
402        None => {
403            pc.ssl_mode(SslMode::Disable);
404            pc.connect(NoTls)
405        }
406        Some(plan) => {
407            pc.ssl_mode(SslMode::Require);
408            if plan.direct {
409                pc.ssl_negotiation(SslNegotiation::Direct);
410            }
411            let rc = rustls_config(plan).map_err(Failure::plain)?;
412            pc.connect(tokio_postgres_rustls::MakeRustlsConnect::new(rc))
413        }
414    };
415    let mut client = connected.map_err(|e| {
416        let mut f = classify(&e, a);
417        if f.code.as_deref() == Some("28P01") && auth_request_code(cfg, a) == Some(10) {
418            f.text = f.text.replacen("server error: ", "failed SASL auth: ", 1);
419        }
420        f
421    })?;
422    if cfg.channel_binding == ChannelBinding::Require
423        && a.tls.is_none()
424        && first_cell(&mut client, "select system_user").is_ok_and(|u| u.starts_with("scram-sha-256:"))
425    {
426        return Err(Failure::plain("failed SASL auth: channel binding required but server does not support SCRAM-SHA-256-PLUS"));
427    }
428    if cfg.min_protocol != "3.0" {
429        let v: i64 = first_cell(&mut client, "show server_version_num").ok().and_then(|s| s.parse().ok()).unwrap_or(0);
430        if v < FIRST_PROTOCOL_3_2_SERVER {
431            return Err(Failure::plain(format!(
432                "server protocol version too low: min_protocol_version is {}, but the server speaks only protocol 3.0",
433                cfg.min_protocol
434            )));
435        }
436    }
437    validate(&mut client, cfg.session_attrs, ignore_not_preferred)?;
438    Ok(client)
439}
440
441fn startup_packet(cfg: &ConnConfig) -> Vec<u8> {
442    let mut body = Vec::new();
443    body.extend_from_slice(&PROTOCOL_3_0.to_be_bytes());
444    let mut param = |k: &str, v: &str| {
445        body.extend_from_slice(k.as_bytes());
446        body.push(0);
447        body.extend_from_slice(v.as_bytes());
448        body.push(0);
449    };
450    param("user", &cfg.user);
451    if !cfg.database.is_empty() {
452        param("database", &cfg.database);
453    }
454    body.push(0);
455    let mut out = i32::try_from(body.len() + 4).expect("a startup packet is a few hundred bytes").to_be_bytes().to_vec();
456    out.extend(body);
457    out
458}
459
460fn read_auth_code(stream: &mut impl std::io::Read) -> Option<i32> {
461    let mut head = [0u8; 9];
462    stream.read_exact(&mut head).ok()?;
463    if head[0] != b'R' {
464        return None;
465    }
466    Some(i32::from_be_bytes([head[5], head[6], head[7], head[8]]))
467}
468
469fn auth_request_code(cfg: &ConnConfig, a: &Attempt) -> Option<i32> {
470    use std::io::{Read, Write};
471    let timeout = Some(std::time::Duration::from_secs(10));
472    let startup = startup_packet(cfg);
473    match (&a.addr, a.tls) {
474        #[cfg(unix)]
475        (Addr::Unix(dir), _) => {
476            let mut s = std::os::unix::net::UnixStream::connect(dsn::unix_socket_address(dir, a.port)).ok()?;
477            s.set_read_timeout(timeout).ok()?;
478            s.write_all(&startup).ok()?;
479            read_auth_code(&mut s)
480        }
481        #[cfg(not(unix))]
482        (Addr::Unix(_), _) => None,
483        (Addr::Tcp(ip), tls) => {
484            let mut tcp = std::net::TcpStream::connect_timeout(&std::net::SocketAddr::new(*ip, a.port), timeout?).ok()?;
485            tcp.set_read_timeout(timeout).ok()?;
486            let Some(plan) = tls else {
487                tcp.write_all(&startup).ok()?;
488                return read_auth_code(&mut tcp);
489            };
490            if !plan.direct {
491                tcp.write_all(&[0, 0, 0, 8, 4, 210, 22, 47]).ok()?;
492                let mut answer = [0u8; 1];
493                tcp.read_exact(&mut answer).ok()?;
494                if answer[0] != b'S' {
495                    return None;
496                }
497            }
498            let name = ServerName::try_from(a.original.to_string()).ok()?;
499            let conn = rustls::ClientConnection::new(Arc::new(rustls_config(plan).ok()?), name).ok()?;
500            let mut tls_stream = rustls::StreamOwned::new(conn, tcp);
501            tls_stream.write_all(&startup).ok()?;
502            read_auth_code(&mut tls_stream)
503        }
504    }
505}
506
507fn lookup_host(host: &str) -> Result<Vec<IpAddr>, String> {
508    if let Ok(ip) = host.parse::<IpAddr>() {
509        return Ok(vec![ip]);
510    }
511    let not_found = || format!("lookup {host}: no such host");
512    let Ok(addrs) = (host, 0).to_socket_addrs() else { return Err(not_found()) };
513    let mut ips: Vec<IpAddr> = Vec::new();
514    for a in addrs {
515        if !ips.contains(&a.ip()) {
516            ips.push(a.ip());
517        }
518    }
519    if ips.is_empty() { Err(not_found()) } else { Ok(ips) }
520}
521
522fn join_host_port(ip: IpAddr, port: u16) -> String {
523    match ip {
524        IpAddr::V4(v) => format!("{v}:{port}"),
525        IpAddr::V6(v) => format!("[{v}]:{port}"),
526    }
527}
528
529fn connect_error(cfg: &ConnConfig, details: &str) -> String {
530    let prefix = format!("failed to connect to `user={} database={}`:", cfg.user, cfg.database);
531    if details.contains('\n') { format!("{prefix}\n\t{}", details.replace('\n', "\n\t")) } else { format!("{prefix} {details}") }
532}
533
534/// Connects to Postgres from a URL or keyword/value string, the way libpq and pgx do.
535///
536/// # Errors
537///
538/// The connection string does not parse, or every host fails to connect, authenticate or meet the TLS mode. The message lists each attempt.
539pub fn connect(conn: &str) -> Result<Client, crate::Error> {
540    let cfg = dsn::parse_config(conn).map_err(|e| crate::Error::connection_string(e.to_string()))?;
541    connect_with(&cfg).map_err(crate::Error::connect)
542}
543
544fn connect_with(cfg: &ConnConfig) -> Result<Client, String> {
545    let mut errors: Vec<String> = Vec::new();
546    let mut attempts: Vec<Attempt> = Vec::new();
547    for fb in &cfg.fallbacks {
548        if dsn::is_absolute_path(&fb.host) {
549            attempts.push(Attempt {
550                addr: Addr::Unix(fb.host.clone()),
551                port: fb.port,
552                address: dsn::unix_socket_address(&fb.host, fb.port),
553                original: &fb.host,
554                tls: fb.tls.as_ref(),
555            });
556            continue;
557        }
558        match lookup_host(&fb.host) {
559            Ok(ips) => {
560                for ip in ips {
561                    attempts.push(Attempt {
562                        addr: Addr::Tcp(ip),
563                        port: fb.port,
564                        address: join_host_port(ip, fb.port),
565                        original: &fb.host,
566                        tls: fb.tls.as_ref(),
567                    });
568                }
569            }
570            Err(e) => errors.push(e),
571        }
572    }
573    if attempts.is_empty() {
574        return Err(connect_error(cfg, &format!("hostname resolving error: {}", errors.join("\n"))));
575    }
576    let mut not_preferred: Option<&Attempt> = None;
577    for a in &attempts {
578        match attempt(cfg, a, false) {
579            Ok(c) => return Ok(c),
580            Err(f) => {
581                errors.push(format!("{} ({}): {}", a.address, a.original, f.text));
582                if matches!(f.code.as_deref(), Some("28P01" | "3D000" | "42501")) {
583                    return Err(connect_error(cfg, &errors.join("\n")));
584                }
585                if f.not_preferred {
586                    not_preferred = Some(a);
587                }
588            }
589        }
590    }
591    if let Some(a) = not_preferred {
592        match attempt(cfg, a, true) {
593            Ok(c) => return Ok(c),
594            Err(f) => errors.push(format!("{} ({}): {}", a.address, a.original, f.text)),
595        }
596    }
597    Err(connect_error(cfg, &errors.join("\n")))
598}