Skip to main content

turnloop_postgres/
lib.rs

1#![deny(unsafe_op_in_unsafe_fn)]
2//!
3//! # Getting started on turnloop
4//! Enable the `turnloop` feature for the `asynchronous` module. The embedding
5//! host owns `LocalExecutor` and calls `turn`; adapters await its streams and
6//! deadline futures. See the crate README and turnloop-io for ownership, streaming
7//! and cancellation examples. Default features retain the sans-I/O API.
8
9#![forbid(unsafe_code)]
10//! Pull-based, bounded, sans-I/O PostgreSQL client.
11//!
12//! Feed bytes with `receive`, pull `next_event`, write `output`, then acknowledge
13//! only transmitted bytes with `consume_output`. Events borrow reusable storage.
14//! The host owns sockets, TLS, entropy, time and result materialization.
15
16#[cfg(all(target_os = "wasi", target_env = "p3"))]
17use turnloop_wasi_random as _;
18
19use bytes::BytesMut;
20pub use postgres_protocol::authentication::sasl::{ChannelBinding, ScramSha256};
21use postgres_protocol::{
22    IsNull,
23    authentication::md5_hash,
24    message::{backend::Header, frontend},
25};
26use std::{collections::VecDeque, fmt};
27pub mod pool;
28pub mod types;
29mod wire;
30use wire::Cursor;
31pub use wire::{ConnectionFailure, Field, Fields, Row, ServerError};
32
33#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
34mod host_time;
35#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
36pub use host_time::Instant;
37#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
38pub use std::time::Instant;
39
40pub type Token = u64;
41pub type Result<T> = std::result::Result<T, Error>;
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub enum Error {
44    Protocol(&'static str),
45    State(&'static str),
46    Limit,
47    Timeout,
48    Transport,
49    /// The server terminated the session; preserves SQLSTATE and every field.
50    ConnectionAborted(ConnectionFailure),
51    Cancelled,
52}
53impl fmt::Display for Error {
54    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55        match self {
56            Self::Protocol(s) | Self::State(s) => f.write_str(s),
57            Self::Limit => f.write_str("protocol buffer limit exceeded"),
58            Self::Timeout => f.write_str("Connection terminated due to timeout"),
59            Self::Transport => f.write_str("Connection terminated unexpectedly"),
60            Self::ConnectionAborted(error) => write!(f, "Connection aborted: {error}"),
61            Self::Cancelled => f.write_str("Connection terminated"),
62        }
63    }
64}
65impl std::error::Error for Error {}
66impl From<Error> for std::io::Error {
67    fn from(error: Error) -> Self {
68        let kind = match error {
69            Error::ConnectionAborted(_) | Error::Transport => std::io::ErrorKind::ConnectionAborted,
70            Error::Timeout => std::io::ErrorKind::TimedOut,
71            _ => std::io::ErrorKind::Other,
72        };
73        Self::new(kind, error)
74    }
75}
76impl From<std::io::Error> for Error {
77    fn from(_: std::io::Error) -> Self {
78        Self::Protocol("invalid PostgreSQL message")
79    }
80}
81
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub enum SslMode {
84    Disable,
85    Prefer,
86    Require,
87}
88#[derive(Clone)]
89pub struct Config {
90    pub user: String,
91    pub password: Vec<u8>,
92    pub database: String,
93    pub application_name: String,
94    pub ssl: SslMode,
95    /// Require SCRAM-SHA-256-PLUS; the host supplies tls-server-end-point data.
96    pub channel_binding_required: bool,
97    pub max_buffer: usize,
98    pub max_pending: usize,
99    pub max_scram_iterations: u32,
100    pub connect_deadline: Option<Instant>,
101}
102impl Default for Config {
103    fn default() -> Self {
104        Self {
105            user: "postgres".into(),
106            password: Vec::new(),
107            database: "postgres".into(),
108            application_name: "turnloop".into(),
109            ssl: SslMode::Disable,
110            channel_binding_required: false,
111            max_buffer: 64 * 1024 * 1024,
112            max_pending: 1024,
113            max_scram_iterations: 1_000_000,
114            connect_deadline: None,
115        }
116    }
117}
118#[derive(Debug, Clone, Copy, PartialEq, Eq)]
119pub enum TransactionStatus {
120    Idle,
121    InTransaction,
122    Failed,
123}
124#[derive(Debug, Clone, PartialEq, Eq)]
125pub enum Outcome {
126    Success,
127    /// A statement failed and ReadyForQuery confirmed the session can continue.
128    ServerError,
129    Aborted(Error),
130}
131#[derive(Debug)]
132pub enum Event<'a> {
133    UpgradeTls,
134    /// Build upstream ScramSha256 outside the core (its constructor reads entropy).
135    ScramNeeded {
136        plus: bool,
137    },
138    Connected,
139    ParameterStatus {
140        name: &'a str,
141        value: &'a str,
142    },
143    Fields {
144        token: Token,
145        fields: Fields<'a>,
146    },
147    Row {
148        token: Token,
149        row: Row<'a>,
150    },
151    CommandComplete {
152        token: Token,
153        tag: &'a str,
154        row_count: Option<u64>,
155    },
156    Error {
157        token: Option<Token>,
158        error: ServerError<'a>,
159    },
160    Notice(ServerError<'a>),
161    Notification {
162        process_id: i32,
163        channel: &'a str,
164        payload: &'a str,
165    },
166    CopyIn {
167        token: Token,
168        binary: bool,
169        column_formats: &'a [u8],
170    },
171    CopyOut {
172        token: Token,
173        binary: bool,
174        column_formats: &'a [u8],
175    },
176    CopyData {
177        token: Token,
178        data: &'a [u8],
179    },
180    CopyDone {
181        token: Token,
182    },
183    Completed {
184        token: Token,
185        outcome: Outcome,
186        transaction: TransactionStatus,
187    },
188    Closed {
189        reason: Error,
190    },
191}
192#[derive(Debug, Clone, Copy, PartialEq, Eq)]
193enum State {
194    Ssl,
195    Tls,
196    Auth,
197    Scram(bool),
198    Ready,
199    Closing,
200    Closed,
201}
202#[derive(Debug)]
203struct Pending {
204    token: Token,
205    deadline: Option<Instant>,
206    failed: bool,
207    extended: bool,
208    parse: Option<usize>,
209}
210struct Statement {
211    name: String,
212    sql: String,
213    oids: Vec<u32>,
214    parsed: bool,
215}
216/// A parameter is already encoded by the host or `types`; 0=text, 1=binary.
217#[derive(Clone, Copy, Debug)]
218pub struct Parameter<'a> {
219    pub value: Option<&'a [u8]>,
220    pub format: i16,
221}
222
223/// Parameters of one extended-protocol operation. An empty name is uncached.
224#[derive(Clone, Copy, Debug)]
225pub struct ExtendedQuery<'a> {
226    pub name: &'a str,
227    pub sql: &'a str,
228    pub oids: &'a [u32],
229    pub params: &'a [Parameter<'a>],
230    pub result_formats: &'a [i16],
231}
232
233pub struct Connection {
234    config: Config,
235    state: State,
236    input: Vec<u8>,
237    input_at: usize,
238    output: BytesMut,
239    output_at: usize,
240    pending: VecDeque<Pending>,
241    statements: Vec<Statement>,
242    scram: Option<ScramSha256>,
243    auth_ok: bool,
244    tls: bool,
245    binding_available: bool,
246    scram_plus: bool,
247    copy_in: bool,
248    transaction: TransactionStatus,
249    key: Option<(i32, i32)>,
250    reason: Error,
251}
252impl Connection {
253    pub fn new(config: Config) -> Result<Self> {
254        if config.max_buffer < 1024
255            || config.max_buffer > i32::MAX as usize
256            || config.max_pending == 0
257        {
258            return Err(Error::Limit);
259        }
260        if config.user.contains('\0')
261            || config.database.contains('\0')
262            || config.application_name.contains('\0')
263        {
264            return Err(Error::State("NUL in startup parameter"));
265        }
266        if config.channel_binding_required && config.ssl == SslMode::Disable {
267            return Err(Error::State("channel binding requires TLS"));
268        }
269        let mut this = Self {
270            config,
271            state: State::Auth,
272            input: Vec::with_capacity(8192),
273            input_at: 0,
274            output: BytesMut::with_capacity(8192),
275            output_at: 0,
276            pending: VecDeque::with_capacity(16),
277            statements: Vec::new(),
278            scram: None,
279            auth_ok: false,
280            tls: false,
281            binding_available: false,
282            scram_plus: false,
283            copy_in: false,
284            transaction: TransactionStatus::Idle,
285            key: None,
286            reason: Error::Transport,
287        };
288        if this.config.ssl == SslMode::Disable {
289            this.startup()?;
290        } else {
291            this.state = State::Ssl;
292            frontend::ssl_request(&mut this.output);
293        }
294        Ok(this)
295    }
296    fn startup(&mut self) -> Result<()> {
297        frontend::startup_message(
298            [
299                ("user", self.config.user.as_str()),
300                ("database", self.config.database.as_str()),
301                ("application_name", self.config.application_name.as_str()),
302                ("client_encoding", "UTF8"),
303                ("DateStyle", "ISO"),
304            ],
305            &mut self.output,
306        )?;
307        self.state = State::Auth;
308        Ok(())
309    }
310    pub fn output(&self) -> &[u8] {
311        &self.output[self.output_at..]
312    }
313    pub fn consume_output(&mut self, n: usize) -> Result<()> {
314        if n > self.output().len() {
315            return Err(Error::State("invalid output acknowledgement"));
316        }
317        self.output_at += n;
318        if self.output_at == self.output.len() {
319            self.output.clear();
320            self.output_at = 0;
321        }
322        Ok(())
323    }
324    pub fn receive(&mut self, bytes: &[u8]) -> Result<()> {
325        if matches!(self.state, State::Tls | State::Closing | State::Closed) {
326            return Err(Error::State("connection cannot receive plaintext now"));
327        }
328        let remaining = self.input.len() - self.input_at;
329        if bytes.len() > self.config.max_buffer.saturating_sub(remaining) {
330            self.abort(Error::Limit);
331            return Err(Error::Limit);
332        }
333        if self.input_at != 0 {
334            self.input.copy_within(self.input_at.., 0);
335            self.input.truncate(remaining);
336            self.input_at = 0;
337        }
338        self.input.extend_from_slice(bytes);
339        Ok(())
340    }
341    /// Acknowledge TLS without channel-binding data (plain SCRAM fallback).
342    pub fn tls_established(&mut self) -> Result<()> {
343        self.tls_established_with_channel_binding(false)
344    }
345    /// Acknowledge verified TLS and whether the host can supply tls-server-end-point
346    /// data to `start_scram`. The core prefers PLUS only when data is available.
347    pub fn tls_established_with_channel_binding(&mut self, available: bool) -> Result<()> {
348        if self.state != State::Tls || !self.output().is_empty() {
349            return Err(Error::State("TLS transition not ready"));
350        }
351        if self.config.channel_binding_required && !available {
352            return Err(Error::State(
353                "channel binding required but certificate binding is unavailable",
354            ));
355        }
356        self.tls = true;
357        self.binding_available = available;
358        self.startup()
359    }
360    pub fn start_scram(&mut self, scram: ScramSha256) -> Result<()> {
361        let State::Scram(plus) = self.state else {
362            return Err(Error::State("SCRAM was not requested"));
363        };
364        if plus != scram.message().starts_with(b"p=tls-server-end-point,") {
365            return Err(Error::State("SCRAM channel binding mismatch"));
366        }
367        frontend::sasl_initial_response(
368            if plus {
369                "SCRAM-SHA-256-PLUS"
370            } else {
371                "SCRAM-SHA-256"
372            },
373            scram.message(),
374            &mut self.output,
375        )?;
376        self.scram = Some(scram);
377        self.state = State::Auth;
378        Ok(())
379    }
380    fn accept(&self, token: Token) -> Result<()> {
381        if self.state != State::Ready || self.copy_in {
382            return Err(Error::State("Client is not queryable"));
383        }
384        if self.pending.len() >= self.config.max_pending {
385            return Err(Error::Limit);
386        }
387        if self.pending.iter().any(|p| p.token == token) {
388            return Err(Error::State("duplicate operation token"));
389        }
390        Ok(())
391    }
392    fn finish_command(
393        &mut self,
394        token: Token,
395        deadline: Option<Instant>,
396        parse: Option<usize>,
397        before: usize,
398        result: Result<()>,
399        extended: bool,
400    ) -> Result<()> {
401        if let Err(e) = result {
402            self.output.truncate(before);
403            return Err(e);
404        }
405        if self.output.len() > self.config.max_buffer {
406            self.output.truncate(before);
407            return Err(Error::Limit);
408        }
409        self.pending.push_back(Pending {
410            token,
411            deadline,
412            failed: false,
413            extended,
414            parse,
415        });
416        Ok(())
417    }
418    pub fn query(&mut self, token: Token, sql: &str, deadline: Option<Instant>) -> Result<()> {
419        self.accept(token)?;
420        if sql.len().saturating_add(6) > self.config.max_buffer.saturating_sub(self.output.len()) {
421            return Err(Error::Limit);
422        }
423        let before = self.output.len();
424        let result = frontend::query(sql, &mut self.output).map_err(Error::from);
425        self.finish_command(token, deadline, None, before, result, false)
426    }
427    /// Every operation ends in Sync, so an error cannot discard a later token.
428    pub fn execute(
429        &mut self,
430        token: Token,
431        query: ExtendedQuery<'_>,
432        deadline: Option<Instant>,
433    ) -> Result<()> {
434        let ExtendedQuery {
435            name,
436            sql,
437            oids,
438            params,
439            result_formats,
440        } = query;
441        self.accept(token)?;
442        let size = params.iter().fold(
443            64usize
444                .saturating_add(name.len().saturating_mul(2))
445                .saturating_add(sql.len())
446                .saturating_add(oids.len().saturating_mul(4))
447                .saturating_add(result_formats.len().saturating_mul(2)),
448            |n, p| {
449                n.saturating_add(6)
450                    .saturating_add(p.value.map_or(0, <[u8]>::len))
451            },
452        );
453        if size > self.config.max_buffer.saturating_sub(self.output.len()) {
454            return Err(Error::Limit);
455        }
456
457        if params.iter().any(|p| !matches!(p.format, 0 | 1))
458            || result_formats.iter().any(|f| !matches!(f, 0 | 1))
459        {
460            return Err(Error::State("invalid format"));
461        }
462        let index = if name.is_empty() {
463            None
464        } else {
465            self.statements.iter().position(|s| s.name == name)
466        };
467        if let Some(i) = index {
468            let s = &self.statements[i];
469            if s.sql != sql || s.oids != oids {
470                return Err(Error::State(
471                    "Prepared statements must be unique - a different statement was used for this name",
472                ));
473            }
474        }
475        // Refuse reuse until ParseComplete; otherwise a pipelined parse failure
476        // could make a later accepted operation refer to a nonexistent statement.
477        if index.is_some_and(|i| !self.statements[i].parsed) {
478            return Err(Error::State("named statement parse still pending"));
479        }
480        let before = self.output.len();
481        let result = (|| {
482            if index.is_none() {
483                frontend::parse(name, sql, oids.iter().copied(), &mut self.output)?;
484            }
485            frontend::bind(
486                "",
487                name,
488                params.iter().map(|p| p.format),
489                params.iter(),
490                |p, out| {
491                    if let Some(value) = p.value {
492                        out.extend_from_slice(value);
493                        Ok(IsNull::No)
494                    } else {
495                        Ok(IsNull::Yes)
496                    }
497                },
498                result_formats.iter().copied(),
499                &mut self.output,
500            )
501            .map_err(|_| Error::Protocol("invalid Bind message"))?;
502            frontend::describe(b'P', "", &mut self.output)?;
503            frontend::execute("", 0, &mut self.output)?;
504            frontend::sync(&mut self.output);
505            Ok(())
506        })();
507        let new_index = if result.is_ok()
508            && self.output.len() <= self.config.max_buffer
509            && index.is_none()
510            && !name.is_empty()
511        {
512            let i = self.statements.len();
513            self.statements.push(Statement {
514                name: name.into(),
515                sql: sql.into(),
516                oids: oids.into(),
517                parsed: false,
518            });
519            Some(i)
520        } else {
521            None
522        };
523        self.finish_command(token, deadline, new_index, before, result, true)
524    }
525    pub fn copy_data(&mut self, bytes: &[u8]) -> Result<()> {
526        if !self.copy_in {
527            return Err(Error::State("COPY IN is not active"));
528        }
529        if bytes.len().saturating_add(5) > self.config.max_buffer.saturating_sub(self.output.len())
530        {
531            return Err(Error::Limit);
532        }
533        frontend::CopyData::new(bytes)?.write(&mut self.output);
534        Ok(())
535    }
536    pub fn copy_finish(&mut self, error: Option<&str>) -> Result<()> {
537        if !self.copy_in {
538            return Err(Error::State("COPY IN is not active"));
539        }
540        let before = self.output.len();
541        let result = if let Some(message) = error {
542            frontend::copy_fail(message, &mut self.output)
543        } else {
544            frontend::copy_done(&mut self.output);
545            Ok(())
546        };
547        // The earlier Sync is ignored by the server inside COPY IN.
548        // Extended protocol needs a fresh Sync after CopyDone/CopyFail.
549        if result.is_ok() && self.pending.front().is_some_and(|p| p.extended) {
550            frontend::sync(&mut self.output);
551        }
552        if result.is_err() || self.output.len() > self.config.max_buffer {
553            self.output.truncate(before);
554            return Err(Error::Limit);
555        }
556        self.copy_in = false;
557        Ok(())
558    }
559    /// Send on a NEW connection; the main stream remains owned by this state machine.
560    pub fn cancel_request(&self) -> Option<[u8; 16]> {
561        self.key.map(|(pid, key)| {
562            let mut b = [0; 16];
563            b[..4].copy_from_slice(&16u32.to_be_bytes());
564            b[4..8].copy_from_slice(&80877102u32.to_be_bytes());
565            b[8..12].copy_from_slice(&pid.to_be_bytes());
566            b[12..].copy_from_slice(&key.to_be_bytes());
567            b
568        })
569    }
570    pub fn transaction_status(&self) -> TransactionStatus {
571        self.transaction
572    }
573    pub fn is_ready(&self) -> bool {
574        self.state == State::Ready
575    }
576    pub fn pending_count(&self) -> usize {
577        self.pending.len()
578    }
579    pub fn next_timeout(&self) -> Option<Instant> {
580        if matches!(self.state, State::Closing | State::Closed) {
581            return None;
582        }
583        self.pending
584            .iter()
585            .filter_map(|p| p.deadline)
586            .chain(if self.state != State::Ready {
587                self.config.connect_deadline
588            } else {
589                None
590            })
591            .min()
592    }
593    pub fn handle_timeout(&mut self, now: Instant) {
594        if self.next_timeout().is_some_and(|t| t <= now) {
595            self.abort(Error::Timeout);
596        }
597    }
598    /// Transport EOF, TLS failure, cancellation or malformed input terminates all
599    /// pending tokens once. Pull Completed events followed by Closed.
600    pub fn abort(&mut self, reason: Error) {
601        if matches!(self.state, State::Closing | State::Closed) {
602            return;
603        }
604        self.reason = reason;
605        self.state = State::Closing;
606        self.output.clear();
607        self.output_at = 0;
608        self.copy_in = false;
609    }
610    pub fn end(&mut self) -> Result<()> {
611        if !self.pending.is_empty() || self.state != State::Ready {
612            return Err(Error::State("drain queries before end"));
613        }
614        frontend::terminate(&mut self.output);
615        self.state = State::Closing;
616        self.reason = Error::Cancelled;
617        Ok(())
618    }
619    fn token(&self) -> Result<Token> {
620        self.pending
621            .front()
622            .map(|p| p.token)
623            .ok_or(Error::Protocol("unsolicited query response"))
624    }
625    /// Pull the next borrowed event. A terminal server ErrorResponse returns
626    /// `Error::ConnectionAborted` immediately and makes the session unusable.
627    /// Continue pulling to drain one Aborted completion per pending token, then
628    /// Closed; a later transport abort cannot replace the server diagnostic.
629    pub fn next_event(&mut self) -> Result<Option<Event<'_>>> {
630        if self.state == State::Closing {
631            if let Some(p) = self.pending.pop_front() {
632                return Ok(Some(Event::Completed {
633                    token: p.token,
634                    outcome: Outcome::Aborted(self.reason.clone()),
635                    transaction: self.transaction,
636                }));
637            }
638            if !self.output().is_empty() {
639                return Ok(None);
640            }
641            self.state = State::Closed;
642            return Ok(Some(Event::Closed {
643                reason: self.reason.clone(),
644            }));
645        }
646        if matches!(self.state, State::Closed | State::Tls | State::Scram(_)) {
647            return Ok(None);
648        }
649        if self.state == State::Ssl {
650            let Some(&reply) = self.input.get(self.input_at) else {
651                return Ok(None);
652            };
653            self.input_at += 1;
654            match reply {
655                b'S' => {
656                    if self.input.len() != self.input_at {
657                        return Err(Error::Protocol("plaintext after TLS acceptance"));
658                    }
659                    self.state = State::Tls;
660                    return Ok(Some(Event::UpgradeTls));
661                }
662                b'N' if self.config.ssl == SslMode::Prefer => {
663                    self.startup()?;
664                }
665                b'N' => {
666                    return Err(Error::Protocol(
667                        "The server does not support SSL connections",
668                    ));
669                }
670                _ => return Err(Error::Protocol("invalid SSLRequest response")),
671            }
672        }
673        loop {
674            let available = &self.input[self.input_at..];
675            let Some(header) = Header::parse(available)? else {
676                return Ok(None);
677            };
678            if header.len() < 4 {
679                return Err(Error::Protocol("invalid message length"));
680            }
681            let length = header.len() as usize + 1;
682            if length > self.config.max_buffer {
683                return Err(Error::Limit);
684            }
685            if available.len() < length {
686                return Ok(None);
687            }
688            let start = self.input_at + 5;
689            self.input_at += length;
690            let body = &self.input[start..self.input_at];
691            let mut c = Cursor(body);
692            match header.tag() {
693                b'R' if self.state == State::Auth => match c.u32()? {
694                    0 => {
695                        c.end()?;
696                        if self.scram.is_some() {
697                            return Err(Error::Protocol("SCRAM final verification missing"));
698                        }
699                        if self.config.channel_binding_required && !self.scram_plus {
700                            return Err(Error::Protocol(
701                                "channel binding required but SCRAM-PLUS was not authenticated",
702                            ));
703                        }
704                        self.auth_ok = true;
705                    }
706                    3 => {
707                        c.end()?;
708                        if self.config.channel_binding_required {
709                            return Err(Error::Protocol("server did not offer channel binding"));
710                        }
711                        frontend::password_message(&self.config.password, &mut self.output)?;
712                    }
713                    5 => {
714                        let salt = c.take(4)?.try_into().unwrap();
715                        c.end()?;
716                        if self.config.channel_binding_required {
717                            return Err(Error::Protocol("server did not offer channel binding"));
718                        }
719                        let hash =
720                            md5_hash(self.config.user.as_bytes(), &self.config.password, salt);
721                        frontend::password_message(hash.as_bytes(), &mut self.output)?;
722                    }
723                    10 => {
724                        let mut plain = false;
725                        let mut plus = false;
726                        loop {
727                            match c.cstr()? {
728                                "" => break,
729                                "SCRAM-SHA-256" => plain = true,
730                                "SCRAM-SHA-256-PLUS" => plus = true,
731                                _ => {}
732                            }
733                        }
734                        c.end()?;
735                        let plus = self.tls && self.binding_available && plus;
736                        if self.config.channel_binding_required && !plus {
737                            return Err(Error::Protocol(
738                                "channel binding required but server did not offer SCRAM-SHA-256-PLUS",
739                            ));
740                        }
741                        if !plus && !plain {
742                            return Err(Error::Protocol("unsupported SASL mechanisms"));
743                        }
744                        self.scram_plus = plus;
745                        self.state = State::Scram(plus);
746                        return Ok(Some(Event::ScramNeeded { plus }));
747                    }
748                    11 => {
749                        let iterations = std::str::from_utf8(c.0)
750                            .ok()
751                            .and_then(|s| s.split(',').find_map(|p| p.strip_prefix("i=")))
752                            .and_then(|s| s.parse::<u32>().ok())
753                            .ok_or(Error::Protocol("invalid SCRAM iterations"))?;
754                        if iterations == 0 || iterations > self.config.max_scram_iterations {
755                            return Err(Error::Limit);
756                        }
757                        let scram = self
758                            .scram
759                            .as_mut()
760                            .ok_or(Error::Protocol("unexpected SASL continuation"))?;
761                        scram.update(c.0)?;
762                        frontend::sasl_response(scram.message(), &mut self.output)?;
763                    }
764                    12 => {
765                        let mut scram = self
766                            .scram
767                            .take()
768                            .ok_or(Error::Protocol("unexpected SASL final"))?;
769                        scram.finish(c.0)?;
770                    }
771                    _ => return Err(Error::Protocol("unsupported authentication method")),
772                },
773                b'S' => {
774                    let name = c.cstr()?;
775                    let value = c.cstr()?;
776                    c.end()?;
777                    return Ok(Some(Event::ParameterStatus { name, value }));
778                }
779                b'K' => {
780                    self.key = Some((c.i32()?, c.i32()?));
781                    c.end()?;
782                }
783                b'Z' => {
784                    self.transaction = match c.u8()? {
785                        b'I' => TransactionStatus::Idle,
786                        b'T' => TransactionStatus::InTransaction,
787                        b'E' => TransactionStatus::Failed,
788                        _ => return Err(Error::Protocol("invalid transaction status")),
789                    };
790                    c.end()?;
791                    self.copy_in = false;
792                    if self.state == State::Auth {
793                        if !self.auth_ok {
794                            return Err(Error::Protocol("Ready before authentication"));
795                        }
796                        self.state = State::Ready;
797                        return Ok(Some(Event::Connected));
798                    }
799                    let p = self
800                        .pending
801                        .pop_front()
802                        .ok_or(Error::Protocol("unsolicited ReadyForQuery"))?;
803                    // Keep stable cache indices; failed names can be registered again.
804                    if let Some(i) = p.parse
805                        && !self.statements[i].parsed
806                    {
807                        self.statements[i].name.clear();
808                    }
809                    return Ok(Some(Event::Completed {
810                        token: p.token,
811                        outcome: if p.failed {
812                            Outcome::ServerError
813                        } else {
814                            Outcome::Success
815                        },
816                        transaction: self.transaction,
817                    }));
818                }
819                b'T' => {
820                    return Ok(Some(Event::Fields {
821                        token: self.token()?,
822                        fields: Fields::parse(body)?,
823                    }));
824                }
825                b'D' => {
826                    return Ok(Some(Event::Row {
827                        token: self.token()?,
828                        row: Row::parse(body)?,
829                    }));
830                }
831                b'C' => {
832                    let tag = c.cstr()?;
833                    c.end()?;
834                    let row_count = tag.rsplit(' ').next().and_then(|s| s.parse().ok());
835                    return Ok(Some(Event::CommandComplete {
836                        token: self.token()?,
837                        tag,
838                        row_count,
839                    }));
840                }
841                b'I' => {
842                    c.end()?;
843                    return Ok(Some(Event::CommandComplete {
844                        token: self.token()?,
845                        tag: "",
846                        row_count: None,
847                    }));
848                }
849                b'E' => {
850                    let error = ServerError::parse(body)?;
851                    let token = self.pending.front_mut().map(|p| {
852                        p.failed = true;
853                        p.token
854                    });
855                    if token.is_none()
856                        || matches!(
857                            error.get(b'V').or(error.severity()),
858                            Some("FATAL" | "PANIC")
859                        )
860                    {
861                        self.state = State::Closing;
862                        self.reason = Error::ConnectionAborted(ConnectionFailure::new(error));
863                        self.output.clear();
864                        self.output_at = 0;
865                        self.copy_in = false;
866                        // FATAL/PANIC needs no ReadyForQuery or EOF confirmation.
867                        // Subsequent pulls still complete every queued token once.
868                        return Err(self.reason.clone());
869                    }
870                    return Ok(Some(Event::Error { token, error }));
871                }
872                b'N' => return Ok(Some(Event::Notice(ServerError::parse(body)?))),
873                b'A' => {
874                    let process_id = c.i32()?;
875                    let channel = c.cstr()?;
876                    let payload = c.cstr()?;
877                    c.end()?;
878                    return Ok(Some(Event::Notification {
879                        process_id,
880                        channel,
881                        payload,
882                    }));
883                }
884                b'1' => {
885                    c.end()?;
886                    let p = self
887                        .pending
888                        .front_mut()
889                        .ok_or(Error::Protocol("unsolicited ParseComplete"))?;
890                    if let Some(i) = p.parse {
891                        self.statements[i].parsed = true;
892                    }
893                }
894                b'2' | b'3' | b'n' => {
895                    c.end()?;
896                    self.token()?;
897                }
898                b'G' | b'H' => {
899                    let binary = match c.u8()? {
900                        0 => false,
901                        1 => true,
902                        _ => return Err(Error::Protocol("invalid COPY format")),
903                    };
904                    let count = c.u16()? as usize;
905                    let column_formats = c.take(count * 2)?;
906                    c.end()?;
907                    let token = self.token()?;
908                    if header.tag() == b'G' {
909                        if self.pending.len() != 1 {
910                            return Err(Error::Protocol("COPY IN requires an exclusive query"));
911                        }
912                        self.copy_in = true;
913                        return Ok(Some(Event::CopyIn {
914                            token,
915                            binary,
916                            column_formats,
917                        }));
918                    }
919                    return Ok(Some(Event::CopyOut {
920                        token,
921                        binary,
922                        column_formats,
923                    }));
924                }
925                b'd' => {
926                    return Ok(Some(Event::CopyData {
927                        token: self.token()?,
928                        data: body,
929                    }));
930                }
931                b'c' => {
932                    c.end()?;
933                    return Ok(Some(Event::CopyDone {
934                        token: self.token()?,
935                    }));
936                }
937                _ => return Err(Error::Protocol("unexpected backend message")),
938            }
939        }
940    }
941}
942
943#[cfg(feature = "turnloop")]
944pub mod asynchronous;