Skip to main content

postgres_mcp/pg/
wire.rs

1//! PostgreSQL client over the frontend/backend protocol: connect, auth, simple and extended queries.
2// WireError::Db holds DbError by value (fixed by the interface), so Result<_, WireError> is large.
3#![allow(clippy::result_large_err)]
4
5use std::collections::HashMap;
6use std::fmt;
7use std::io;
8use std::sync::Arc;
9use std::time::Duration;
10
11use bytes::{Buf, BufMut, Bytes, BytesMut};
12use fallible_iterator::FallibleIterator;
13use postgres_protocol::IsNull;
14use postgres_protocol::authentication::md5_hash;
15use postgres_protocol::authentication::sasl::{self, ChannelBinding, ScramSha256};
16use postgres_protocol::message::backend::{
17    DataRowBody, ErrorResponseBody, Header, Message, RowDescriptionBody,
18};
19use postgres_protocol::message::frontend::{self, BindError};
20use rustls::ClientConfig;
21use rustls::pki_types::ServerName;
22use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
23use tokio::net::TcpStream;
24use tokio_rustls::TlsConnector;
25use tracing::trace;
26
27use crate::pg::tls::{self, SslMode};
28
29const MAX_DATA_ROW_LEN: u64 = (1 << 30) + 16;
30const MAX_OTHER_LEN: u64 = 64 << 20;
31const DISCARD_TIMEOUT: Duration = Duration::from_secs(5);
32const DISCARD_MAX_BYTES: usize = 64 << 20;
33const CANCEL_TIMEOUT: Duration = Duration::from_secs(5);
34/// Read size used when a DataRow is discarded without being buffered.
35const SKIP_CHUNK: usize = 64 << 10;
36/// Bytes of a message header: the tag and the length word.
37const HEADER_LEN: usize = 5;
38
39/// What `recv_frame` does beyond returning whole messages.
40#[derive(Clone, Copy)]
41enum Skip {
42    Nothing,
43    /// Query rows: DataRows are read field by field, keeping `max_value_bytes` of each; NotificationResponse is ignored.
44    Rows {
45        max_value_bytes: usize,
46    },
47}
48
49/// One received frame: a whole message, or a streamed DataRow with its kept fields.
50enum Frame {
51    Message(Incoming),
52    Row {
53        fields: Vec<Option<Field>>,
54        len: usize,
55    },
56}
57
58#[derive(Clone)]
59pub struct ConnectConfig {
60    pub host: String,
61    pub port: u16,
62    pub database: String,
63    pub user: String,
64    pub password: Option<String>,
65    pub ssl_mode: SslMode,
66    pub ssl_root_cert: Option<std::path::PathBuf>,
67    pub connect_timeout: Duration,
68    /// Sent in the startup packet after user/database (e.g. ("application_name","x"), ("DateStyle","ISO")).
69    pub startup_params: Vec<(String, String)>,
70}
71
72impl fmt::Debug for ConnectConfig {
73    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74        let password = if self.password.is_some() {
75            "<redacted>"
76        } else {
77            "None"
78        };
79        f.debug_struct("ConnectConfig")
80            .field("host", &self.host)
81            .field("port", &self.port)
82            .field("database", &self.database)
83            .field("user", &self.user)
84            .field("password", &password)
85            .field("ssl_mode", &self.ssl_mode)
86            .field("ssl_root_cert", &self.ssl_root_cert)
87            .field("connect_timeout", &self.connect_timeout)
88            .field("startup_params", &self.startup_params)
89            .finish()
90    }
91}
92
93/// Which authentication methods the server may use. Refused methods are never answered.
94#[derive(Debug, Clone, PartialEq, Eq)]
95pub struct AuthPolicy {
96    pub scram: bool,
97    pub md5: bool,
98    pub password: bool,
99    pub trust: bool,
100}
101
102impl Default for AuthPolicy {
103    fn default() -> Self {
104        AuthPolicy {
105            scram: true,
106            md5: false,
107            password: false,
108            trust: true,
109        }
110    }
111}
112
113#[derive(Debug, Clone, PartialEq, Eq)]
114pub struct DbError {
115    pub severity: String,
116    pub code: String,
117    pub message: String,
118    pub detail: Option<String>,
119    pub hint: Option<String>,
120    pub position: Option<u32>,
121}
122
123#[derive(Debug, thiserror::Error)]
124pub enum WireError {
125    #[error("connection failed: {0}")]
126    Io(#[from] io::Error),
127    #[error("TLS error: {0}")]
128    Tls(String),
129    #[error("authentication failed: {0}")]
130    Auth(String),
131    #[error("protocol error: {0}")]
132    Protocol(String),
133    #[error("{}", .0.message)]
134    Db(DbError),
135    #[error("timed out")]
136    Timeout,
137    #[error("statement was refused: {0}")]
138    Refused(String),
139}
140
141#[derive(Debug, Clone, Copy, PartialEq, Eq)]
142pub enum TxStatus {
143    Idle,
144    InTransaction,
145    Failed,
146}
147
148#[derive(Debug, Clone, PartialEq, Eq)]
149pub struct Column {
150    pub name: String,
151    pub type_oid: u32,
152    pub type_modifier: i32,
153}
154
155/// One result value in text format. `data` holds at most `max_value_bytes` leading bytes; `full_len` is the real length.
156#[derive(Debug, Clone, PartialEq, Eq)]
157pub struct Field {
158    pub data: Bytes,
159    pub full_len: usize,
160}
161
162#[derive(Debug, Clone, Copy, PartialEq, Eq)]
163pub enum Truncation {
164    Rows,
165    Bytes,
166}
167
168#[derive(Debug, Clone, Copy)]
169pub struct FetchLimits {
170    pub max_rows: usize,
171    pub max_bytes: usize,
172    pub max_value_bytes: usize,
173}
174
175#[derive(Debug)]
176pub struct QueryResult {
177    pub columns: Vec<Column>,
178    /// None = SQL NULL; never more than max_rows rows.
179    pub rows: Vec<Vec<Option<Field>>>,
180    pub truncated: Option<Truncation>,
181    /// None when the fetch was cut short.
182    pub command_tag: Option<String>,
183    pub status: TxStatus,
184}
185
186#[derive(Debug)]
187pub struct SimpleResult {
188    /// Rows of the LAST result set that had a RowDescription.
189    pub rows: Vec<Vec<Option<String>>>,
190    pub tags: Vec<String>,
191    pub status: TxStatus,
192}
193
194/// Sends a CancelRequest for one connection. Uses TLS when that connection does.
195#[derive(Clone)]
196pub struct CancelHandle {
197    host: String,
198    port: u16,
199    tls: Option<Arc<ClientConfig>>,
200    process_id: i32,
201    secret_key: i32,
202}
203
204impl CancelHandle {
205    pub async fn cancel(&self) -> Result<(), WireError> {
206        tokio::time::timeout(CANCEL_TIMEOUT, self.send_cancel())
207            .await
208            .map_err(|_| WireError::Timeout)?
209    }
210
211    async fn send_cancel(&self) -> Result<(), WireError> {
212        let mut tcp = TcpStream::connect((self.host.as_str(), self.port)).await?;
213        let mut stream: Box<dyn Transport> = match &self.tls {
214            None => Box::new(tcp),
215            Some(config) => {
216                let (answer, rest) = ssl_request(&mut tcp).await?;
217                if answer != b'S' || !rest.is_empty() {
218                    return Err(WireError::Tls(
219                        "TLS was not accepted for the cancel request".into(),
220                    ));
221                }
222                start_tls(tcp, &self.host, config.clone()).await?
223            }
224        };
225        let mut out = BytesMut::new();
226        frontend::cancel_request(self.process_id, self.secret_key, &mut out);
227        stream.write_all(&out).await?;
228        stream.flush().await?;
229        stream.shutdown().await?;
230        Ok(())
231    }
232}
233
234trait Transport: AsyncRead + AsyncWrite + Unpin + Send {}
235
236impl<T: AsyncRead + AsyncWrite + Unpin + Send> Transport for T {}
237
238pub struct Connection {
239    stream: Box<dyn Transport>,
240    buf: BytesMut,
241    parameters: HashMap<String, String>,
242    cancel: CancelHandle,
243    poisoned: bool,
244    peak_message_bytes: usize,
245}
246
247/// One backend message with its tag and total length (header included).
248struct Incoming {
249    tag: u8,
250    len: usize,
251    message: Message,
252}
253
254impl Connection {
255    pub async fn connect(cfg: &ConnectConfig) -> Result<Connection, WireError> {
256        Connection::connect_with(cfg, &AuthPolicy::default()).await
257    }
258
259    /// Connects and authenticates; only the methods in `policy` are answered.
260    pub async fn connect_with(
261        cfg: &ConnectConfig,
262        policy: &AuthPolicy,
263    ) -> Result<Connection, WireError> {
264        Connection::connect_with_tls(cfg, policy, None).await
265    }
266
267    /// Like `connect_with`, using `tls` for the handshake when given instead of reading the root file.
268    pub async fn connect_with_tls(
269        cfg: &ConnectConfig,
270        policy: &AuthPolicy,
271        tls: Option<Arc<ClientConfig>>,
272    ) -> Result<Connection, WireError> {
273        tokio::time::timeout(cfg.connect_timeout, connect_inner(cfg, policy, tls))
274            .await
275            .map_err(|_| WireError::Timeout)?
276    }
277
278    /// Largest message held whole, or the kept bytes of one streamed DataRow.
279    pub fn peak_message_bytes(&self) -> usize {
280        self.peak_message_bytes
281    }
282
283    pub fn parameter(&self, name: &str) -> Option<&str> {
284        self.parameters.get(name).map(String::as_str)
285    }
286
287    pub fn server_version_num(&self) -> u32 {
288        self.parameter("server_version")
289            .map_or(0, parse_server_version_num)
290    }
291
292    pub fn cancel_handle(&self) -> CancelHandle {
293        self.cancel.clone()
294    }
295
296    pub fn is_poisoned(&self) -> bool {
297        self.poisoned
298    }
299
300    pub async fn simple_query(&mut self, sql: &str) -> Result<SimpleResult, WireError> {
301        self.ensure_usable()?;
302        let result = self.simple_inner(sql).await;
303        self.note(&result);
304        result
305    }
306
307    pub async fn query(
308        &mut self,
309        sql: &str,
310        params: &[Option<&str>],
311        user_sql: bool,
312        limits: &FetchLimits,
313    ) -> Result<QueryResult, WireError> {
314        self.ensure_usable()?;
315        let result = self.query_inner(sql, params, user_sql, limits).await;
316        self.note(&result);
317        result
318    }
319
320    /// Runs one EXPLAIN text through the simple protocol. The server must parse it as one statement first,
321    /// and no Query is sent unless it does. The plan's bytes are capped at `max_bytes` while they are read.
322    pub async fn explain_unbound(
323        &mut self,
324        sql: &str,
325        max_bytes: usize,
326    ) -> Result<QueryResult, WireError> {
327        self.ensure_usable()?;
328        let result = self.explain_unbound_inner(sql, max_bytes).await;
329        if let Err(WireError::Protocol(reason)) = &result {
330            tracing::error!(reason = %crate::scrub::scrub(reason), "explain response rejected; connection dropped");
331        }
332        self.note(&result);
333        result
334    }
335
336    /// Sends Terminate and closes the socket. Errors are logged at debug level only.
337    pub async fn close(mut self) {
338        let mut out = BytesMut::new();
339        frontend::terminate(&mut out);
340        let result = async {
341            self.stream.write_all(&out).await?;
342            self.stream.flush().await?;
343            self.stream.shutdown().await
344        }
345        .await;
346        if let Err(e) = result {
347            tracing::debug!(error = %crate::scrub::scrub(&e.to_string()), "connection close was not clean");
348        }
349    }
350
351    fn ensure_usable(&self) -> Result<(), WireError> {
352        if self.poisoned {
353            return Err(WireError::Protocol("connection is poisoned".into()));
354        }
355        Ok(())
356    }
357
358    /// Marks the connection poisoned after any error that leaves the protocol state unknown.
359    fn note<T>(&mut self, result: &Result<T, WireError>) {
360        if let Err(e) = result
361            && poisons(e)
362        {
363            self.poisoned = true;
364        }
365    }
366
367    async fn send(&mut self, out: &mut BytesMut) -> Result<(), WireError> {
368        self.stream.write_all(out).await.map_err(transport_error)?;
369        self.stream.flush().await.map_err(transport_error)?;
370        out.clear();
371        Ok(())
372    }
373
374    /// Reads one backend message. ParameterStatus and NoticeResponse are consumed here.
375    async fn recv(&mut self) -> Result<Incoming, WireError> {
376        match self.recv_frame(Skip::Nothing).await? {
377            Frame::Message(incoming) => Ok(incoming),
378            Frame::Row { .. } => Err(unexpected(b'D')),
379        }
380    }
381
382    /// Reads one backend frame, discarding what `skip` allows without buffering it.
383    async fn recv_frame(&mut self, skip: Skip) -> Result<Frame, WireError> {
384        loop {
385            if let Some(header) = Header::parse(&self.buf).map_err(protocol)? {
386                let (tag, len) = (header.tag(), header.len());
387                let rows = matches!(skip, Skip::Rows { .. });
388                if matches!(tag, b'G' | b'H' | b'W' | b'd' | b'c') || (tag == b'A' && !rows) {
389                    return Err(unexpected(tag));
390                }
391                let limit = if tag == b'D' {
392                    MAX_DATA_ROW_LEN
393                } else {
394                    MAX_OTHER_LEN
395                };
396                let len = u64::try_from(len).map_err(protocol)?;
397                if len > limit {
398                    return Err(protocol(format!(
399                        "message '{}' of {len} bytes is too large",
400                        char::from(tag)
401                    )));
402                }
403                let total = usize::try_from(len).map_err(protocol)? + 1;
404                if let Skip::Rows { max_value_bytes } = skip
405                    && tag == b'D'
406                {
407                    let fields = self.stream_row(total, max_value_bytes).await?;
408                    return Ok(Frame::Row { fields, len: total });
409                }
410                if self.buf.len() >= total {
411                    self.peak_message_bytes = self.peak_message_bytes.max(total);
412                    let message = Message::parse(&mut self.buf)
413                        .map_err(protocol)?
414                        .ok_or_else(|| protocol("incomplete message"))?;
415                    match message {
416                        Message::NoticeResponse(_) => {
417                            trace!("ignoring NoticeResponse");
418                            continue;
419                        }
420                        Message::NotificationResponse(_) if rows => continue,
421                        Message::ParameterStatus(body) => {
422                            let name = body.name().map_err(protocol)?.to_owned();
423                            let value = body.value().map_err(protocol)?.to_owned();
424                            check_session_parameter(&name, &value)?;
425                            self.parameters.insert(name, value);
426                            continue;
427                        }
428                        message => {
429                            return Ok(Frame::Message(Incoming {
430                                tag,
431                                len: total,
432                                message,
433                            }));
434                        }
435                    }
436                }
437            }
438            let read = self
439                .stream
440                .read_buf(&mut self.buf)
441                .await
442                .map_err(transport_error)?;
443            if read == 0 {
444                return Err(eof());
445            }
446        }
447    }
448
449    /// Reads one DataRow of `total` bytes field by field: `max_value_bytes` of each field are kept, the rest is discarded.
450    async fn stream_row(
451        &mut self,
452        total: usize,
453        max_value_bytes: usize,
454    ) -> Result<Vec<Option<Field>>, WireError> {
455        self.buf.advance(HEADER_LEN);
456        let mut left = total
457            .checked_sub(HEADER_LEN)
458            .ok_or_else(|| protocol("data row is too short"))?;
459        let mut count = [0u8; 2];
460        left = left
461            .checked_sub(count.len())
462            .ok_or_else(|| protocol("data row is truncated"))?;
463        self.read_exact_into(&mut count).await?;
464        let mut fields = Vec::with_capacity(usize::from(u16::from_be_bytes(count)));
465        let mut held = 0usize;
466        for _ in 0..u16::from_be_bytes(count) {
467            let mut word = [0u8; 4];
468            left = left
469                .checked_sub(word.len())
470                .ok_or_else(|| protocol("data row is truncated"))?;
471            self.read_exact_into(&mut word).await?;
472            let length = i32::from_be_bytes(word);
473            if length == -1 {
474                fields.push(None);
475                continue;
476            }
477            let full = usize::try_from(length)
478                .map_err(|_| protocol("data row field has a negative length"))?;
479            if full > left {
480                return Err(protocol("data row field is longer than the message"));
481            }
482            left -= full;
483            let kept = full.min(max_value_bytes);
484            let mut data = vec![0u8; kept];
485            self.read_exact_into(&mut data).await?;
486            self.discard(full - kept).await?;
487            held += kept;
488            fields.push(Some(Field {
489                data: Bytes::from(data),
490                full_len: full,
491            }));
492        }
493        if left != 0 {
494            return Err(protocol("data row is longer than its fields"));
495        }
496        self.peak_message_bytes = self.peak_message_bytes.max(held);
497        Ok(fields)
498    }
499
500    /// Fills `out` from the stream, buffered bytes first.
501    async fn read_exact_into(&mut self, out: &mut [u8]) -> Result<(), WireError> {
502        let from_buf = out.len().min(self.buf.len());
503        out[..from_buf].copy_from_slice(&self.buf[..from_buf]);
504        self.buf.advance(from_buf);
505        let mut filled = from_buf;
506        while filled < out.len() {
507            let read = self.stream.read(&mut out[filled..]).await?;
508            if read == 0 {
509                return Err(eof());
510            }
511            filled += read;
512        }
513        Ok(())
514    }
515
516    /// Drops the next `count` bytes of the stream in SKIP_CHUNK steps, using buffered bytes first.
517    async fn discard(&mut self, count: usize) -> Result<(), WireError> {
518        let buffered = count.min(self.buf.len());
519        self.buf.advance(buffered);
520        let mut remaining = count - buffered;
521        let mut chunk = vec![0u8; SKIP_CHUNK.min(remaining)];
522        while remaining > 0 {
523            let want = remaining.min(SKIP_CHUNK);
524            let read = self.stream.read(&mut chunk[..want]).await?;
525            if read == 0 {
526                return Err(eof());
527            }
528            remaining -= read;
529        }
530        Ok(())
531    }
532
533    async fn simple_inner(&mut self, sql: &str) -> Result<SimpleResult, WireError> {
534        if sql.contains('\0') {
535            return Err(nul_refusal());
536        }
537        let mut out = BytesMut::new();
538        frontend::query(sql, &mut out).map_err(protocol)?;
539        self.send(&mut out).await?;
540
541        let mut rows = Vec::new();
542        let mut tags = Vec::new();
543        let mut error = None;
544        let status = loop {
545            let incoming = self.recv().await?;
546            match incoming.message {
547                Message::RowDescription(_) => rows = Vec::new(),
548                Message::DataRow(body) => rows.push(text_row(&body)?),
549                Message::CommandComplete(body) => {
550                    tags.push(body.tag().map_err(protocol)?.to_owned());
551                }
552                Message::EmptyQueryResponse => {}
553                Message::ErrorResponse(body) => {
554                    if error.is_none() {
555                        error = Some(db_error(&body)?);
556                    }
557                }
558                Message::ReadyForQuery(body) => break tx_status(body.status())?,
559                _ => return Err(unexpected(incoming.tag)),
560            }
561        };
562        match error {
563            Some(e) => Err(WireError::Db(e)),
564            None => Ok(SimpleResult { rows, tags, status }),
565        }
566    }
567
568    async fn query_inner(
569        &mut self,
570        sql: &str,
571        params: &[Option<&str>],
572        user_sql: bool,
573        limits: &FetchLimits,
574    ) -> Result<QueryResult, WireError> {
575        if sql.contains('\0') {
576            return Err(nul_refusal());
577        }
578        let (columns, param_count) = self.describe(sql).await?;
579        let columns =
580            columns.ok_or_else(|| WireError::Refused("statement does not return rows".into()))?;
581        if user_sql && param_count != 0 {
582            return Err(WireError::Refused(
583                "parameter placeholders are not supported".into(),
584            ));
585        }
586        if param_count != params.len() {
587            return Err(WireError::Refused(format!(
588                "statement takes {param_count} parameters, {} given",
589                params.len()
590            )));
591        }
592        self.execute(params, limits, columns).await
593    }
594
595    async fn explain_unbound_inner(
596        &mut self,
597        sql: &str,
598        max_bytes: usize,
599    ) -> Result<QueryResult, WireError> {
600        if sql.contains('\0') {
601            return Err(nul_refusal());
602        }
603        self.explain_preflight(sql).await?;
604        let mut out = BytesMut::new();
605        frontend::query(sql, &mut out).map_err(protocol)?;
606        self.send(&mut out).await?;
607
608        let skip = Skip::Rows {
609            max_value_bytes: max_bytes,
610        };
611        let mut columns: Option<Vec<Column>> = None;
612        let mut rows = Vec::new();
613        let mut plan_bytes = 0usize;
614        let mut tags = Vec::new();
615        let mut empty = false;
616        let mut error = None;
617        let status = loop {
618            let incoming = match self.recv_frame(skip).await? {
619                Frame::Message(incoming) => incoming,
620                Frame::Row { fields, .. } => {
621                    if columns.is_none() {
622                        return Err(explain_shape("data row before the row description"));
623                    }
624                    for field in fields.iter().flatten() {
625                        plan_bytes = plan_bytes.saturating_add(field.full_len);
626                    }
627                    if plan_bytes > max_bytes {
628                        self.poisoned = true;
629                        return Err(WireError::Refused("plan too large".into()));
630                    }
631                    rows.push(fields);
632                    continue;
633                }
634            };
635            match incoming.message {
636                Message::RowDescription(body) => {
637                    if columns.is_some() {
638                        return Err(explain_shape("more than one row description"));
639                    }
640                    columns = Some(column_list(&body)?);
641                }
642                Message::CommandComplete(body) => {
643                    tags.push(body.tag().map_err(protocol)?.to_owned());
644                }
645                Message::EmptyQueryResponse => empty = true,
646                Message::ErrorResponse(body) => {
647                    if error.is_none() {
648                        error = Some(db_error(&body)?);
649                    }
650                }
651                Message::ReadyForQuery(body) => break tx_status(body.status())?,
652                _ => return Err(unexpected(incoming.tag)),
653            }
654        };
655        if let Some(e) = error {
656            return Err(WireError::Db(e));
657        }
658        let columns = columns.ok_or_else(|| explain_shape("no row description"))?;
659        if empty || tags != ["EXPLAIN"] || status != TxStatus::InTransaction {
660            return Err(explain_shape("unexpected response to the explain query"));
661        }
662        Ok(QueryResult {
663            columns,
664            rows,
665            truncated: None,
666            command_tag: tags.pop(),
667            status,
668        })
669    }
670
671    /// Parse + Describe + Sync on the unnamed statement. Succeeds only for one statement that returns rows.
672    async fn explain_preflight(&mut self, sql: &str) -> Result<(), WireError> {
673        let mut out = BytesMut::new();
674        frontend::parse("", sql, std::iter::empty(), &mut out).map_err(protocol)?;
675        frontend::describe(b'S', "", &mut out).map_err(protocol)?;
676        frontend::sync(&mut out);
677        self.send(&mut out).await?;
678
679        let mut parsed = false;
680        let mut described = false;
681        let mut error = None;
682        let status = loop {
683            let incoming = self.recv().await?;
684            match incoming.message {
685                Message::ParseComplete => parsed = true,
686                Message::ParameterDescription(_) | Message::NoData => {}
687                Message::RowDescription(_) => described = true,
688                Message::ErrorResponse(body) => {
689                    if error.is_none() {
690                        error = Some(db_error(&body)?);
691                    }
692                }
693                Message::ReadyForQuery(body) => break tx_status(body.status())?,
694                _ => return Err(unexpected(incoming.tag)),
695            }
696        };
697        if let Some(e) = error {
698            return Err(WireError::Db(e));
699        }
700        if parsed && described && status == TxStatus::InTransaction {
701            return Ok(());
702        }
703        Err(explain_shape(
704            "unexpected response to the explain preflight",
705        ))
706    }
707
708    /// Parse + Describe on the unnamed statement. Returns the columns (None for NoData) and the parameter count.
709    async fn describe(&mut self, sql: &str) -> Result<(Option<Vec<Column>>, usize), WireError> {
710        let mut out = BytesMut::new();
711        frontend::parse("", sql, std::iter::empty(), &mut out).map_err(protocol)?;
712        frontend::describe(b'S', "", &mut out).map_err(protocol)?;
713        frontend::sync(&mut out);
714        self.send(&mut out).await?;
715
716        let mut parsed = false;
717        let mut param_count = None;
718        let mut columns = None;
719        let mut error = None;
720        loop {
721            let incoming = self.recv().await?;
722            match incoming.message {
723                Message::ParseComplete => parsed = true,
724                Message::ParameterDescription(body) => {
725                    param_count = Some(body.parameters().count().map_err(protocol)?);
726                }
727                Message::RowDescription(body) => columns = Some(Some(column_list(&body)?)),
728                Message::NoData => columns = Some(None),
729                Message::ErrorResponse(body) => {
730                    if error.is_none() {
731                        error = Some(db_error(&body)?);
732                    }
733                }
734                Message::ReadyForQuery(_) => break,
735                _ => return Err(unexpected(incoming.tag)),
736            }
737        }
738        if let Some(e) = error {
739            return Err(WireError::Db(e));
740        }
741        match (parsed, param_count, columns) {
742            (true, Some(count), Some(columns)) => Ok((columns, count)),
743            _ => Err(protocol("incomplete describe response")),
744        }
745    }
746
747    async fn execute(
748        &mut self,
749        params: &[Option<&str>],
750        limits: &FetchLimits,
751        columns: Vec<Column>,
752    ) -> Result<QueryResult, WireError> {
753        let mut out = BytesMut::new();
754        frontend::bind(
755            "",
756            "",
757            std::iter::once(0),
758            params.iter().copied(),
759            |value, buf| match value {
760                Some(text) => {
761                    buf.put_slice(text.as_bytes());
762                    Ok(IsNull::No)
763                }
764                None => Ok(IsNull::Yes),
765            },
766            std::iter::once(0),
767            &mut out,
768        )
769        .map_err(|e| match e {
770            BindError::Conversion(e) => protocol(e),
771            BindError::Serialization(e) => protocol(e),
772        })?;
773        frontend::execute("", 0, &mut out).map_err(protocol)?;
774        frontend::sync(&mut out);
775        self.send(&mut out).await?;
776        self.stream_rows(columns, limits).await
777    }
778
779    async fn stream_rows(
780        &mut self,
781        columns: Vec<Column>,
782        limits: &FetchLimits,
783    ) -> Result<QueryResult, WireError> {
784        let mut rows = Vec::new();
785        let mut kept = 0usize;
786        let mut truncated = None;
787        let mut bound = false;
788        let mut command_tag = None;
789        let mut error = None;
790        let mut status = None;
791        let skip = Skip::Rows {
792            max_value_bytes: limits.max_value_bytes,
793        };
794        loop {
795            let incoming = match self.recv_frame(skip).await? {
796                Frame::Message(incoming) => incoming,
797                Frame::Row { fields, .. } if bound => {
798                    if let Some(t) = keep_row(fields, &mut rows, &mut kept, limits) {
799                        truncated = Some(t);
800                        break;
801                    }
802                    continue;
803                }
804                Frame::Row { .. } => return Err(unexpected(b'D')),
805            };
806            match incoming.message {
807                Message::BindComplete if !bound => bound = true,
808                Message::CommandComplete(body) => {
809                    command_tag = Some(body.tag().map_err(protocol)?.to_owned());
810                }
811                Message::ErrorResponse(body) => {
812                    if error.is_none() {
813                        error = Some(db_error(&body)?);
814                    }
815                }
816                Message::ReadyForQuery(body) => {
817                    status = Some(tx_status(body.status())?);
818                    break;
819                }
820                _ => return Err(unexpected(incoming.tag)),
821            }
822        }
823
824        if let Some(t) = truncated {
825            // A failed cancel leaves the statement running; the bounded drain below still reads it to ReadyForQuery.
826            if let Err(e) = self.cancel.cancel().await {
827                tracing::warn!(error = %crate::scrub::scrub(&e.to_string()), "cancel request after a capped fetch failed; draining the statement");
828            }
829            let (tx_status, other) = self.discard_until_ready(skip).await?;
830            if let Some(e) = other {
831                return Err(WireError::Db(e));
832            }
833            return Ok(QueryResult {
834                columns,
835                rows,
836                truncated: Some(t),
837                command_tag: None,
838                status: tx_status,
839            });
840        }
841        if let Some(e) = error {
842            return Err(WireError::Db(e));
843        }
844        let command_tag =
845            command_tag.ok_or_else(|| protocol("no CommandComplete before ReadyForQuery"))?;
846        let status = status.ok_or_else(|| protocol("no ReadyForQuery"))?;
847        Ok(QueryResult {
848            columns,
849            rows,
850            truncated: None,
851            command_tag: Some(command_tag),
852            status,
853        })
854    }
855
856    /// Reads and drops messages until ReadyForQuery, bounded by DISCARD_TIMEOUT and DISCARD_MAX_BYTES.
857    async fn discard_until_ready(
858        &mut self,
859        skip: Skip,
860    ) -> Result<(TxStatus, Option<DbError>), WireError> {
861        tokio::time::timeout(DISCARD_TIMEOUT, self.discard_loop(skip))
862            .await
863            .map_err(|_| WireError::Timeout)?
864    }
865
866    async fn discard_loop(&mut self, skip: Skip) -> Result<(TxStatus, Option<DbError>), WireError> {
867        let mut discarded = 0usize;
868        let mut other_error = None;
869        loop {
870            let frame = self.recv_frame(skip).await?;
871            let len = match &frame {
872                Frame::Message(incoming) => incoming.len,
873                Frame::Row { len, .. } => *len,
874            };
875            discarded = discarded.saturating_add(len);
876            if discarded > DISCARD_MAX_BYTES {
877                return Err(protocol("too much data while cancelling the query"));
878            }
879            let Frame::Message(incoming) = frame else {
880                continue;
881            };
882            match incoming.message {
883                Message::ErrorResponse(body) => {
884                    let e = db_error(&body)?;
885                    if e.code != "57014" && other_error.is_none() {
886                        other_error = Some(e);
887                    }
888                }
889                Message::ReadyForQuery(body) => {
890                    return Ok((tx_status(body.status())?, other_error));
891                }
892                _ => {}
893            }
894        }
895    }
896
897    /// Reads the startup, auth and parameter messages until the first ReadyForQuery.
898    async fn authenticate(
899        &mut self,
900        cfg: &ConnectConfig,
901        policy: &AuthPolicy,
902    ) -> Result<(), WireError> {
903        let mut out = BytesMut::new();
904        let mut scram: Option<ScramSha256> = None;
905        let mut scram_proved = false;
906        // A password exchange (cleartext, MD5 or SASL) has started.
907        let mut challenged = false;
908        let mut authenticated = false;
909        loop {
910            let incoming = self.recv().await?;
911            if authenticated && incoming.tag == b'R' {
912                return Err(protocol("authentication request after AuthenticationOk"));
913            }
914            match incoming.message {
915                Message::AuthenticationOk => {
916                    if scram.is_some() && !scram_proved {
917                        return Err(WireError::Auth(
918                            "the server ended SCRAM authentication without proving its identity"
919                                .into(),
920                        ));
921                    }
922                    if !challenged && !policy.trust {
923                        return Err(refused("trust"));
924                    }
925                    authenticated = true;
926                }
927                Message::AuthenticationCleartextPassword => {
928                    if self.cancel.tls.is_none() {
929                        return Err(WireError::Auth(
930                            "server asked for a cleartext password on an unencrypted connection"
931                                .into(),
932                        ));
933                    }
934                    if !policy.password {
935                        return Err(refused("cleartext password"));
936                    }
937                    let password = configured_password(cfg)?;
938                    frontend::password_message(password.as_bytes(), &mut out).map_err(protocol)?;
939                    challenged = true;
940                }
941                Message::AuthenticationMd5Password(body) => {
942                    if !policy.md5 {
943                        return Err(refused("MD5"));
944                    }
945                    let password = configured_password(cfg)?;
946                    let hashed = md5_hash(cfg.user.as_bytes(), password.as_bytes(), body.salt());
947                    frontend::password_message(hashed.as_bytes(), &mut out).map_err(protocol)?;
948                    challenged = true;
949                }
950                Message::AuthenticationSasl(body) => {
951                    if !policy.scram {
952                        return Err(refused("SCRAM-SHA-256"));
953                    }
954                    if scram.is_some() {
955                        return Err(protocol("SASL start received twice"));
956                    }
957                    let mut mechanisms = body.mechanisms();
958                    let mut offered = false;
959                    while let Some(name) = mechanisms.next().map_err(protocol)? {
960                        offered |= name == sasl::SCRAM_SHA_256;
961                    }
962                    if !offered {
963                        return Err(WireError::Auth(
964                            "server offered no supported SASL mechanism (SCRAM-SHA-256 required)"
965                                .into(),
966                        ));
967                    }
968                    let password = configured_password(cfg)?;
969                    let client =
970                        ScramSha256::new(password.as_bytes(), ChannelBinding::unsupported());
971                    frontend::sasl_initial_response(
972                        sasl::SCRAM_SHA_256,
973                        client.message(),
974                        &mut out,
975                    )
976                    .map_err(protocol)?;
977                    scram = Some(client);
978                    challenged = true;
979                }
980                Message::AuthenticationSaslContinue(body) => {
981                    let client = scram
982                        .as_mut()
983                        .ok_or_else(|| protocol("SASL continue without SASL start"))?;
984                    client
985                        .update(body.data())
986                        .map_err(|e| WireError::Auth(e.to_string()))?;
987                    frontend::sasl_response(client.message(), &mut out).map_err(protocol)?;
988                }
989                Message::AuthenticationSaslFinal(body) => {
990                    let client = scram
991                        .as_mut()
992                        .ok_or_else(|| protocol("SASL final without SASL start"))?;
993                    client
994                        .finish(body.data())
995                        .map_err(|e| WireError::Auth(e.to_string()))?;
996                    scram_proved = true;
997                }
998                Message::AuthenticationGss | Message::AuthenticationGssContinue(_) => {
999                    return Err(WireError::Auth(
1000                        "server requested GSSAPI authentication, which is not supported".into(),
1001                    ));
1002                }
1003                Message::AuthenticationKerberosV5 => {
1004                    return Err(WireError::Auth(
1005                        "server requested Kerberos V5 authentication, which is not supported"
1006                            .into(),
1007                    ));
1008                }
1009                Message::AuthenticationSspi => {
1010                    return Err(WireError::Auth(
1011                        "server requested SSPI authentication, which is not supported".into(),
1012                    ));
1013                }
1014                Message::AuthenticationScmCredential => {
1015                    return Err(WireError::Auth(
1016                        "server requested SCM credential authentication, which is not supported"
1017                            .into(),
1018                    ));
1019                }
1020                Message::BackendKeyData(body) => {
1021                    self.cancel.process_id = body.process_id();
1022                    self.cancel.secret_key = body.secret_key();
1023                }
1024                Message::ReadyForQuery(_) => {
1025                    if !authenticated {
1026                        return Err(protocol("ReadyForQuery before AuthenticationOk"));
1027                    }
1028                    return Ok(());
1029                }
1030                Message::ErrorResponse(body) => return Err(WireError::Db(db_error(&body)?)),
1031                _ => return Err(unexpected(incoming.tag)),
1032            }
1033            if !out.is_empty() {
1034                self.send(&mut out).await?;
1035            }
1036        }
1037    }
1038}
1039
1040async fn connect_inner(
1041    cfg: &ConnectConfig,
1042    policy: &AuthPolicy,
1043    prepared: Option<Arc<ClientConfig>>,
1044) -> Result<Connection, WireError> {
1045    // A prepared configuration already holds the roots, which may be inline and so have no path here.
1046    if cfg.ssl_mode == SslMode::VerifyCa && cfg.ssl_root_cert.is_none() && prepared.is_none() {
1047        return Err(WireError::Tls("sslmode=verify-ca needs sslrootcert".into()));
1048    }
1049    let mut tcp = TcpStream::connect((cfg.host.as_str(), cfg.port)).await?;
1050    tcp.set_nodelay(true)?;
1051    let mut buf = BytesMut::new();
1052    let mut tls = None;
1053    let stream: Box<dyn Transport> = if cfg.ssl_mode == SslMode::Disable {
1054        Box::new(tcp)
1055    } else {
1056        let (answer, rest) = ssl_request(&mut tcp).await?;
1057        match answer {
1058            b'S' => {
1059                if !rest.is_empty() {
1060                    return Err(WireError::Tls(
1061                        "unexpected data after the SSL response".into(),
1062                    ));
1063                }
1064                let config = match prepared {
1065                    Some(config) => config,
1066                    None => tls::client_config(cfg.ssl_mode, cfg.ssl_root_cert.as_deref())?,
1067                };
1068                tls = Some(config.clone());
1069                start_tls(tcp, &cfg.host, config).await?
1070            }
1071            b'N' if cfg.ssl_mode == SslMode::Prefer => {
1072                buf = rest;
1073                Box::new(tcp)
1074            }
1075            b'N' => return Err(WireError::Tls("server does not support TLS".into())),
1076            other => {
1077                return Err(protocol(format!(
1078                    "unexpected answer to SSLRequest '{}'",
1079                    char::from(other)
1080                )));
1081            }
1082        }
1083    };
1084
1085    let mut conn = Connection {
1086        stream,
1087        buf,
1088        parameters: HashMap::new(),
1089        cancel: CancelHandle {
1090            host: cfg.host.clone(),
1091            port: cfg.port,
1092            tls,
1093            process_id: 0,
1094            secret_key: 0,
1095        },
1096        poisoned: false,
1097        peak_message_bytes: 0,
1098    };
1099    let mut params = vec![
1100        ("user", cfg.user.as_str()),
1101        ("database", cfg.database.as_str()),
1102        ("client_encoding", "UTF8"),
1103    ];
1104    params.extend(
1105        cfg.startup_params
1106            .iter()
1107            .map(|(k, v)| (k.as_str(), v.as_str())),
1108    );
1109    let mut out = BytesMut::new();
1110    frontend::startup_message(params, &mut out).map_err(protocol)?;
1111    conn.send(&mut out).await?;
1112    conn.authenticate(cfg, policy).await?;
1113    Ok(conn)
1114}
1115
1116/// Writes an SSLRequest and returns the one-byte answer plus any bytes that arrived with it.
1117async fn ssl_request(tcp: &mut TcpStream) -> Result<(u8, BytesMut), WireError> {
1118    let mut out = BytesMut::new();
1119    frontend::ssl_request(&mut out);
1120    tcp.write_all(&out).await?;
1121    tcp.flush().await?;
1122    let mut buf = BytesMut::new();
1123    while buf.is_empty() {
1124        if tcp.read_buf(&mut buf).await? == 0 {
1125            return Err(WireError::Io(io::Error::new(
1126                io::ErrorKind::UnexpectedEof,
1127                "server closed the connection",
1128            )));
1129        }
1130    }
1131    let answer = buf[0];
1132    buf.advance(1);
1133    Ok((answer, buf))
1134}
1135
1136async fn start_tls(
1137    tcp: TcpStream,
1138    host: &str,
1139    config: Arc<ClientConfig>,
1140) -> Result<Box<dyn Transport>, WireError> {
1141    let name = ServerName::try_from(host.to_owned()).map_err(|e| WireError::Tls(e.to_string()))?;
1142    let stream = TlsConnector::from(config)
1143        .connect(name, tcp)
1144        .await
1145        .map_err(|e| WireError::Tls(e.to_string()))?;
1146    Ok(Box::new(stream))
1147}
1148
1149fn configured_password(cfg: &ConnectConfig) -> Result<&str, WireError> {
1150    cfg.password
1151        .as_deref()
1152        .ok_or_else(|| WireError::Auth("server requires a password, but none is configured".into()))
1153}
1154
1155fn protocol(e: impl fmt::Display) -> WireError {
1156    WireError::Protocol(e.to_string())
1157}
1158
1159/// A socket error that carries a rustls error, such as a fatal alert, is a TLS failure rather than a lost connection.
1160fn transport_error(error: io::Error) -> WireError {
1161    match error
1162        .get_ref()
1163        .and_then(|inner| inner.downcast_ref::<rustls::Error>())
1164    {
1165        Some(tls) => WireError::Tls(tls.to_string()),
1166        None => WireError::Io(error),
1167    }
1168}
1169
1170fn unexpected(tag: u8) -> WireError {
1171    WireError::Protocol(format!("unexpected message '{}'", char::from(tag)))
1172}
1173
1174fn nul_refusal() -> WireError {
1175    WireError::Refused("SQL contains a NUL byte".into())
1176}
1177
1178fn utf8(bytes: &[u8]) -> Result<String, WireError> {
1179    String::from_utf8(bytes.to_vec())
1180        .map_err(|_| WireError::Protocol("server sent invalid UTF-8".into()))
1181}
1182
1183fn tx_status(byte: u8) -> Result<TxStatus, WireError> {
1184    match byte {
1185        b'I' => Ok(TxStatus::Idle),
1186        b'T' => Ok(TxStatus::InTransaction),
1187        b'E' => Ok(TxStatus::Failed),
1188        other => Err(protocol(format!("unknown transaction status {other}"))),
1189    }
1190}
1191
1192/// Errors that leave the protocol state unknown. Server errors and refusals do not.
1193fn poisons(e: &WireError) -> bool {
1194    !matches!(e, WireError::Db(_) | WireError::Refused(_))
1195}
1196
1197fn db_error(body: &ErrorResponseBody) -> Result<DbError, WireError> {
1198    let mut error = DbError {
1199        severity: String::new(),
1200        code: String::new(),
1201        message: String::new(),
1202        detail: None,
1203        hint: None,
1204        position: None,
1205    };
1206    let mut fields = body.fields();
1207    while let Some(field) = fields.next().map_err(protocol)? {
1208        let value = utf8(field.value_bytes())?;
1209        match field.type_() {
1210            b'S' => error.severity = value,
1211            b'C' => error.code = value,
1212            b'M' => error.message = value,
1213            b'D' => error.detail = Some(value),
1214            b'H' => error.hint = Some(value),
1215            b'P' => {
1216                error.position = Some(
1217                    value
1218                        .parse()
1219                        .map_err(|_| protocol(format!("invalid error position \"{value}\"")))?,
1220                );
1221            }
1222            _ => {}
1223        }
1224    }
1225    Ok(error)
1226}
1227
1228fn column_list(body: &RowDescriptionBody) -> Result<Vec<Column>, WireError> {
1229    let mut columns = Vec::new();
1230    let mut fields = body.fields();
1231    while let Some(field) = fields.next().map_err(protocol)? {
1232        columns.push(Column {
1233            name: field.name().to_owned(),
1234            type_oid: field.type_oid(),
1235            type_modifier: field.type_modifier(),
1236        });
1237    }
1238    Ok(columns)
1239}
1240
1241/// Borrowed field values of a DataRow, None for SQL NULL.
1242fn field_slices(body: &DataRowBody) -> Result<Vec<Option<&[u8]>>, WireError> {
1243    let bytes = body.buffer();
1244    let mut ranges = body.ranges();
1245    let mut values = Vec::new();
1246    while let Some(range) = ranges.next().map_err(protocol)? {
1247        values.push(match range {
1248            None => None,
1249            Some(r) => Some(
1250                bytes
1251                    .get(r)
1252                    .ok_or_else(|| protocol("data row field out of range"))?,
1253            ),
1254        });
1255    }
1256    Ok(values)
1257}
1258
1259fn text_row(body: &DataRowBody) -> Result<Vec<Option<String>>, WireError> {
1260    let mut row = Vec::new();
1261    for value in field_slices(body)? {
1262        row.push(match value {
1263            Some(bytes) => Some(utf8(bytes)?),
1264            None => None,
1265        });
1266    }
1267    Ok(row)
1268}
1269
1270/// Keeps one streamed row within the limits. Returns the truncation when this row must not be kept.
1271fn keep_row(
1272    fields: Vec<Option<Field>>,
1273    rows: &mut Vec<Vec<Option<Field>>>,
1274    kept: &mut usize,
1275    limits: &FetchLimits,
1276) -> Option<Truncation> {
1277    if rows.len() >= limits.max_rows {
1278        return Some(Truncation::Rows);
1279    }
1280    let row_bytes: usize = fields.iter().flatten().map(|f| f.data.len()).sum();
1281    if *kept + row_bytes > limits.max_bytes {
1282        if rows.is_empty() {
1283            *kept += row_bytes;
1284            rows.push(fields);
1285        }
1286        return Some(Truncation::Bytes);
1287    }
1288    *kept += row_bytes;
1289    rows.push(fields);
1290    None
1291}
1292
1293/// A response the explain path does not accept. Logged by `explain_unbound`, which never logs SQL text.
1294fn explain_shape(reason: &'static str) -> WireError {
1295    protocol(reason)
1296}
1297
1298fn eof() -> WireError {
1299    WireError::Io(io::Error::new(
1300        io::ErrorKind::UnexpectedEof,
1301        "server closed the connection",
1302    ))
1303}
1304
1305/// The error for an authentication method that `require_auth` does not allow.
1306fn refused(method: &str) -> WireError {
1307    WireError::Auth(format!(
1308        "the server asked for {method} authentication, which is not allowed here (require_auth)"
1309    ))
1310}
1311
1312/// Rejects a session parameter whose value the read-only recipe depends on.
1313fn check_session_parameter(name: &str, value: &str) -> Result<(), WireError> {
1314    match (name, value) {
1315        ("standard_conforming_strings", "on") | ("client_encoding", "UTF8") => Ok(()),
1316        ("standard_conforming_strings", other) => Err(protocol(format!(
1317            "server changed standard_conforming_strings to \"{other}\""
1318        ))),
1319        ("client_encoding", other) => Err(protocol(format!(
1320            "server changed client_encoding to \"{other}\""
1321        ))),
1322        _ => Ok(()),
1323    }
1324}
1325
1326/// Parses a server_version string such as "19.0" or "15.20 (...)" into PG_VERSION_NUM form.
1327pub fn parse_server_version_num(text: &str) -> u32 {
1328    let (major, rest) = leading_number(text);
1329    let (minor, rest) = after_dot(rest);
1330    if major >= 10 {
1331        return major.saturating_mul(10_000).saturating_add(minor);
1332    }
1333    let (patch, _) = after_dot(rest);
1334    major
1335        .saturating_mul(10_000)
1336        .saturating_add(minor.saturating_mul(100))
1337        .saturating_add(patch)
1338}
1339
1340fn after_dot(s: &str) -> (u32, &str) {
1341    match s.strip_prefix('.') {
1342        Some(rest) => leading_number(rest),
1343        None => (0, s),
1344    }
1345}
1346
1347fn leading_number(s: &str) -> (u32, &str) {
1348    let end = s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len());
1349    (s[..end].parse().unwrap_or(0), &s[end..])
1350}