1#![deny(unsafe_op_in_unsafe_fn)]
2#![forbid(unsafe_code)]
10#[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::{
32 ConnectionFailure, Field, Fields, OwnedFields, OwnedRow, OwnedServerError, Row, ServerError,
33};
34
35#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
36mod host_time;
37#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
38pub use host_time::Instant;
39#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
40pub use std::time::Instant;
41
42pub type Token = u64;
43pub type Result<T> = std::result::Result<T, Error>;
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub enum Error {
46 Protocol(&'static str),
47 State(&'static str),
48 Limit,
49 Timeout,
50 Transport(Option<TransportFailure>),
53 ConnectionAborted(ConnectionFailure),
55 Cancelled,
56}
57impl Error {
58 pub fn transport(error: &std::io::Error) -> Self {
60 Self::Transport(Some(error.into()))
61 }
62}
63impl fmt::Display for Error {
64 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65 match self {
66 Self::Protocol(s) | Self::State(s) => f.write_str(s),
67 Self::Limit => f.write_str("protocol buffer limit exceeded"),
68 Self::Timeout => f.write_str("Connection terminated due to timeout"),
69 Self::Transport(None) => f.write_str("Connection terminated unexpectedly"),
70 Self::Transport(Some(failure)) => {
71 write!(f, "Connection terminated unexpectedly: {failure}")
72 }
73 Self::ConnectionAborted(error) => write!(f, "Connection aborted: {error}"),
74 Self::Cancelled => f.write_str("Connection terminated"),
75 }
76 }
77}
78impl std::error::Error for Error {}
79impl From<Error> for std::io::Error {
80 fn from(error: Error) -> Self {
81 let kind = match &error {
82 Error::Transport(Some(failure)) => failure.kind(),
83 Error::ConnectionAborted(_) | Error::Transport(None) => {
84 std::io::ErrorKind::ConnectionAborted
85 }
86 Error::Timeout => std::io::ErrorKind::TimedOut,
87 _ => std::io::ErrorKind::Other,
88 };
89 Self::new(kind, error)
90 }
91}
92#[derive(Debug, Clone, PartialEq, Eq)]
95pub struct TransportFailure {
96 kind: std::io::ErrorKind,
97 code: Option<i32>,
98 message: std::sync::Arc<str>,
99}
100impl TransportFailure {
101 pub fn new(
103 kind: std::io::ErrorKind,
104 code: Option<i32>,
105 message: impl Into<std::sync::Arc<str>>,
106 ) -> Self {
107 Self {
108 kind,
109 code,
110 message: message.into(),
111 }
112 }
113 pub fn kind(&self) -> std::io::ErrorKind {
114 self.kind
115 }
116 pub fn code(&self) -> Option<i32> {
117 self.code
118 }
119 pub fn message(&self) -> &str {
120 &self.message
121 }
122}
123impl From<&std::io::Error> for TransportFailure {
124 fn from(error: &std::io::Error) -> Self {
125 Self::new(error.kind(), error.raw_os_error(), error.to_string())
126 }
127}
128impl fmt::Display for TransportFailure {
129 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
130 f.write_str(&self.message)
131 }
132}
133impl From<std::io::Error> for Error {
134 fn from(_: std::io::Error) -> Self {
135 Self::Protocol("invalid PostgreSQL message")
136 }
137}
138
139#[derive(Debug, Clone, Copy, PartialEq, Eq)]
140pub enum SslMode {
141 Disable,
142 Prefer,
143 Require,
144}
145#[derive(Clone)]
146pub struct Config {
147 pub user: String,
148 pub password: Vec<u8>,
149 pub database: String,
150 pub application_name: String,
151 pub ssl: SslMode,
152 pub channel_binding_required: bool,
154 pub max_buffer: usize,
155 pub max_pending: usize,
156 pub max_scram_iterations: u32,
157 pub connect_deadline: Option<Instant>,
158}
159impl Default for Config {
160 fn default() -> Self {
161 Self {
162 user: "postgres".into(),
163 password: Vec::new(),
164 database: "postgres".into(),
165 application_name: "turnloop".into(),
166 ssl: SslMode::Disable,
167 channel_binding_required: false,
168 max_buffer: 64 * 1024 * 1024,
169 max_pending: 1024,
170 max_scram_iterations: 1_000_000,
171 connect_deadline: None,
172 }
173 }
174}
175#[derive(Debug, Clone, Copy, PartialEq, Eq)]
176pub enum TransactionStatus {
177 Idle,
178 InTransaction,
179 Failed,
180}
181#[derive(Debug, Clone, PartialEq, Eq)]
182pub enum Outcome {
183 Success,
184 ServerError,
186 Aborted(Error),
187}
188#[derive(Debug)]
189pub enum Event<'a> {
190 UpgradeTls,
191 ScramNeeded {
194 plus: bool,
195 },
196 Connected,
197 ParameterStatus {
198 name: &'a str,
199 value: &'a str,
200 },
201 Fields {
202 token: Token,
203 fields: Fields<'a>,
204 },
205 Row {
206 token: Token,
207 row: Row<'a>,
208 },
209 CommandComplete {
210 token: Token,
211 tag: &'a str,
212 row_count: Option<u64>,
213 },
214 Error {
215 token: Option<Token>,
216 error: ServerError<'a>,
217 },
218 Notice(ServerError<'a>),
219 Notification {
220 process_id: i32,
221 channel: &'a str,
222 payload: &'a str,
223 },
224 CopyIn {
225 token: Token,
226 binary: bool,
227 column_formats: &'a [u8],
228 },
229 CopyOut {
230 token: Token,
231 binary: bool,
232 column_formats: &'a [u8],
233 },
234 CopyData {
235 token: Token,
236 data: &'a [u8],
237 },
238 CopyDone {
239 token: Token,
240 },
241 Completed {
242 token: Token,
243 outcome: Outcome,
244 transaction: TransactionStatus,
245 },
246 Closed {
247 reason: Error,
248 },
249}
250#[derive(Debug, Clone, PartialEq, Eq)]
254pub enum OwnedEvent {
255 UpgradeTls,
256 ScramNeeded {
257 plus: bool,
258 },
259 Connected,
260 ParameterStatus {
261 name: String,
262 value: String,
263 },
264 Fields {
265 token: Token,
266 fields: OwnedFields,
267 },
268 Row {
269 token: Token,
270 row: OwnedRow,
271 },
272 CommandComplete {
273 token: Token,
274 tag: String,
275 row_count: Option<u64>,
276 },
277 Error {
278 token: Option<Token>,
279 error: OwnedServerError,
280 },
281 Notice(OwnedServerError),
282 Notification {
283 process_id: i32,
284 channel: String,
285 payload: String,
286 },
287 CopyIn {
288 token: Token,
289 binary: bool,
290 column_formats: Vec<u8>,
291 },
292 CopyOut {
293 token: Token,
294 binary: bool,
295 column_formats: Vec<u8>,
296 },
297 CopyData {
298 token: Token,
299 data: Vec<u8>,
300 },
301 CopyDone {
302 token: Token,
303 },
304 Completed {
305 token: Token,
306 outcome: Outcome,
307 transaction: TransactionStatus,
308 },
309 Closed {
310 reason: Error,
311 },
312}
313impl Event<'_> {
314 pub fn into_owned(self) -> OwnedEvent {
317 match self {
318 Self::UpgradeTls => OwnedEvent::UpgradeTls,
319 Self::ScramNeeded { plus } => OwnedEvent::ScramNeeded { plus },
320 Self::Connected => OwnedEvent::Connected,
321 Self::ParameterStatus { name, value } => OwnedEvent::ParameterStatus {
322 name: name.into(),
323 value: value.into(),
324 },
325 Self::Fields { token, fields } => OwnedEvent::Fields {
326 token,
327 fields: fields.into_owned(),
328 },
329 Self::Row { token, row } => OwnedEvent::Row {
330 token,
331 row: row.into_owned(),
332 },
333 Self::CommandComplete {
334 token,
335 tag,
336 row_count,
337 } => OwnedEvent::CommandComplete {
338 token,
339 tag: tag.into(),
340 row_count,
341 },
342 Self::Error { token, error } => OwnedEvent::Error {
343 token,
344 error: error.into_owned(),
345 },
346 Self::Notice(error) => OwnedEvent::Notice(error.into_owned()),
347 Self::Notification {
348 process_id,
349 channel,
350 payload,
351 } => OwnedEvent::Notification {
352 process_id,
353 channel: channel.into(),
354 payload: payload.into(),
355 },
356 Self::CopyIn {
357 token,
358 binary,
359 column_formats,
360 } => OwnedEvent::CopyIn {
361 token,
362 binary,
363 column_formats: column_formats.into(),
364 },
365 Self::CopyOut {
366 token,
367 binary,
368 column_formats,
369 } => OwnedEvent::CopyOut {
370 token,
371 binary,
372 column_formats: column_formats.into(),
373 },
374 Self::CopyData { token, data } => OwnedEvent::CopyData {
375 token,
376 data: data.into(),
377 },
378 Self::CopyDone { token } => OwnedEvent::CopyDone { token },
379 Self::Completed {
380 token,
381 outcome,
382 transaction,
383 } => OwnedEvent::Completed {
384 token,
385 outcome,
386 transaction,
387 },
388 Self::Closed { reason } => OwnedEvent::Closed { reason },
389 }
390 }
391}
392impl OwnedEvent {
393 pub fn as_event(&self) -> Event<'_> {
395 match self {
396 Self::UpgradeTls => Event::UpgradeTls,
397 Self::ScramNeeded { plus } => Event::ScramNeeded { plus: *plus },
398 Self::Connected => Event::Connected,
399 Self::ParameterStatus { name, value } => Event::ParameterStatus { name, value },
400 Self::Fields { token, fields } => Event::Fields {
401 token: *token,
402 fields: fields.fields(),
403 },
404 Self::Row { token, row } => Event::Row {
405 token: *token,
406 row: row.row(),
407 },
408 Self::CommandComplete {
409 token,
410 tag,
411 row_count,
412 } => Event::CommandComplete {
413 token: *token,
414 tag,
415 row_count: *row_count,
416 },
417 Self::Error { token, error } => Event::Error {
418 token: *token,
419 error: error.server_error(),
420 },
421 Self::Notice(error) => Event::Notice(error.server_error()),
422 Self::Notification {
423 process_id,
424 channel,
425 payload,
426 } => Event::Notification {
427 process_id: *process_id,
428 channel,
429 payload,
430 },
431 Self::CopyIn {
432 token,
433 binary,
434 column_formats,
435 } => Event::CopyIn {
436 token: *token,
437 binary: *binary,
438 column_formats,
439 },
440 Self::CopyOut {
441 token,
442 binary,
443 column_formats,
444 } => Event::CopyOut {
445 token: *token,
446 binary: *binary,
447 column_formats,
448 },
449 Self::CopyData { token, data } => Event::CopyData {
450 token: *token,
451 data,
452 },
453 Self::CopyDone { token } => Event::CopyDone { token: *token },
454 Self::Completed {
455 token,
456 outcome,
457 transaction,
458 } => Event::Completed {
459 token: *token,
460 outcome: outcome.clone(),
461 transaction: *transaction,
462 },
463 Self::Closed { reason } => Event::Closed {
464 reason: reason.clone(),
465 },
466 }
467 }
468}
469#[derive(Debug, Clone, Copy, PartialEq, Eq)]
470enum State {
471 Ssl,
472 Tls,
473 Auth,
474 Scram(bool),
475 Ready,
476 Closing,
477 Closed,
478}
479#[derive(Debug)]
480struct Pending {
481 token: Token,
482 deadline: Option<Instant>,
483 failed: bool,
484 extended: bool,
485 parse: Option<usize>,
486}
487struct Statement {
488 name: String,
489 sql: String,
490 oids: Vec<u32>,
491 parsed: bool,
492}
493#[derive(Clone, Copy, Debug)]
495pub struct Parameter<'a> {
496 pub value: Option<&'a [u8]>,
497 pub format: i16,
498}
499
500#[derive(Clone, Copy, Debug)]
502pub struct ExtendedQuery<'a> {
503 pub name: &'a str,
504 pub sql: &'a str,
505 pub oids: &'a [u32],
506 pub params: &'a [Parameter<'a>],
507 pub result_formats: &'a [i16],
508}
509
510pub struct Connection {
511 config: Config,
512 state: State,
513 input: Vec<u8>,
514 input_at: usize,
515 output: BytesMut,
516 output_at: usize,
517 pending: VecDeque<Pending>,
518 statements: Vec<Statement>,
519 scram: Option<ScramSha256>,
520 auth_ok: bool,
521 tls: bool,
522 binding_available: bool,
523 scram_plus: bool,
524 copy_in: bool,
525 transaction: TransactionStatus,
526 key: Option<(i32, i32)>,
527 reason: Error,
528}
529impl Connection {
530 pub fn new(config: Config) -> Result<Self> {
544 if config.max_buffer < 1024
545 || config.max_buffer > i32::MAX as usize
546 || config.max_pending == 0
547 {
548 return Err(Error::Limit);
549 }
550 if config.user.contains('\0')
551 || config.database.contains('\0')
552 || config.application_name.contains('\0')
553 {
554 return Err(Error::State("NUL in startup parameter"));
555 }
556 if config.channel_binding_required && config.ssl == SslMode::Disable {
557 return Err(Error::State("channel binding requires TLS"));
558 }
559 let mut this = Self {
560 config,
561 state: State::Auth,
562 input: Vec::with_capacity(8192),
563 input_at: 0,
564 output: BytesMut::with_capacity(8192),
565 output_at: 0,
566 pending: VecDeque::with_capacity(16),
567 statements: Vec::new(),
568 scram: None,
569 auth_ok: false,
570 tls: false,
571 binding_available: false,
572 scram_plus: false,
573 copy_in: false,
574 transaction: TransactionStatus::Idle,
575 key: None,
576 reason: Error::Transport(None),
577 };
578 if this.config.ssl == SslMode::Disable {
579 this.startup()?;
580 } else {
581 this.state = State::Ssl;
582 frontend::ssl_request(&mut this.output);
583 }
584 Ok(this)
585 }
586 fn startup(&mut self) -> Result<()> {
587 frontend::startup_message(
588 [
589 ("user", self.config.user.as_str()),
590 ("database", self.config.database.as_str()),
591 ("application_name", self.config.application_name.as_str()),
592 ("client_encoding", "UTF8"),
593 ("DateStyle", "ISO"),
594 ],
595 &mut self.output,
596 )?;
597 self.state = State::Auth;
598 Ok(())
599 }
600 pub fn config(&self) -> &Config {
603 &self.config
604 }
605 pub fn output(&self) -> &[u8] {
606 &self.output[self.output_at..]
607 }
608 pub fn consume_output(&mut self, n: usize) -> Result<()> {
609 if n > self.output().len() {
610 return Err(Error::State("invalid output acknowledgement"));
611 }
612 self.output_at += n;
613 if self.output_at == self.output.len() {
614 self.output.clear();
615 self.output_at = 0;
616 }
617 Ok(())
618 }
619 pub fn receive(&mut self, bytes: &[u8]) -> Result<()> {
620 if matches!(self.state, State::Tls | State::Closing | State::Closed) {
621 return Err(Error::State("connection cannot receive plaintext now"));
622 }
623 let remaining = self.input.len() - self.input_at;
624 if bytes.len() > self.config.max_buffer.saturating_sub(remaining) {
625 self.abort(Error::Limit);
626 return Err(Error::Limit);
627 }
628 if self.input_at != 0 {
629 self.input.copy_within(self.input_at.., 0);
630 self.input.truncate(remaining);
631 self.input_at = 0;
632 }
633 self.input.extend_from_slice(bytes);
634 Ok(())
635 }
636 pub fn tls_established(&mut self) -> Result<()> {
638 self.tls_established_with_channel_binding(false)
639 }
640 pub fn tls_established_with_channel_binding(&mut self, available: bool) -> Result<()> {
643 if self.state != State::Tls || !self.output().is_empty() {
644 return Err(Error::State("TLS transition not ready"));
645 }
646 if self.config.channel_binding_required && !available {
647 return Err(Error::State(
648 "channel binding required but certificate binding is unavailable",
649 ));
650 }
651 self.tls = true;
652 self.binding_available = available;
653 self.startup()
654 }
655 pub fn start_scram(&mut self, scram: ScramSha256) -> Result<()> {
656 let State::Scram(plus) = self.state else {
657 return Err(Error::State("SCRAM was not requested"));
658 };
659 if plus != scram.message().starts_with(b"p=tls-server-end-point,") {
660 return Err(Error::State("SCRAM channel binding mismatch"));
661 }
662 frontend::sasl_initial_response(
663 if plus {
664 "SCRAM-SHA-256-PLUS"
665 } else {
666 "SCRAM-SHA-256"
667 },
668 scram.message(),
669 &mut self.output,
670 )?;
671 self.scram = Some(scram);
672 self.state = State::Auth;
673 Ok(())
674 }
675 fn accept(&self, token: Token) -> Result<()> {
676 if self.state != State::Ready || self.copy_in {
677 return Err(Error::State("Client is not queryable"));
678 }
679 if self.pending.len() >= self.config.max_pending {
680 return Err(Error::Limit);
681 }
682 if self.pending.iter().any(|p| p.token == token) {
683 return Err(Error::State("duplicate operation token"));
684 }
685 Ok(())
686 }
687 fn finish_command(
688 &mut self,
689 token: Token,
690 deadline: Option<Instant>,
691 parse: Option<usize>,
692 before: usize,
693 result: Result<()>,
694 extended: bool,
695 ) -> Result<()> {
696 if let Err(e) = result {
697 self.output.truncate(before);
698 return Err(e);
699 }
700 if self.output.len() > self.config.max_buffer {
701 self.output.truncate(before);
702 return Err(Error::Limit);
703 }
704 self.pending.push_back(Pending {
705 token,
706 deadline,
707 failed: false,
708 extended,
709 parse,
710 });
711 Ok(())
712 }
713 pub fn query(&mut self, token: Token, sql: &str, deadline: Option<Instant>) -> Result<()> {
714 self.accept(token)?;
715 if sql.len().saturating_add(6) > self.config.max_buffer.saturating_sub(self.output.len()) {
716 return Err(Error::Limit);
717 }
718 let before = self.output.len();
719 let result = frontend::query(sql, &mut self.output).map_err(Error::from);
720 self.finish_command(token, deadline, None, before, result, false)
721 }
722 pub fn execute(
724 &mut self,
725 token: Token,
726 query: ExtendedQuery<'_>,
727 deadline: Option<Instant>,
728 ) -> Result<()> {
729 let ExtendedQuery {
730 name,
731 sql,
732 oids,
733 params,
734 result_formats,
735 } = query;
736 self.accept(token)?;
737 let size = params.iter().fold(
738 64usize
739 .saturating_add(name.len().saturating_mul(2))
740 .saturating_add(sql.len())
741 .saturating_add(oids.len().saturating_mul(4))
742 .saturating_add(result_formats.len().saturating_mul(2)),
743 |n, p| {
744 n.saturating_add(6)
745 .saturating_add(p.value.map_or(0, <[u8]>::len))
746 },
747 );
748 if size > self.config.max_buffer.saturating_sub(self.output.len()) {
749 return Err(Error::Limit);
750 }
751
752 if params.iter().any(|p| !matches!(p.format, 0 | 1))
753 || result_formats.iter().any(|f| !matches!(f, 0 | 1))
754 {
755 return Err(Error::State("invalid format"));
756 }
757 let index = if name.is_empty() {
758 None
759 } else {
760 self.statements.iter().position(|s| s.name == name)
761 };
762 if let Some(i) = index {
763 let s = &self.statements[i];
764 if s.sql != sql || s.oids != oids {
765 return Err(Error::State(
766 "Prepared statements must be unique - a different statement was used for this name",
767 ));
768 }
769 }
770 if index.is_some_and(|i| !self.statements[i].parsed) {
773 return Err(Error::State("named statement parse still pending"));
774 }
775 let before = self.output.len();
776 let result = (|| {
777 if index.is_none() {
778 frontend::parse(name, sql, oids.iter().copied(), &mut self.output)?;
779 }
780 frontend::bind(
781 "",
782 name,
783 params.iter().map(|p| p.format),
784 params.iter(),
785 |p, out| {
786 if let Some(value) = p.value {
787 out.extend_from_slice(value);
788 Ok(IsNull::No)
789 } else {
790 Ok(IsNull::Yes)
791 }
792 },
793 result_formats.iter().copied(),
794 &mut self.output,
795 )
796 .map_err(|_| Error::Protocol("invalid Bind message"))?;
797 frontend::describe(b'P', "", &mut self.output)?;
798 frontend::execute("", 0, &mut self.output)?;
799 frontend::sync(&mut self.output);
800 Ok(())
801 })();
802 let new_index = if result.is_ok()
803 && self.output.len() <= self.config.max_buffer
804 && index.is_none()
805 && !name.is_empty()
806 {
807 let i = self.statements.len();
808 self.statements.push(Statement {
809 name: name.into(),
810 sql: sql.into(),
811 oids: oids.into(),
812 parsed: false,
813 });
814 Some(i)
815 } else {
816 None
817 };
818 self.finish_command(token, deadline, new_index, before, result, true)
819 }
820 pub fn copy_data(&mut self, bytes: &[u8]) -> Result<()> {
821 if !self.copy_in {
822 return Err(Error::State("COPY IN is not active"));
823 }
824 if bytes.len().saturating_add(5) > self.config.max_buffer.saturating_sub(self.output.len())
825 {
826 return Err(Error::Limit);
827 }
828 frontend::CopyData::new(bytes)?.write(&mut self.output);
829 Ok(())
830 }
831 pub fn copy_finish(&mut self, error: Option<&str>) -> Result<()> {
832 if !self.copy_in {
833 return Err(Error::State("COPY IN is not active"));
834 }
835 let before = self.output.len();
836 let result = if let Some(message) = error {
837 frontend::copy_fail(message, &mut self.output)
838 } else {
839 frontend::copy_done(&mut self.output);
840 Ok(())
841 };
842 if result.is_ok() && self.pending.front().is_some_and(|p| p.extended) {
845 frontend::sync(&mut self.output);
846 }
847 if result.is_err() || self.output.len() > self.config.max_buffer {
848 self.output.truncate(before);
849 return Err(Error::Limit);
850 }
851 self.copy_in = false;
852 Ok(())
853 }
854 pub fn cancel_request(&self) -> Option<[u8; 16]> {
856 self.key.map(|(pid, key)| {
857 let mut b = [0; 16];
858 b[..4].copy_from_slice(&16u32.to_be_bytes());
859 b[4..8].copy_from_slice(&80877102u32.to_be_bytes());
860 b[8..12].copy_from_slice(&pid.to_be_bytes());
861 b[12..].copy_from_slice(&key.to_be_bytes());
862 b
863 })
864 }
865 pub fn transaction_status(&self) -> TransactionStatus {
866 self.transaction
867 }
868 pub fn is_ready(&self) -> bool {
869 self.state == State::Ready
870 }
871 pub fn pending_count(&self) -> usize {
872 self.pending.len()
873 }
874 pub fn next_timeout(&self) -> Option<Instant> {
875 if matches!(self.state, State::Closing | State::Closed) {
876 return None;
877 }
878 self.pending
879 .iter()
880 .filter_map(|p| p.deadline)
881 .chain(if self.state != State::Ready {
882 self.config.connect_deadline
883 } else {
884 None
885 })
886 .min()
887 }
888 pub fn handle_timeout(&mut self, now: Instant) {
889 if self.next_timeout().is_some_and(|t| t <= now) {
890 self.abort(Error::Timeout);
891 }
892 }
893 pub fn abort(&mut self, reason: Error) {
896 if matches!(self.state, State::Closing | State::Closed) {
897 return;
898 }
899 self.reason = reason;
900 self.state = State::Closing;
901 self.output.clear();
902 self.output_at = 0;
903 self.copy_in = false;
904 }
905 pub fn end(&mut self) -> Result<()> {
906 if !self.pending.is_empty() || self.state != State::Ready {
907 return Err(Error::State("drain queries before end"));
908 }
909 frontend::terminate(&mut self.output);
910 self.state = State::Closing;
911 self.reason = Error::Cancelled;
912 Ok(())
913 }
914 fn token(&self) -> Result<Token> {
915 self.pending
916 .front()
917 .map(|p| p.token)
918 .ok_or(Error::Protocol("unsolicited query response"))
919 }
920 pub fn next_event(&mut self) -> Result<Option<Event<'_>>> {
930 if self.state == State::Closing {
931 if let Some(p) = self.pending.pop_front() {
932 return Ok(Some(Event::Completed {
933 token: p.token,
934 outcome: Outcome::Aborted(self.reason.clone()),
935 transaction: self.transaction,
936 }));
937 }
938 if !self.output().is_empty() {
939 return Ok(None);
940 }
941 self.state = State::Closed;
942 return Ok(Some(Event::Closed {
943 reason: self.reason.clone(),
944 }));
945 }
946 if let State::Scram(_) = self.state {
947 return Err(Error::State(
950 "SCRAM authentication pending: answer ScramNeeded with start_scram",
951 ));
952 }
953 if matches!(self.state, State::Closed | State::Tls) {
954 return Ok(None);
955 }
956 if self.state == State::Ssl {
957 let Some(&reply) = self.input.get(self.input_at) else {
958 return Ok(None);
959 };
960 self.input_at += 1;
961 match reply {
962 b'S' => {
963 if self.input.len() != self.input_at {
964 return Err(Error::Protocol("plaintext after TLS acceptance"));
965 }
966 self.state = State::Tls;
967 return Ok(Some(Event::UpgradeTls));
968 }
969 b'N' if self.config.ssl == SslMode::Prefer => {
970 self.startup()?;
971 }
972 b'N' => {
973 return Err(Error::Protocol(
974 "The server does not support SSL connections",
975 ));
976 }
977 _ => return Err(Error::Protocol("invalid SSLRequest response")),
978 }
979 }
980 loop {
981 let available = &self.input[self.input_at..];
982 let Some(header) = Header::parse(available)? else {
983 return Ok(None);
984 };
985 if header.len() < 4 {
986 return Err(Error::Protocol("invalid message length"));
987 }
988 let length = header.len() as usize + 1;
989 if length > self.config.max_buffer {
990 return Err(Error::Limit);
991 }
992 if available.len() < length {
993 return Ok(None);
994 }
995 let start = self.input_at + 5;
996 self.input_at += length;
997 let body = &self.input[start..self.input_at];
998 let mut c = Cursor(body);
999 match header.tag() {
1000 b'R' if self.state == State::Auth => match c.u32()? {
1001 0 => {
1002 c.end()?;
1003 if self.scram.is_some() {
1004 return Err(Error::Protocol("SCRAM final verification missing"));
1005 }
1006 if self.config.channel_binding_required && !self.scram_plus {
1007 return Err(Error::Protocol(
1008 "channel binding required but SCRAM-PLUS was not authenticated",
1009 ));
1010 }
1011 self.auth_ok = true;
1012 }
1013 3 => {
1014 c.end()?;
1015 if self.config.channel_binding_required {
1016 return Err(Error::Protocol("server did not offer channel binding"));
1017 }
1018 frontend::password_message(&self.config.password, &mut self.output)?;
1019 }
1020 5 => {
1021 let salt = c.take(4)?.try_into().unwrap();
1022 c.end()?;
1023 if self.config.channel_binding_required {
1024 return Err(Error::Protocol("server did not offer channel binding"));
1025 }
1026 let hash =
1027 md5_hash(self.config.user.as_bytes(), &self.config.password, salt);
1028 frontend::password_message(hash.as_bytes(), &mut self.output)?;
1029 }
1030 10 => {
1031 let mut plain = false;
1032 let mut plus = false;
1033 loop {
1034 match c.cstr()? {
1035 "" => break,
1036 "SCRAM-SHA-256" => plain = true,
1037 "SCRAM-SHA-256-PLUS" => plus = true,
1038 _ => {}
1039 }
1040 }
1041 c.end()?;
1042 let plus = self.tls && self.binding_available && plus;
1043 if self.config.channel_binding_required && !plus {
1044 return Err(Error::Protocol(
1045 "channel binding required but server did not offer SCRAM-SHA-256-PLUS",
1046 ));
1047 }
1048 if !plus && !plain {
1049 return Err(Error::Protocol("unsupported SASL mechanisms"));
1050 }
1051 self.scram_plus = plus;
1052 self.state = State::Scram(plus);
1053 return Ok(Some(Event::ScramNeeded { plus }));
1054 }
1055 11 => {
1056 let iterations = std::str::from_utf8(c.0)
1057 .ok()
1058 .and_then(|s| s.split(',').find_map(|p| p.strip_prefix("i=")))
1059 .and_then(|s| s.parse::<u32>().ok())
1060 .ok_or(Error::Protocol("invalid SCRAM iterations"))?;
1061 if iterations == 0 || iterations > self.config.max_scram_iterations {
1062 return Err(Error::Limit);
1063 }
1064 let scram = self
1065 .scram
1066 .as_mut()
1067 .ok_or(Error::Protocol("unexpected SASL continuation"))?;
1068 scram.update(c.0)?;
1069 frontend::sasl_response(scram.message(), &mut self.output)?;
1070 }
1071 12 => {
1072 let mut scram = self
1073 .scram
1074 .take()
1075 .ok_or(Error::Protocol("unexpected SASL final"))?;
1076 scram.finish(c.0)?;
1077 }
1078 _ => return Err(Error::Protocol("unsupported authentication method")),
1079 },
1080 b'S' => {
1081 let name = c.cstr()?;
1082 let value = c.cstr()?;
1083 c.end()?;
1084 return Ok(Some(Event::ParameterStatus { name, value }));
1085 }
1086 b'K' => {
1087 self.key = Some((c.i32()?, c.i32()?));
1088 c.end()?;
1089 }
1090 b'Z' => {
1091 self.transaction = match c.u8()? {
1092 b'I' => TransactionStatus::Idle,
1093 b'T' => TransactionStatus::InTransaction,
1094 b'E' => TransactionStatus::Failed,
1095 _ => return Err(Error::Protocol("invalid transaction status")),
1096 };
1097 c.end()?;
1098 self.copy_in = false;
1099 if self.state == State::Auth {
1100 if !self.auth_ok {
1101 return Err(Error::Protocol("Ready before authentication"));
1102 }
1103 self.state = State::Ready;
1104 return Ok(Some(Event::Connected));
1105 }
1106 let p = self
1107 .pending
1108 .pop_front()
1109 .ok_or(Error::Protocol("unsolicited ReadyForQuery"))?;
1110 if let Some(i) = p.parse
1112 && !self.statements[i].parsed
1113 {
1114 self.statements[i].name.clear();
1115 }
1116 return Ok(Some(Event::Completed {
1117 token: p.token,
1118 outcome: if p.failed {
1119 Outcome::ServerError
1120 } else {
1121 Outcome::Success
1122 },
1123 transaction: self.transaction,
1124 }));
1125 }
1126 b'T' => {
1127 return Ok(Some(Event::Fields {
1128 token: self.token()?,
1129 fields: Fields::parse(body)?,
1130 }));
1131 }
1132 b'D' => {
1133 return Ok(Some(Event::Row {
1134 token: self.token()?,
1135 row: Row::parse(body)?,
1136 }));
1137 }
1138 b'C' => {
1139 let tag = c.cstr()?;
1140 c.end()?;
1141 let row_count = tag.rsplit(' ').next().and_then(|s| s.parse().ok());
1142 return Ok(Some(Event::CommandComplete {
1143 token: self.token()?,
1144 tag,
1145 row_count,
1146 }));
1147 }
1148 b'I' => {
1149 c.end()?;
1150 return Ok(Some(Event::CommandComplete {
1151 token: self.token()?,
1152 tag: "",
1153 row_count: None,
1154 }));
1155 }
1156 b'E' => {
1157 let error = ServerError::parse(body)?;
1158 let token = self.pending.front_mut().map(|p| {
1159 p.failed = true;
1160 p.token
1161 });
1162 if token.is_none()
1163 || matches!(
1164 error.get(b'V').or(error.severity()),
1165 Some("FATAL" | "PANIC")
1166 )
1167 {
1168 self.state = State::Closing;
1169 self.reason = Error::ConnectionAborted(ConnectionFailure::new(error));
1170 self.output.clear();
1171 self.output_at = 0;
1172 self.copy_in = false;
1173 return Err(self.reason.clone());
1176 }
1177 return Ok(Some(Event::Error { token, error }));
1178 }
1179 b'N' => return Ok(Some(Event::Notice(ServerError::parse(body)?))),
1180 b'A' => {
1181 let process_id = c.i32()?;
1182 let channel = c.cstr()?;
1183 let payload = c.cstr()?;
1184 c.end()?;
1185 return Ok(Some(Event::Notification {
1186 process_id,
1187 channel,
1188 payload,
1189 }));
1190 }
1191 b'1' => {
1192 c.end()?;
1193 let p = self
1194 .pending
1195 .front_mut()
1196 .ok_or(Error::Protocol("unsolicited ParseComplete"))?;
1197 if let Some(i) = p.parse {
1198 self.statements[i].parsed = true;
1199 }
1200 }
1201 b'2' | b'3' | b'n' => {
1202 c.end()?;
1203 self.token()?;
1204 }
1205 b'G' | b'H' => {
1206 let binary = match c.u8()? {
1207 0 => false,
1208 1 => true,
1209 _ => return Err(Error::Protocol("invalid COPY format")),
1210 };
1211 let count = c.u16()? as usize;
1212 let column_formats = c.take(count * 2)?;
1213 c.end()?;
1214 let token = self.token()?;
1215 if header.tag() == b'G' {
1216 if self.pending.len() != 1 {
1217 return Err(Error::Protocol("COPY IN requires an exclusive query"));
1218 }
1219 self.copy_in = true;
1220 return Ok(Some(Event::CopyIn {
1221 token,
1222 binary,
1223 column_formats,
1224 }));
1225 }
1226 return Ok(Some(Event::CopyOut {
1227 token,
1228 binary,
1229 column_formats,
1230 }));
1231 }
1232 b'd' => {
1233 return Ok(Some(Event::CopyData {
1234 token: self.token()?,
1235 data: body,
1236 }));
1237 }
1238 b'c' => {
1239 c.end()?;
1240 return Ok(Some(Event::CopyDone {
1241 token: self.token()?,
1242 }));
1243 }
1244 _ => return Err(Error::Protocol("unexpected backend message")),
1245 }
1246 }
1247 }
1248}
1249
1250#[cfg(feature = "turnloop")]
1251pub mod asynchronous;