Skip to main content

pgwire/
pg_protocol.rs

1// Copyright 2022 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::any::Any;
16use std::collections::HashMap;
17use std::io::ErrorKind;
18use std::panic::AssertUnwindSafe;
19use std::pin::Pin;
20use std::str::Utf8Error;
21use std::sync::{Arc, LazyLock, Weak};
22use std::time::{Duration, Instant};
23use std::{io, str};
24
25use bytes::{Bytes, BytesMut};
26use futures::FutureExt;
27use futures::stream::StreamExt;
28use itertools::Itertools;
29use openssl::ssl::{SslAcceptor, SslContext, SslContextRef, SslMethod};
30use risingwave_common::types::DataType;
31use risingwave_common::util::deployment::Deployment;
32use risingwave_common::util::env_var::env_var_is_true;
33use risingwave_common::util::panic::FutureCatchUnwindExt;
34use risingwave_common::util::query_log::*;
35use risingwave_common::{PG_VERSION, SERVER_ENCODING, STANDARD_CONFORMING_STRINGS};
36use risingwave_sqlparser::ast::{SqlOptionRedactionRef, Statement};
37use risingwave_sqlparser::parser::Parser;
38use thiserror_ext::AsReport;
39use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt};
40use tokio::sync::Mutex;
41use tokio_openssl::SslStream;
42use tracing::Instrument;
43
44use crate::error::{PsqlError, PsqlResult};
45use crate::error_or_notice::Severity;
46use crate::memory_manager::{MessageMemoryGuard, MessageMemoryManagerRef};
47use crate::net::AddressRef;
48use crate::pg_extended::ResultCache;
49use crate::pg_message::{
50    BeCommandCompleteMessage, BeMessage, BeParameterStatusMessage, FeBindMessage, FeCancelMessage,
51    FeCloseMessage, FeDescribeMessage, FeExecuteMessage, FeMessage, FeMessageHeader,
52    FeParseMessage, FePasswordMessage, FeStartupMessage, ServerThrottleReason, TransactionStatus,
53};
54use crate::pg_server::{Session, SessionManager, UserAuthenticator};
55use crate::types::Format;
56
57/// Truncates query log if it's longer than `RW_QUERY_LOG_TRUNCATE_LEN`, to avoid log file being too
58/// large.
59static RW_QUERY_LOG_TRUNCATE_LEN: LazyLock<usize> =
60    LazyLock::new(|| match std::env::var("RW_QUERY_LOG_TRUNCATE_LEN") {
61        Ok(len) if len.parse::<usize>().is_ok() => len.parse::<usize>().unwrap(),
62        _ => 65536,
63    });
64
65tokio::task_local! {
66    /// The current session. Concrete type is erased for different session implementations.
67    pub static CURRENT_SESSION: Weak<dyn Any + Send + Sync>
68}
69
70/// The state machine for each psql connection.
71/// Read pg messages from tcp stream and write results back.
72pub struct PgProtocol<S, SM>
73where
74    SM: SessionManager,
75{
76    /// Used for write/read pg messages.
77    stream: PgStream<S>,
78    /// Current states of pg connection.
79    state: PgProtocolState,
80    /// Whether the connection is terminated.
81    is_terminate: bool,
82
83    session_mgr: Arc<SM>,
84    session: Option<Arc<SM::Session>>,
85    /// `application_name` from the startup message, reported back to the client once
86    /// authentication finishes. Kept here because the startup message is gone by the
87    /// time a password arrives.
88    application_name: Option<String>,
89
90    result_cache: HashMap<String, ResultCache<<SM::Session as Session>::ValuesStream>>,
91    unnamed_prepare_statement:
92        Option<PreparedStatementData<<SM::Session as Session>::PreparedStatement>>,
93    prepare_statement_store:
94        HashMap<String, PreparedStatementData<<SM::Session as Session>::PreparedStatement>>,
95    unnamed_portal: Option<PortalData<<SM::Session as Session>::Portal>>,
96    portal_store: HashMap<String, PortalData<<SM::Session as Session>::Portal>>,
97    // Used to store the dependency of portal and prepare statement.
98    // When we close a prepare statement, we need to close all the portals that depend on it.
99    statement_portal_dependency: HashMap<String, Vec<String>>,
100
101    // Used for ssl connection.
102    // If None, not expected to build ssl connection (panic).
103    tls_context: Option<SslContext>,
104
105    // TLS configuration including SSL enforcement setting
106    tls_config: Option<TlsConfig>,
107
108    // Used in extended query protocol. When encounter error in extended query, we need to ignore
109    // the following message util sync message.
110    ignore_util_sync: bool,
111
112    // Client Address
113    peer_addr: AddressRef,
114
115    sql_option_redaction: Option<SqlOptionRedactionRef>,
116    message_memory_manager: MessageMemoryManagerRef,
117}
118
119/// Configures TLS encryption for connections.
120#[derive(Debug, Clone)]
121pub struct TlsConfig {
122    /// The path to the TLS certificate.
123    pub cert: String,
124    /// The path to the TLS key.
125    pub key: String,
126    /// Whether to enforce SSL connections (reject non-SSL clients).
127    pub enforce_ssl: bool,
128}
129
130impl TlsConfig {
131    pub fn new_default() -> anyhow::Result<Option<Self>> {
132        let cert = std::env::var("RW_SSL_CERT").ok();
133        let key = std::env::var("RW_SSL_KEY").ok();
134        let enforce_ssl = env_var_is_true("RW_SSL_ENFORCE");
135
136        if cert.is_some() ^ key.is_some() {
137            return Err(anyhow::anyhow!(
138                "RW_SSL_CERT and RW_SSL_KEY must be set together"
139            ));
140        }
141
142        if enforce_ssl && cert.is_none() {
143            return Err(anyhow::anyhow!(
144                "RW_SSL_ENFORCE requires RW_SSL_CERT and RW_SSL_KEY to be set"
145            ));
146        }
147
148        let (Some(cert), Some(key)) = (cert, key) else {
149            return Ok(None);
150        };
151
152        tracing::info!(
153            "RW_SSL_CERT={}, RW_SSL_KEY={}, RW_SSL_ENFORCE={}",
154            cert,
155            key,
156            enforce_ssl
157        );
158        Ok(Some(Self {
159            cert,
160            key,
161            enforce_ssl,
162        }))
163    }
164}
165
166impl<S, SM> Drop for PgProtocol<S, SM>
167where
168    SM: SessionManager,
169{
170    fn drop(&mut self) {
171        if let Some(session) = &self.session {
172            // Clear the session in session manager.
173            self.session_mgr.end_session(session);
174        }
175    }
176}
177
178/// States flow happened from top to down.
179#[derive(PartialEq, Eq)]
180enum PgProtocolState {
181    Startup,
182    Authentication,
183    Regular,
184}
185
186#[derive(Clone)]
187struct PreparedStatementData<S> {
188    statement: S,
189    sql: Arc<str>,
190}
191
192#[derive(Clone)]
193struct PortalData<P> {
194    portal: P,
195    sql: Arc<str>,
196}
197
198/// Truncate 0 from C string in Bytes and stringify it (returns slice, no allocations).
199///
200/// PG protocol strings are always C strings.
201pub fn cstr_to_str(b: &Bytes) -> Result<&str, Utf8Error> {
202    let without_null = if b.last() == Some(&0) {
203        &b[..b.len() - 1]
204    } else {
205        &b[..]
206    };
207    std::str::from_utf8(without_null)
208}
209
210fn get_redacted_and_truncated_sql(
211    sql: &str,
212    sql_option_redaction: Option<SqlOptionRedactionRef>,
213) -> String {
214    let redacted_sql = if let Some(redaction) = sql_option_redaction
215        && !redaction.keywords.is_empty()
216    {
217        redact_sql(sql, redaction)
218    } else {
219        sql.to_owned()
220    };
221    let truncated = truncated_fmt::TruncatedFmt(&redacted_sql, *RW_QUERY_LOG_TRUNCATE_LEN);
222    truncated.to_string()
223}
224
225/// Record `sql` in the current tracing span.
226fn record_sql_in_span(
227    sql: &str,
228    sql_option_redaction: Option<SqlOptionRedactionRef>,
229    span: &mut tracing::Span,
230) {
231    let redacted_and_truncated_sql = get_redacted_and_truncated_sql(sql, sql_option_redaction);
232    span.record("sql", tracing::field::display(&redacted_and_truncated_sql));
233}
234
235fn record_user_in_span(user: &str, span: &mut tracing::Span) {
236    span.record("user", tracing::field::display(user));
237}
238
239/// Redacts sensitive SQL fields. Data in DML is not redacted.
240fn redact_sql(sql: &str, redaction: SqlOptionRedactionRef) -> String {
241    match Parser::parse_sql(sql) {
242        Ok(sqls) => sqls
243            .into_iter()
244            .map(|sql| sql.to_redacted_string(redaction.clone()))
245            .join(";"),
246        Err(_) => sql.to_owned(),
247    }
248}
249
250#[derive(Clone)]
251pub struct ConnectionContext {
252    pub tls_config: Option<TlsConfig>,
253    pub sql_option_redaction: Option<SqlOptionRedactionRef>,
254    pub message_memory_manager: MessageMemoryManagerRef,
255    pub stream_flush_threshold_bytes: usize,
256}
257
258impl<S, SM> PgProtocol<S, SM>
259where
260    S: PgByteStream,
261    SM: SessionManager,
262{
263    pub fn new(
264        stream: S,
265        session_mgr: Arc<SM>,
266        peer_addr: AddressRef,
267        context: ConnectionContext,
268    ) -> Self {
269        let ConnectionContext {
270            tls_config,
271            sql_option_redaction,
272            message_memory_manager,
273            stream_flush_threshold_bytes,
274        } = context;
275        Self {
276            stream: PgStream::new(stream, stream_flush_threshold_bytes),
277            is_terminate: false,
278            state: PgProtocolState::Startup,
279            session_mgr,
280            session: None,
281            application_name: None,
282            tls_context: tls_config
283                .as_ref()
284                .and_then(|e| build_ssl_ctx_from_config(e).ok()),
285            tls_config,
286            result_cache: Default::default(),
287            unnamed_prepare_statement: Default::default(),
288            prepare_statement_store: Default::default(),
289            unnamed_portal: Default::default(),
290            portal_store: Default::default(),
291            statement_portal_dependency: Default::default(),
292            ignore_util_sync: false,
293            peer_addr,
294            sql_option_redaction,
295            message_memory_manager,
296        }
297    }
298
299    /// Run the protocol to serve the connection.
300    pub async fn run(&mut self) {
301        let mut notice_fut = None;
302
303        loop {
304            // Once a session is present, create a future to subscribe and send notices asynchronously.
305            if notice_fut.is_none()
306                && let Some(session) = self.session.clone()
307            {
308                let mut stream = self.stream.clone();
309                notice_fut = Some(Box::pin(async move {
310                    loop {
311                        let notice = session.next_notice().await;
312                        if let Err(e) = stream.write(BeMessage::NoticeResponse(&notice)).await {
313                            tracing::error!(error = %e.as_report(), notice, "failed to send notice");
314                        }
315                    }
316                }));
317            }
318
319            // Read and process messages.
320            let process = std::pin::pin!(async {
321                let (msg, _memory_guard) = match self.read_message().await {
322                    Ok(msg) => msg,
323                    Err(e) => {
324                        tracing::error!(error = %e.as_report(), "error when reading message");
325                        return true; // terminate the connection
326                    }
327                };
328                tracing::trace!(?msg, "received message");
329                self.process(msg).await
330            });
331
332            let terminated = if let Some(notice_fut) = notice_fut.as_mut() {
333                tokio::select! {
334                    _ = notice_fut => unreachable!(),
335                    terminated = process => terminated,
336                }
337            } else {
338                process.await
339            };
340
341            if terminated {
342                break;
343            }
344        }
345    }
346
347    /// Processes one message. Returns true if the connection is terminated.
348    pub async fn process(&mut self, msg: FeMessage) -> bool {
349        self.do_process(msg).await.is_none() || self.is_terminate
350    }
351
352    /// The root tracing span for processing a message. The target of the span is
353    /// [`PGWIRE_ROOT_SPAN_TARGET`].
354    ///
355    /// This is used to provide context for the (slow) query logs and traces.
356    ///
357    /// The span is only effective if there's a current session and the message is
358    /// query-related. Otherwise, `Span::none()` is returned.
359    fn root_span_for_msg(&self, msg: &FeMessage) -> tracing::Span {
360        let Some(session_id) = self.session.as_ref().map(|s| s.id().0) else {
361            return tracing::Span::none();
362        };
363
364        let mode = match msg {
365            FeMessage::Query(_) => "simple query",
366            FeMessage::Parse(_) => "extended query parse",
367            FeMessage::Execute(_) => "extended query execute",
368            _ => return tracing::Span::none(),
369        };
370
371        let mut span = tracing::info_span!(
372            target: PGWIRE_ROOT_SPAN_TARGET,
373            "handle_query",
374            mode,
375            session_id,
376            sql = tracing::field::Empty,
377            user = tracing::field::Empty,
378        );
379        match msg {
380            FeMessage::Execute(execute_msg) => {
381                if let Ok(portal_name) = cstr_to_str(&execute_msg.portal_name)
382                    && let Ok(sql) = self.get_portal_sql(portal_name)
383                {
384                    record_sql_in_span(&sql, self.sql_option_redaction.clone(), &mut span);
385                }
386            }
387            _ => {
388                if let Ok(sql) = msg.get_sql()
389                    && let Some(sql) = sql
390                {
391                    record_sql_in_span(sql, self.sql_option_redaction.clone(), &mut span);
392                }
393            }
394        }
395        if let Some(current_session) = self.session.as_ref() {
396            record_user_in_span(&current_session.user(), &mut span);
397        }
398        span
399    }
400
401    /// Return type `Option<()>` is essentially a bool, but allows `?` for early return.
402    /// - `None` means to terminate the current connection
403    /// - `Some(())` means to continue processing the next message
404    async fn do_process(&mut self, msg: FeMessage) -> Option<()> {
405        let span = self.root_span_for_msg(&msg);
406        let weak_session = self
407            .session
408            .as_ref()
409            .map(|s| Arc::downgrade(s) as Weak<dyn Any + Send + Sync>);
410
411        // Processing the message itself.
412        //
413        // Note: pin the future to avoid stack overflow as we'll wrap it multiple times
414        // in the following code.
415        let fut = Box::pin(self.do_process_inner(msg));
416
417        // Set the current session as the context when processing the message, if exists.
418        let fut = async move {
419            if let Some(session) = weak_session {
420                CURRENT_SESSION.scope(session, fut).await
421            } else {
422                fut.await
423            }
424        };
425
426        // Catch unwind.
427        let fut = async move {
428            AssertUnwindSafe(fut)
429                .rw_catch_unwind()
430                .await
431                .unwrap_or_else(|payload| {
432                    Err(PsqlError::Panic(
433                        panic_message::panic_message(&payload).to_owned(),
434                    ))
435                })
436        };
437
438        // Slow query log.
439        let fut = async move {
440            let period = *SLOW_QUERY_LOG_PERIOD;
441            let mut fut = std::pin::pin!(fut);
442            let mut elapsed = Duration::ZERO;
443
444            // Report the SQL in the log periodically if the query is slow.
445            loop {
446                match tokio::time::timeout(period, &mut fut).await {
447                    Ok(result) => break result,
448                    Err(_) => {
449                        elapsed += period;
450                        tracing::info!(
451                            target: PGWIRE_SLOW_QUERY_LOG,
452                            elapsed = %format_args!("{}ms", elapsed.as_millis()),
453                            "slow query"
454                        );
455                    }
456                }
457            }
458        };
459
460        // Query log.
461        let fut = async move {
462            if !tracing::Span::current().is_none() {
463                tracing::info!(
464                    target: PGWIRE_QUERY_LOG,
465                    status = "started",
466                );
467            }
468
469            let start = Instant::now();
470            let result = fut.await;
471            let elapsed = start.elapsed();
472
473            // Always log if an error occurs.
474            // Note: all messages will be processed through this code path, making it the
475            //       only necessary place to log errors.
476            if let Err(error) = &result {
477                if cfg!(debug_assertions) && !Deployment::current().is_ci() {
478                    // For local debugging, we print the error with backtrace.
479                    // It's useful only when:
480                    // - no additional context is added to the error
481                    // - backtrace is captured in the error
482                    // - backtrace is not printed in the middle
483                    tracing::error!(error = ?error.as_report(), "error when process message");
484                } else {
485                    tracing::error!(error = %error.as_report(), "error when process message");
486                }
487            }
488
489            // Log to optionally-enabled target `PGWIRE_QUERY_LOG`.
490            // Only log if we're currently in a tracing span set in `span_for_msg`.
491            if !tracing::Span::current().is_none() {
492                tracing::info!(
493                    target: PGWIRE_QUERY_LOG,
494                    status = if result.is_ok() { "ok" } else { "err" },
495                    time = %format_args!("{}ms", elapsed.as_millis()),
496                );
497            }
498
499            result
500        };
501
502        // Tracing span.
503        let fut = fut.instrument(span);
504
505        // Execute the future and handle the error.
506        match fut.await {
507            Ok(()) => Some(()),
508            Err(e) => {
509                match e {
510                    PsqlError::IoError(io_err) => {
511                        if io_err.kind() == std::io::ErrorKind::UnexpectedEof {
512                            return None;
513                        }
514                    }
515
516                    PsqlError::SslError(_) => {
517                        // For ssl error, because the stream has already been consumed, so there is
518                        // no way to write more message.
519                        return None;
520                    }
521
522                    PsqlError::StartupError(_)
523                    | PsqlError::PasswordError
524                    | PsqlError::ProtocolError(_) => {
525                        self.stream
526                            .write_no_flush(BeMessage::ErrorResponse {
527                                error: &e,
528                                // At this time we're not in a session, use compact error message for
529                                // better alignment with Postgres' UI.
530                                pretty: false,
531                                severity: Some(Severity::Fatal),
532                            })
533                            .ok()?;
534                        let _ = self.stream.flush().await;
535                        return None;
536                    }
537
538                    PsqlError::SimpleQueryError(_) | PsqlError::ServerThrottle(_) => {
539                        self.stream
540                            .write_no_flush(BeMessage::ErrorResponse {
541                                error: &e,
542                                pretty: true,
543                                severity: None,
544                            })
545                            .ok()?;
546                        self.ready_for_query().ok()?;
547                    }
548
549                    PsqlError::IdleInTxnTimeout | PsqlError::Panic(_) => {
550                        self.stream
551                            .write_no_flush(BeMessage::ErrorResponse {
552                                error: &e,
553                                pretty: true,
554                                severity: None,
555                            })
556                            .ok()?;
557                        let _ = self.stream.flush().await;
558
559                        // 1. Catching the panic during message processing may leave the session in an
560                        // inconsistent state. We forcefully close the connection (then end the
561                        // session) here for safety.
562                        // 2. Idle in transaction timeout should also close the connection.
563                        return None;
564                    }
565
566                    PsqlError::Uncategorized(_)
567                    | PsqlError::ExtendedPrepareError(_)
568                    | PsqlError::ExtendedExecuteError(_) => {
569                        self.stream
570                            .write_no_flush(BeMessage::ErrorResponse {
571                                error: &e,
572                                pretty: true,
573                                severity: None,
574                            })
575                            .ok()?;
576                    }
577                }
578                let _ = self.stream.flush().await;
579                Some(())
580            }
581        }
582    }
583
584    async fn do_process_inner(&mut self, msg: FeMessage) -> PsqlResult<()> {
585        if self.state == PgProtocolState::Authentication && !matches!(&msg, FeMessage::Password(_))
586        {
587            return Err(PsqlError::protocol_error(
588                "expected PasswordMessage during authentication",
589            ));
590        }
591
592        // Ignore util sync message.
593        if self.ignore_util_sync {
594            if let FeMessage::Sync = msg {
595            } else {
596                tracing::trace!("ignore message {:?} until sync.", msg);
597                return Ok(());
598            }
599        }
600
601        match msg {
602            FeMessage::Gss => self.process_gss_msg().await?,
603            FeMessage::Ssl => self.process_ssl_msg().await?,
604            FeMessage::Startup(msg) => self.process_startup_msg(msg).await?,
605            FeMessage::Password(msg) => self.process_password_msg(msg).await?,
606            FeMessage::Query(query_msg) => {
607                let sql = Arc::from(query_msg.get_sql()?);
608                // The process_query_msg can be slow. Release potential large FeQueryMessage early.
609                drop(query_msg);
610                self.process_query_msg(sql).await?
611            }
612            FeMessage::CancelQuery(m) => self.process_cancel_msg(m)?,
613            FeMessage::Terminate => self.process_terminate(),
614            FeMessage::Parse(m) => {
615                if let Err(err) = self.process_parse_msg(m).await {
616                    self.ignore_util_sync = true;
617                    return Err(err);
618                }
619            }
620            FeMessage::Bind(m) => {
621                if let Err(err) = self.process_bind_msg(m) {
622                    self.ignore_util_sync = true;
623                    return Err(err);
624                }
625            }
626            FeMessage::Execute(m) => {
627                if let Err(err) = self.process_execute_msg(m).await {
628                    self.ignore_util_sync = true;
629                    return Err(err);
630                }
631            }
632            FeMessage::Describe(m) => {
633                if let Err(err) = self.process_describe_msg(m) {
634                    self.ignore_util_sync = true;
635                    return Err(err);
636                }
637            }
638            FeMessage::Sync => {
639                self.ignore_util_sync = false;
640                self.ready_for_query()?
641            }
642            FeMessage::Close(m) => {
643                if let Err(err) = self.process_close_msg(m) {
644                    self.ignore_util_sync = true;
645                    return Err(err);
646                }
647            }
648            FeMessage::Flush => {
649                if let Err(err) = self.stream.flush().await {
650                    self.ignore_util_sync = true;
651                    return Err(err.into());
652                }
653            }
654            FeMessage::HealthCheck => self.process_health_check(),
655            FeMessage::ServerThrottle(reason) => match reason {
656                ServerThrottleReason::TooLargeMessage => {
657                    return Err(PsqlError::ServerThrottle(format!(
658                        "max_single_query_size_bytes {} has been exceeded, please either reduce the query size or increase the limit",
659                        self.message_memory_manager.max_filter_bytes
660                    )));
661                }
662                ServerThrottleReason::TooManyMemoryUsage => {
663                    return Err(PsqlError::ServerThrottle(format!(
664                        "max_total_query_size_bytes {} has been exceeded, please either retry or increase the limit",
665                        self.message_memory_manager.max_running_bytes
666                    )));
667                }
668            },
669        }
670        self.stream.flush().await?;
671        Ok(())
672    }
673
674    pub async fn read_message(&mut self) -> io::Result<(FeMessage, Option<MessageMemoryGuard>)> {
675        match self.state {
676            PgProtocolState::Startup => self
677                .stream
678                .read_startup()
679                .await
680                .map(|message: FeMessage| (message, None)),
681            PgProtocolState::Authentication | PgProtocolState::Regular => {
682                self.stream.read_header().await?;
683                let guard = if let Some(ref header) = self.stream.read_header {
684                    let payload_len = std::cmp::max(header.payload_len, 0) as u64;
685                    let (reason, guard) = self.message_memory_manager.add(payload_len);
686                    if let Some(reason) = reason {
687                        // Release the memory ASAP.
688                        drop(guard);
689                        self.stream.skip_body().await?;
690                        return Ok((FeMessage::ServerThrottle(reason), None));
691                    }
692                    guard
693                } else {
694                    None
695                };
696                let message = self.stream.read_body().await?;
697                Ok((message, guard))
698            }
699        }
700    }
701
702    /// Writes a `ReadyForQuery` message to the client without flushing.
703    fn ready_for_query(&mut self) -> io::Result<()> {
704        self.stream.write_no_flush(BeMessage::ReadyForQuery(
705            self.session
706                .as_ref()
707                .map(|s| s.transaction_status())
708                .unwrap_or(TransactionStatus::Idle),
709        ))
710    }
711
712    async fn process_gss_msg(&mut self) -> PsqlResult<()> {
713        // We don't support GSSAPI, so we just say no gracefully.
714        self.stream.write(BeMessage::EncryptionResponseNo).await?;
715        Ok(())
716    }
717
718    async fn process_ssl_msg(&mut self) -> PsqlResult<()> {
719        if let Some(context) = self.tls_context.as_ref() {
720            // If got and ssl context, say yes for ssl connection.
721            // Construct ssl stream and replace with current one.
722            self.stream.write(BeMessage::EncryptionResponseSsl).await?;
723            self.stream.upgrade_to_ssl(context).await?;
724        } else {
725            // If no, say no for encryption.
726            self.stream.write(BeMessage::EncryptionResponseNo).await?;
727        }
728
729        Ok(())
730    }
731
732    async fn process_startup_msg(&mut self, msg: FeStartupMessage) -> PsqlResult<()> {
733        // Check SSL enforcement: if SSL is enforced but connection is not using SSL, reject
734        if let Some(ref tls_config) = self.tls_config
735            && tls_config.enforce_ssl
736            && !self.stream.is_ssl_connection().await
737        {
738            return Err(PsqlError::StartupError(
739                "SSL connection is required but not established".into(),
740            ));
741        }
742
743        let db_name = msg
744            .config
745            .get("database")
746            .cloned()
747            .unwrap_or_else(|| "dev".to_owned());
748        let user_name = msg
749            .config
750            .get("user")
751            .cloned()
752            .unwrap_or_else(|| "root".to_owned());
753
754        let session = self
755            .session_mgr
756            .connect(&db_name, &user_name, self.peer_addr.clone())
757            .map_err(|e| PsqlError::StartupError(e.into()))?;
758
759        if let Some(options) = msg.config.get("options") {
760            for (key, value) in parse_options(options)? {
761                session
762                    .set_config(&key, value)
763                    .map_err(|e| PsqlError::StartupError(e.into()))?;
764            }
765        }
766        // dedicated `application_name` has higher priority than `options`
767        let application_name = msg.config.get("application_name");
768        if let Some(application_name) = application_name {
769            session
770                .set_config("application_name", application_name.clone())
771                .map_err(|e| PsqlError::StartupError(e.into()))?;
772        }
773
774        self.application_name = application_name.cloned();
775
776        match session.user_authenticator() {
777            UserAuthenticator::None => self.finish_authentication(&session)?,
778            UserAuthenticator::ClearText(_)
779            | UserAuthenticator::OAuth { .. }
780            | UserAuthenticator::Ldap(..) => {
781                self.stream
782                    .write_no_flush(BeMessage::AuthenticationCleartextPassword)?;
783                self.state = PgProtocolState::Authentication;
784            }
785            UserAuthenticator::Md5WithSalt { salt, .. } => {
786                self.stream
787                    .write_no_flush(BeMessage::AuthenticationMd5Password(salt))?;
788                self.state = PgProtocolState::Authentication;
789            }
790        };
791
792        self.session = Some(session);
793        Ok(())
794    }
795
796    /// Completes the startup sequence once the user is authenticated: acknowledge the
797    /// authentication, hand the client the key it needs to cancel this session, report the
798    /// server parameters and open the connection for queries.
799    ///
800    /// Shared by every authentication method so that none of them can drift.
801    fn finish_authentication(&mut self, session: &SM::Session) -> PsqlResult<()> {
802        self.stream.write_no_flush(BeMessage::AuthenticationOk)?;
803        // The client needs this to identify the session in a later `CancelRequest`, and
804        // postgres sends it once authentication has succeeded.
805        self.stream
806            .write_no_flush(BeMessage::BackendKeyData(session.id()))?;
807        let timezone = session
808            .get_config("timezone")
809            .map_err(|e| PsqlError::StartupError(e.into()))?;
810        self.stream.write_no_flush(BeMessage::ParameterStatus(
811            BeParameterStatusMessage::TimeZone(&timezone),
812        ))?;
813        self.stream
814            .write_parameter_status_msg_no_flush(&ParameterStatus {
815                application_name: self.application_name.clone(),
816            })?;
817        self.ready_for_query()?;
818        self.state = PgProtocolState::Regular;
819        Ok(())
820    }
821
822    async fn process_password_msg(&mut self, msg: FePasswordMessage) -> PsqlResult<()> {
823        let session = self.session.clone().unwrap();
824        session
825            .user_authenticator()
826            .authenticate(&msg.password)
827            .await?;
828        self.finish_authentication(&session)
829    }
830
831    fn process_cancel_msg(&mut self, m: FeCancelMessage) -> PsqlResult<()> {
832        let session_id = (m.target_process_id, m.target_secret_key);
833        tracing::trace!("cancel query in session: {:?}", session_id);
834        self.session_mgr.cancel_queries_in_session(session_id);
835        self.session_mgr.cancel_creating_jobs_in_session(session_id);
836        self.is_terminate = true;
837        Ok(())
838    }
839
840    async fn process_query_msg(&mut self, sql: Arc<str>) -> PsqlResult<()> {
841        let truncated_sql = get_redacted_and_truncated_sql(&sql, self.sql_option_redaction.clone());
842        let session = self.session.clone().unwrap();
843
844        session.check_idle_in_transaction_timeout()?;
845        // Store only truncated SQL in context to prevent excessive memory usage from large SQL.
846        let _exec_context_guard = session.init_exec_context(truncated_sql.into());
847        self.inner_process_query_msg(sql, session.clone()).await
848    }
849
850    async fn inner_process_query_msg(
851        &mut self,
852        sql: Arc<str>,
853        session: Arc<SM::Session>,
854    ) -> PsqlResult<()> {
855        // Parse sql.
856        let stmts =
857            Parser::parse_sql(&sql).map_err(|err| PsqlError::SimpleQueryError(err.into()))?;
858        // The following inner_process_query_msg_one_stmt can be slow. Release potential large String early.
859        drop(sql);
860        if stmts.is_empty() {
861            self.stream.write_no_flush(BeMessage::EmptyQueryResponse)?;
862        }
863
864        // Execute multiple statements in simple query. KISS later.
865        for stmt in stmts {
866            self.inner_process_query_msg_one_stmt(stmt, session.clone())
867                .await?;
868        }
869        // Put this line inside the for loop above will lead to unfinished/stuck regress test...Not
870        // sure the reason.
871        self.ready_for_query()?;
872        Ok(())
873    }
874
875    async fn inner_process_query_msg_one_stmt(
876        &mut self,
877        stmt: Statement,
878        session: Arc<SM::Session>,
879    ) -> PsqlResult<()> {
880        let session = session.clone();
881
882        // execute query
883        let res = session.clone().run_one_query(stmt, Format::Text).await;
884
885        // Take all remaining notices (if any) and send them before `CommandComplete`.
886        while let Some(notice) = session.next_notice().now_or_never() {
887            self.stream
888                .write_no_flush(BeMessage::NoticeResponse(&notice))?;
889        }
890
891        let mut res = res.map_err(|e| PsqlError::SimpleQueryError(e.into()))?;
892
893        for notice in res.notices() {
894            self.stream
895                .write_no_flush(BeMessage::NoticeResponse(notice))?;
896        }
897
898        let status = res.status();
899        if let Some(ref application_name) = status.application_name {
900            self.stream.write_no_flush(BeMessage::ParameterStatus(
901                BeParameterStatusMessage::ApplicationName(application_name),
902            ))?;
903        }
904
905        if res.is_copy_query_to_stdout() {
906            self.stream
907                .write_no_flush(BeMessage::CopyOutResponse(res.row_desc().len()))?;
908            let mut count = 0;
909            while let Some(row_set) = res.values_stream().next().await {
910                let row_set = row_set.map_err(PsqlError::SimpleQueryError)?;
911                for row in row_set {
912                    self.stream
913                        .write_streaming(BeMessage::CopyData(&row))
914                        .await?;
915                    count += 1;
916                }
917            }
918
919            self.stream.write_no_flush(BeMessage::CopyDone)?;
920
921            // Run the callback before sending the `CommandComplete` message.
922            res.run_callback().await?;
923
924            self.stream
925                .write_no_flush(BeMessage::CommandComplete(BeCommandCompleteMessage {
926                    stmt_type: res.stmt_type(),
927                    rows_cnt: count,
928                }))?;
929        } else if res.is_query() {
930            self.stream
931                .write_no_flush(BeMessage::RowDescription(res.row_desc()))?;
932
933            let mut rows_cnt = 0;
934
935            while let Some(row_set) = res.values_stream().next().await {
936                let row_set = row_set.map_err(PsqlError::SimpleQueryError)?;
937                for row in row_set {
938                    self.stream
939                        .write_streaming(BeMessage::DataRow(&row))
940                        .await?;
941                    rows_cnt += 1;
942                }
943            }
944
945            // Run the callback before sending the `CommandComplete` message.
946            res.run_callback().await?;
947
948            self.stream
949                .write_no_flush(BeMessage::CommandComplete(BeCommandCompleteMessage {
950                    stmt_type: res.stmt_type(),
951                    rows_cnt,
952                }))?;
953        } else if res.stmt_type().is_dml() && !res.stmt_type().is_returning() {
954            let first_row_set = res.values_stream().next().await;
955            let first_row_set = match first_row_set {
956                None => {
957                    return Err(PsqlError::Uncategorized(
958                        anyhow::anyhow!("no affected rows in output").into(),
959                    ));
960                }
961                Some(row) => row.map_err(PsqlError::SimpleQueryError)?,
962            };
963            let affected_rows_str = first_row_set[0].values()[0]
964                .as_ref()
965                .expect("compute node should return affected rows in output");
966
967            assert!(matches!(res.row_cnt_format(), Some(Format::Text)));
968            let affected_rows_cnt = String::from_utf8(affected_rows_str.to_vec())
969                .unwrap()
970                .parse()
971                .unwrap_or_default();
972
973            // Run the callback before sending the `CommandComplete` message.
974            res.run_callback().await?;
975
976            self.stream
977                .write_no_flush(BeMessage::CommandComplete(BeCommandCompleteMessage {
978                    stmt_type: res.stmt_type(),
979                    rows_cnt: affected_rows_cnt,
980                }))?;
981        } else {
982            // Run the callback before sending the `CommandComplete` message.
983            res.run_callback().await?;
984
985            self.stream
986                .write_no_flush(BeMessage::CommandComplete(BeCommandCompleteMessage {
987                    stmt_type: res.stmt_type(),
988                    rows_cnt: 0,
989                }))?;
990        }
991
992        Ok(())
993    }
994
995    fn process_terminate(&mut self) {
996        self.is_terminate = true;
997    }
998
999    fn process_health_check(&mut self) {
1000        tracing::debug!("health check");
1001        self.is_terminate = true;
1002    }
1003
1004    async fn process_parse_msg(&mut self, mut msg: FeParseMessage) -> PsqlResult<()> {
1005        let sql = Arc::from(cstr_to_str(&msg.sql_bytes).unwrap());
1006        let session = self.session.clone().unwrap();
1007        let statement_name = cstr_to_str(&msg.statement_name).unwrap().to_owned();
1008        let type_ids = std::mem::take(&mut msg.type_ids);
1009        // The inner_process_parse_msg can be slow. Release potential large FeParseMessage early.
1010        drop(msg);
1011        self.inner_process_parse_msg(session, sql, statement_name, type_ids)
1012            .await?;
1013        Ok(())
1014    }
1015
1016    async fn inner_process_parse_msg(
1017        &mut self,
1018        session: Arc<SM::Session>,
1019        sql: Arc<str>,
1020        statement_name: String,
1021        type_ids: Vec<i32>,
1022    ) -> PsqlResult<()> {
1023        if statement_name.is_empty() {
1024            // Remove the unnamed prepare statement first, in case the unsupported sql binds a wrong
1025            // prepare statement.
1026            self.unnamed_prepare_statement.take();
1027        } else if self.prepare_statement_store.contains_key(&statement_name) {
1028            return Err(PsqlError::ExtendedPrepareError(
1029                "Duplicated statement name".into(),
1030            ));
1031        }
1032
1033        let stmt = {
1034            let stmts = Parser::parse_sql(&sql)
1035                .map_err(|err| PsqlError::ExtendedPrepareError(err.into()))?;
1036            if stmts.len() > 1 {
1037                return Err(PsqlError::ExtendedPrepareError(
1038                    "Only one statement is allowed in extended query mode".into(),
1039                ));
1040            }
1041
1042            stmts.into_iter().next()
1043        };
1044
1045        let param_types: Vec<Option<DataType>> = type_ids
1046            .iter()
1047            .map(|&id| {
1048                // 0 means unspecified type
1049                // ref: https://www.postgresql.org/docs/15/protocol-message-formats.html#:~:text=Placing%20a%20zero%20here%20is%20equivalent%20to%20leaving%20the%20type%20unspecified.
1050                if id == 0 {
1051                    Ok(None)
1052                } else {
1053                    DataType::from_oid(id)
1054                        .map(Some)
1055                        .map_err(|e| PsqlError::ExtendedPrepareError(e.into()))
1056                }
1057            })
1058            .try_collect()?;
1059
1060        let prepare_statement = session
1061            .parse(stmt, param_types)
1062            .await
1063            .map_err(|e| PsqlError::ExtendedPrepareError(e.into()))?;
1064        let prepare_statement = PreparedStatementData {
1065            statement: prepare_statement,
1066            sql,
1067        };
1068
1069        if statement_name.is_empty() {
1070            self.unnamed_prepare_statement.replace(prepare_statement);
1071        } else {
1072            self.prepare_statement_store
1073                .insert(statement_name.clone(), prepare_statement);
1074        }
1075
1076        self.statement_portal_dependency
1077            .entry(statement_name)
1078            .or_default()
1079            .clear();
1080
1081        self.stream.write_no_flush(BeMessage::ParseComplete)?;
1082        Ok(())
1083    }
1084
1085    fn process_bind_msg(&mut self, msg: FeBindMessage) -> PsqlResult<()> {
1086        let statement_name = cstr_to_str(&msg.statement_name).unwrap().to_owned();
1087        let portal_name = cstr_to_str(&msg.portal_name).unwrap().to_owned();
1088        let session = self.session.clone().unwrap();
1089
1090        if self.portal_store.contains_key(&portal_name) {
1091            return Err(PsqlError::Uncategorized("Duplicated portal name".into()));
1092        }
1093
1094        let prepare_statement = self.get_statement_data(&statement_name)?.clone();
1095
1096        let result_formats = msg
1097            .result_format_codes
1098            .iter()
1099            .map(|&format_code| Format::from_i16(format_code))
1100            .try_collect()?;
1101        let param_formats = msg
1102            .param_format_codes
1103            .iter()
1104            .map(|&format_code| Format::from_i16(format_code))
1105            .try_collect()?;
1106
1107        let portal = session
1108            .bind(
1109                prepare_statement.statement,
1110                msg.params,
1111                param_formats,
1112                result_formats,
1113            )
1114            .map_err(|e| PsqlError::Uncategorized(e.into()))?;
1115        let portal = PortalData {
1116            portal,
1117            sql: prepare_statement.sql,
1118        };
1119
1120        if portal_name.is_empty() {
1121            self.result_cache.remove(&portal_name);
1122            self.unnamed_portal.replace(portal);
1123        } else {
1124            assert!(
1125                !self.result_cache.contains_key(&portal_name),
1126                "Named portal never can be overridden."
1127            );
1128            self.portal_store.insert(portal_name.clone(), portal);
1129        }
1130
1131        self.statement_portal_dependency
1132            .get_mut(&statement_name)
1133            .unwrap()
1134            .push(portal_name);
1135
1136        self.stream.write_no_flush(BeMessage::BindComplete)?;
1137        Ok(())
1138    }
1139
1140    async fn process_execute_msg(&mut self, msg: FeExecuteMessage) -> PsqlResult<()> {
1141        let portal_name = cstr_to_str(&msg.portal_name).unwrap().to_owned();
1142        let row_max = msg.max_rows as usize;
1143        drop(msg);
1144        let session = self.session.clone().unwrap();
1145
1146        match self.result_cache.remove(&portal_name) {
1147            Some(mut result_cache) => {
1148                assert!(self.portal_store.contains_key(&portal_name));
1149
1150                let is_consume_completed =
1151                    result_cache.consume::<S>(row_max, &mut self.stream).await?;
1152
1153                if !is_consume_completed {
1154                    self.result_cache.insert(portal_name, result_cache);
1155                }
1156            }
1157            _ => {
1158                let portal = self.get_portal_data(&portal_name)?.clone();
1159                let sql = format!("{}", portal.portal);
1160                let truncated_sql =
1161                    get_redacted_and_truncated_sql(&sql, self.sql_option_redaction.clone());
1162                drop(sql);
1163
1164                session.check_idle_in_transaction_timeout()?;
1165                // Store only truncated SQL in context to prevent excessive memory usage from large SQL.
1166                let _exec_context_guard = session.init_exec_context(truncated_sql.into());
1167                let result = session.clone().execute(portal.portal).await;
1168
1169                let pg_response = result.map_err(|e| PsqlError::ExtendedExecuteError(e.into()))?;
1170                let mut result_cache = ResultCache::new(pg_response);
1171                let is_consume_completed =
1172                    result_cache.consume::<S>(row_max, &mut self.stream).await?;
1173                if !is_consume_completed {
1174                    self.result_cache.insert(portal_name, result_cache);
1175                }
1176            }
1177        }
1178
1179        Ok(())
1180    }
1181
1182    fn process_describe_msg(&mut self, msg: FeDescribeMessage) -> PsqlResult<()> {
1183        let name = cstr_to_str(&msg.name).unwrap().to_owned();
1184        let session = self.session.clone().unwrap();
1185        //  b'S' => Statement
1186        //  b'P' => Portal
1187
1188        assert!(msg.kind == b'S' || msg.kind == b'P');
1189        if msg.kind == b'S' {
1190            let prepare_statement = self.get_statement(&name)?;
1191
1192            let (param_types, row_descriptions) = self
1193                .session
1194                .clone()
1195                .unwrap()
1196                .describe_statement(prepare_statement)
1197                .map_err(|e| PsqlError::Uncategorized(e.into()))?;
1198            self.stream.write_no_flush(BeMessage::ParameterDescription(
1199                &param_types.iter().map(|t| t.to_oid()).collect_vec(),
1200            ))?;
1201
1202            if row_descriptions.is_empty() {
1203                // According https://www.postgresql.org/docs/current/protocol-flow.html#:~:text=The%20response%20is%20a%20RowDescri[…]0a%20query%20that%20will%20return%20rows%3B,
1204                // return NoData message if the statement is not a query.
1205                self.stream.write_no_flush(BeMessage::NoData)?;
1206            } else {
1207                self.stream
1208                    .write_no_flush(BeMessage::RowDescription(&row_descriptions))?;
1209            }
1210        } else if msg.kind == b'P' {
1211            let portal = self.get_portal(&name)?;
1212
1213            let row_descriptions = session
1214                .describe_portal(portal)
1215                .map_err(|e| PsqlError::Uncategorized(e.into()))?;
1216
1217            if row_descriptions.is_empty() {
1218                // According https://www.postgresql.org/docs/current/protocol-flow.html#:~:text=The%20response%20is%20a%20RowDescri[…]0a%20query%20that%20will%20return%20rows%3B,
1219                // return NoData message if the statement is not a query.
1220                self.stream.write_no_flush(BeMessage::NoData)?;
1221            } else {
1222                self.stream
1223                    .write_no_flush(BeMessage::RowDescription(&row_descriptions))?;
1224            }
1225        }
1226        Ok(())
1227    }
1228
1229    fn process_close_msg(&mut self, msg: FeCloseMessage) -> PsqlResult<()> {
1230        let name = cstr_to_str(&msg.name).unwrap().to_owned();
1231        assert!(msg.kind == b'S' || msg.kind == b'P');
1232        if msg.kind == b'S' {
1233            if name.is_empty() {
1234                self.unnamed_prepare_statement = None;
1235            } else {
1236                self.prepare_statement_store.remove(&name);
1237            }
1238            for portal_name in self
1239                .statement_portal_dependency
1240                .remove(&name)
1241                .unwrap_or_default()
1242            {
1243                self.remove_portal(&portal_name);
1244            }
1245        } else if msg.kind == b'P' {
1246            self.remove_portal(&name);
1247        }
1248        self.stream.write_no_flush(BeMessage::CloseComplete)?;
1249        Ok(())
1250    }
1251
1252    fn remove_portal(&mut self, portal_name: &str) {
1253        if portal_name.is_empty() {
1254            self.unnamed_portal = None;
1255        } else {
1256            self.portal_store.remove(portal_name);
1257        }
1258        self.result_cache.remove(portal_name);
1259    }
1260
1261    fn get_portal(&self, portal_name: &str) -> PsqlResult<<SM::Session as Session>::Portal> {
1262        Ok(self.get_portal_data(portal_name)?.portal.clone())
1263    }
1264
1265    fn get_portal_data(
1266        &self,
1267        portal_name: &str,
1268    ) -> PsqlResult<&PortalData<<SM::Session as Session>::Portal>> {
1269        if portal_name.is_empty() {
1270            self.unnamed_portal
1271                .as_ref()
1272                .ok_or_else(|| PsqlError::Uncategorized("unnamed portal not found".into()))
1273        } else {
1274            self.portal_store.get(portal_name).ok_or_else(|| {
1275                PsqlError::Uncategorized(format!("Portal {} not found", portal_name).into())
1276            })
1277        }
1278    }
1279
1280    fn get_statement(
1281        &self,
1282        statement_name: &str,
1283    ) -> PsqlResult<<SM::Session as Session>::PreparedStatement> {
1284        Ok(self.get_statement_data(statement_name)?.statement.clone())
1285    }
1286
1287    fn get_statement_data(
1288        &self,
1289        statement_name: &str,
1290    ) -> PsqlResult<&PreparedStatementData<<SM::Session as Session>::PreparedStatement>> {
1291        if statement_name.is_empty() {
1292            self.unnamed_prepare_statement.as_ref().ok_or_else(|| {
1293                PsqlError::Uncategorized("unnamed prepare statement not found".into())
1294            })
1295        } else {
1296            self.prepare_statement_store
1297                .get(statement_name)
1298                .ok_or_else(|| {
1299                    PsqlError::Uncategorized(
1300                        format!("Prepare statement {} not found", statement_name).into(),
1301                    )
1302                })
1303        }
1304    }
1305
1306    fn get_portal_sql(&self, portal_name: &str) -> PsqlResult<Arc<str>> {
1307        Ok(self.get_portal_data(portal_name)?.sql.clone())
1308    }
1309}
1310
1311enum PgStreamInner<S> {
1312    /// Used for the intermediate state when converting from unencrypted to ssl stream.
1313    Placeholder,
1314    /// An unencrypted stream.
1315    Unencrypted(S),
1316    /// An ssl stream.
1317    Ssl(SslStream<S>),
1318}
1319
1320/// Trait for a byte stream that can be used for pg protocol.
1321pub trait PgByteStream: AsyncWrite + AsyncRead + Unpin + Send + 'static {}
1322impl<S> PgByteStream for S where S: AsyncWrite + AsyncRead + Unpin + Send + 'static {}
1323
1324/// Wraps a byte stream and read/write pg messages.
1325///
1326/// Cloning a `PgStream` will share the same stream but a fresh & independent write buffer,
1327/// so that it can be used to write messages concurrently without interference.
1328pub struct PgStream<S> {
1329    /// The underlying stream.
1330    stream: Arc<Mutex<PgStreamInner<S>>>,
1331    /// Write into buffer before flush to stream.
1332    write_buf: BytesMut,
1333    stream_flush_threshold_bytes: usize,
1334    read_header: Option<FeMessageHeader>,
1335}
1336
1337impl<S> PgStream<S> {
1338    /// Create a new `PgStream` with the given stream and streaming flush threshold.
1339    pub fn new(stream: S, stream_flush_threshold_bytes: usize) -> Self {
1340        const DEFAULT_WRITE_BUF_CAPACITY: usize = 10 * 1024;
1341
1342        Self {
1343            stream: Arc::new(Mutex::new(PgStreamInner::Unencrypted(stream))),
1344            write_buf: BytesMut::with_capacity(DEFAULT_WRITE_BUF_CAPACITY),
1345            stream_flush_threshold_bytes,
1346            read_header: None,
1347        }
1348    }
1349
1350    /// Check if the current connection is using SSL
1351    async fn is_ssl_connection(&self) -> bool {
1352        let stream = self.stream.lock().await;
1353        matches!(*stream, PgStreamInner::Ssl(_))
1354    }
1355}
1356
1357impl<S> Clone for PgStream<S> {
1358    fn clone(&self) -> Self {
1359        Self {
1360            stream: Arc::clone(&self.stream),
1361            write_buf: BytesMut::with_capacity(self.write_buf.capacity()),
1362            stream_flush_threshold_bytes: self.stream_flush_threshold_bytes,
1363            read_header: self.read_header.clone(),
1364        }
1365    }
1366}
1367
1368/// At present there is a hard-wired set of parameters for which
1369/// ParameterStatus will be generated: they are:
1370///
1371///  * `server_version`
1372///  * `server_encoding`
1373///  * `client_encoding`
1374///  * `application_name`
1375///  * `is_superuser`
1376///  * `session_authorization`
1377///  * `DateStyle`
1378///  * `IntervalStyle`
1379///  * `TimeZone`
1380///  * `integer_datetimes`
1381///  * `standard_conforming_string`
1382///
1383/// See: <https://www.postgresql.org/docs/9.2/static/protocol-flow.html#PROTOCOL-ASYNC>.
1384#[derive(Debug, Default, Clone)]
1385pub struct ParameterStatus {
1386    pub application_name: Option<String>,
1387}
1388
1389impl<S> PgStream<S>
1390where
1391    S: PgByteStream,
1392{
1393    async fn read_startup(&mut self) -> io::Result<FeMessage> {
1394        let mut stream = self.stream.lock().await;
1395        match &mut *stream {
1396            PgStreamInner::Placeholder => unreachable!(),
1397            PgStreamInner::Unencrypted(stream) => FeStartupMessage::read(stream).await,
1398            PgStreamInner::Ssl(ssl_stream) => FeStartupMessage::read(ssl_stream).await,
1399        }
1400    }
1401
1402    async fn read_header(&mut self) -> io::Result<()> {
1403        let mut stream = self.stream.lock().await;
1404        match &mut *stream {
1405            PgStreamInner::Placeholder => unreachable!(),
1406            PgStreamInner::Unencrypted(stream) => {
1407                self.read_header = Some(FeMessage::read_header(stream).await?);
1408                Ok(())
1409            }
1410            PgStreamInner::Ssl(ssl_stream) => {
1411                self.read_header = Some(FeMessage::read_header(ssl_stream).await?);
1412                Ok(())
1413            }
1414        }
1415    }
1416
1417    async fn read_body(&mut self) -> io::Result<FeMessage> {
1418        let mut stream = self.stream.lock().await;
1419        let header = self
1420            .read_header
1421            .take()
1422            .ok_or_else(|| std::io::Error::new(ErrorKind::InvalidInput, "header not found"))?;
1423        match &mut *stream {
1424            PgStreamInner::Placeholder => unreachable!(),
1425            PgStreamInner::Unencrypted(stream) => FeMessage::read_body(stream, header).await,
1426            PgStreamInner::Ssl(ssl_stream) => FeMessage::read_body(ssl_stream, header).await,
1427        }
1428    }
1429
1430    async fn skip_body(&mut self) -> io::Result<()> {
1431        let mut stream = self.stream.lock().await;
1432        let header = self
1433            .read_header
1434            .take()
1435            .ok_or_else(|| std::io::Error::new(ErrorKind::InvalidInput, "header not found"))?;
1436        match &mut *stream {
1437            PgStreamInner::Placeholder => unreachable!(),
1438            PgStreamInner::Unencrypted(stream) => FeMessage::skip_body(stream, header).await,
1439            PgStreamInner::Ssl(ssl_stream) => FeMessage::skip_body(ssl_stream, header).await,
1440        }
1441    }
1442
1443    fn write_parameter_status_msg_no_flush(&mut self, status: &ParameterStatus) -> io::Result<()> {
1444        self.write_no_flush(BeMessage::ParameterStatus(
1445            BeParameterStatusMessage::ClientEncoding(SERVER_ENCODING),
1446        ))?;
1447        self.write_no_flush(BeMessage::ParameterStatus(
1448            BeParameterStatusMessage::StandardConformingString(STANDARD_CONFORMING_STRINGS),
1449        ))?;
1450        self.write_no_flush(BeMessage::ParameterStatus(
1451            BeParameterStatusMessage::ServerVersion(PG_VERSION),
1452        ))?;
1453        if let Some(application_name) = &status.application_name {
1454            self.write_no_flush(BeMessage::ParameterStatus(
1455                BeParameterStatusMessage::ApplicationName(application_name),
1456            ))?;
1457        }
1458        Ok(())
1459    }
1460
1461    pub fn write_no_flush(&mut self, message: BeMessage<'_>) -> io::Result<()> {
1462        BeMessage::write(&mut self.write_buf, message)
1463    }
1464
1465    /// Write a message that is part of a potentially large response, flushing periodically to
1466    /// bound the write buffer and propagate network backpressure to the result stream.
1467    pub(crate) async fn write_streaming(&mut self, message: BeMessage<'_>) -> io::Result<()> {
1468        self.write_no_flush(message)?;
1469        if self.write_buf.len() >= self.stream_flush_threshold_bytes {
1470            self.flush().await?;
1471        }
1472        Ok(())
1473    }
1474
1475    async fn write(&mut self, message: BeMessage<'_>) -> io::Result<()> {
1476        self.write_no_flush(message)?;
1477        self.flush().await?;
1478        Ok(())
1479    }
1480
1481    async fn flush(&mut self) -> io::Result<()> {
1482        let mut stream = self.stream.lock().await;
1483        match &mut *stream {
1484            PgStreamInner::Placeholder => unreachable!(),
1485            PgStreamInner::Unencrypted(stream) => {
1486                stream.write_all(&self.write_buf).await?;
1487                stream.flush().await?;
1488            }
1489            PgStreamInner::Ssl(ssl_stream) => {
1490                ssl_stream.write_all(&self.write_buf).await?;
1491                ssl_stream.flush().await?;
1492            }
1493        }
1494        self.write_buf.clear();
1495        Ok(())
1496    }
1497}
1498
1499impl<S> PgStream<S>
1500where
1501    S: PgByteStream,
1502{
1503    /// Convert the underlying stream to ssl stream based on the given context.
1504    async fn upgrade_to_ssl(&mut self, ssl_ctx: &SslContextRef) -> PsqlResult<()> {
1505        let mut stream = self.stream.lock().await;
1506
1507        match std::mem::replace(&mut *stream, PgStreamInner::Placeholder) {
1508            PgStreamInner::Unencrypted(unencrypted_stream) => {
1509                let ssl = openssl::ssl::Ssl::new(ssl_ctx).unwrap();
1510                let mut ssl_stream =
1511                    tokio_openssl::SslStream::new(ssl, unencrypted_stream).unwrap();
1512
1513                if let Err(e) = Pin::new(&mut ssl_stream).accept().await {
1514                    tracing::warn!(error = %e.as_report(), "Unable to set up an ssl connection");
1515                    let _ = ssl_stream.shutdown().await;
1516                    return Err(e.into());
1517                }
1518
1519                *stream = PgStreamInner::Ssl(ssl_stream);
1520            }
1521            PgStreamInner::Ssl(_) => panic!("the stream is already ssl"),
1522            PgStreamInner::Placeholder => unreachable!(),
1523        }
1524
1525        Ok(())
1526    }
1527}
1528
1529fn build_ssl_ctx_from_config(tls_config: &TlsConfig) -> PsqlResult<SslContext> {
1530    let mut acceptor = SslAcceptor::mozilla_intermediate_v5(SslMethod::tls()).unwrap();
1531
1532    let key_path = &tls_config.key;
1533    let cert_path = &tls_config.cert;
1534
1535    // Build ssl acceptor according to the config.
1536    // Now we set every verify to true.
1537    acceptor
1538        .set_private_key_file(key_path, openssl::ssl::SslFiletype::PEM)
1539        .map_err(|e| PsqlError::Uncategorized(e.into()))?;
1540    acceptor
1541        .set_ca_file(cert_path)
1542        .map_err(|e| PsqlError::Uncategorized(e.into()))?;
1543    acceptor
1544        .set_certificate_chain_file(cert_path)
1545        .map_err(|e| PsqlError::Uncategorized(e.into()))?;
1546    let acceptor = acceptor.build();
1547
1548    Ok(acceptor.into_context())
1549}
1550
1551pub mod truncated_fmt {
1552    use std::fmt::*;
1553
1554    struct TruncatedFormatter<'a, 'b> {
1555        remaining: usize,
1556        finished: bool,
1557        f: &'a mut Formatter<'b>,
1558    }
1559    impl Write for TruncatedFormatter<'_, '_> {
1560        fn write_str(&mut self, s: &str) -> Result {
1561            if self.finished {
1562                return Ok(());
1563            }
1564
1565            if self.remaining < s.len() {
1566                let actual = s.floor_char_boundary(self.remaining);
1567                self.f.write_str(&s[0..actual])?;
1568                self.remaining -= actual;
1569                self.f.write_str(&format!("...(truncated,{})", s.len()))?;
1570                self.finished = true; // so that ...(truncated) is printed exactly once
1571            } else {
1572                self.f.write_str(s)?;
1573                self.remaining -= s.len();
1574            }
1575            Ok(())
1576        }
1577    }
1578
1579    pub struct TruncatedFmt<'a, T>(pub &'a T, pub usize);
1580
1581    impl<T> Debug for TruncatedFmt<'_, T>
1582    where
1583        T: Debug,
1584    {
1585        fn fmt(&self, f: &mut Formatter<'_>) -> Result {
1586            TruncatedFormatter {
1587                remaining: self.1,
1588                finished: false,
1589                f,
1590            }
1591            .write_fmt(format_args!("{:?}", self.0))
1592        }
1593    }
1594
1595    impl<T> Display for TruncatedFmt<'_, T>
1596    where
1597        T: Display,
1598    {
1599        fn fmt(&self, f: &mut Formatter<'_>) -> Result {
1600            TruncatedFormatter {
1601                remaining: self.1,
1602                finished: false,
1603                f,
1604            }
1605            .write_fmt(format_args!("{}", self.0))
1606        }
1607    }
1608
1609    #[cfg(test)]
1610    mod tests {
1611        use super::*;
1612
1613        #[test]
1614        fn test_trunc_utf8() {
1615            assert_eq!(
1616                format!("{}", TruncatedFmt(&"select '🌊';", 10)),
1617                "select '...(truncated,14)",
1618            );
1619        }
1620    }
1621}
1622
1623/// Handle `options` in `StartupMessage` from client
1624///
1625/// It is like shell arguments but only respects backslash-escape and space;
1626/// quotes have no special meaning and are handled literally.
1627///
1628/// PostgreSQL allows both `-c key=value` and `--key=value`.
1629///
1630/// `key-name` is normalized as `key_name`.
1631///
1632/// * <https://github.com/postgres/postgres/blob/REL_18_1/src/backend/utils/init/postinit.c#L487>
1633/// * <https://github.com/postgres/postgres/blob/REL_18_1/src/backend/tcop/postgres.c#L3866>
1634/// * <https://github.com/postgres/postgres/blob/REL_18_1/src/backend/utils/misc/guc.c#L6361>
1635fn parse_options(options: &str) -> PsqlResult<Vec<(String, String)>> {
1636    let mut args = Vec::new();
1637    let mut current_arg = String::new();
1638    let mut chars = options.chars().peekable();
1639
1640    while let Some(c) = chars.next() {
1641        if c == '\\' {
1642            if let Some(next_c) = chars.next() {
1643                current_arg.push(next_c);
1644            }
1645        } else if c.is_ascii_whitespace() {
1646            if !current_arg.is_empty() {
1647                args.push(std::mem::take(&mut current_arg));
1648            }
1649        } else {
1650            current_arg.push(c);
1651        }
1652    }
1653    if !current_arg.is_empty() {
1654        args.push(current_arg);
1655    }
1656
1657    let mut args_iter = args.into_iter();
1658    let mut config = Vec::new();
1659
1660    while let Some(arg) = args_iter.next() {
1661        if arg == "-c" {
1662            if let Some(config_str) = args_iter.next() {
1663                if let Some((key, value)) = config_str.split_once('=') {
1664                    let key = key.replace("-", "_");
1665                    config.push((key, value.to_owned()));
1666                } else {
1667                    return Err(PsqlError::StartupError(
1668                        format!("invalid config format: {}", config_str).into(),
1669                    ));
1670                }
1671            } else {
1672                return Err(PsqlError::StartupError("missing argument for -c".into()));
1673            }
1674        } else if let Some(config_str) = arg.strip_prefix("--") {
1675            if let Some((key, value)) = config_str.split_once('=') {
1676                let key = key.replace("-", "_");
1677                config.push((key, value.to_owned()));
1678            } else {
1679                return Err(PsqlError::StartupError(
1680                    format!("invalid config format: {}", config_str).into(),
1681                ));
1682            }
1683        } else {
1684            tracing::warn!(
1685                arg,
1686                "ignoring unrecognized option for backward compatibility"
1687            );
1688        }
1689    }
1690    Ok(config)
1691}
1692
1693#[cfg(test)]
1694mod tests {
1695    use risingwave_sqlparser::ast::SqlOptionRedaction;
1696    use tokio::io::AsyncReadExt;
1697
1698    use super::*;
1699    use crate::types::Row;
1700
1701    #[tokio::test]
1702    async fn test_streaming_write_flushes_at_threshold() {
1703        const STREAM_FLUSH_THRESHOLD: usize = 64 * 1024;
1704
1705        let (server, mut client) = tokio::io::duplex(STREAM_FLUSH_THRESHOLD * 2);
1706        let mut stream = PgStream::new(server, STREAM_FLUSH_THRESHOLD);
1707
1708        let small_row = Row::new(vec![Some(Bytes::from_static(b"small"))]);
1709        stream
1710            .write_streaming(BeMessage::DataRow(&small_row))
1711            .await
1712            .unwrap();
1713        assert!(!stream.write_buf.is_empty());
1714
1715        let large_row = Row::new(vec![Some(Bytes::from(vec![0; STREAM_FLUSH_THRESHOLD]))]);
1716        stream
1717            .write_streaming(BeMessage::DataRow(&large_row))
1718            .await
1719            .unwrap();
1720        assert!(stream.write_buf.is_empty());
1721
1722        let mut message_tag = [0];
1723        client.read_exact(&mut message_tag).await.unwrap();
1724        assert_eq!(message_tag[0], b'D');
1725    }
1726
1727    #[test]
1728    fn test_redact_parsable_sql() {
1729        let redaction = Arc::new(SqlOptionRedaction::new(
1730            ["v2".into(), "v4".into(), "b".into()],
1731            [],
1732        ));
1733        let sql = r"
1734        create source temp (k bigint, v varchar) with (
1735            connector = 'datagen',
1736            v1 = 123,
1737            v2 = 'with',
1738            v3 = false,
1739            v4 = '',
1740        ) FORMAT plain ENCODE json (a='1',b='2')
1741        ";
1742        assert_eq!(
1743            redact_sql(sql, redaction),
1744            "CREATE SOURCE temp (k BIGINT, v CHARACTER VARYING) WITH (connector = 'datagen', v1 = 123, v2 = [REDACTED], v3 = false, v4 = [REDACTED]) FORMAT PLAIN ENCODE JSON (a = '1', b = [REDACTED])"
1745        );
1746    }
1747
1748    #[test]
1749    fn test_redact_sql_option_allowlist() {
1750        let config = risingwave_common::config::BatchConfig::default();
1751        let sql = "CREATE SINK s FROM t WITH (primary_key = 'id', api_key = 'secret')";
1752        let redaction = Arc::new(SqlOptionRedaction::new(
1753            config.redact_sql_option_keywords.clone(),
1754            config.redact_sql_option_allowlist,
1755        ));
1756        assert_eq!(
1757            get_redacted_and_truncated_sql(sql, Some(redaction)),
1758            "CREATE SINK s FROM t WITH (primary_key = 'id', api_key = [REDACTED])",
1759        );
1760
1761        let redaction = Arc::new(SqlOptionRedaction::new(
1762            config.redact_sql_option_keywords,
1763            [],
1764        ));
1765        assert_eq!(
1766            get_redacted_and_truncated_sql(sql, Some(redaction)),
1767            "CREATE SINK s FROM t WITH (primary_key = [REDACTED], api_key = [REDACTED])",
1768        );
1769    }
1770
1771    #[test]
1772    fn test_redact_user_password_sql() {
1773        let redaction = Arc::new(SqlOptionRedaction::new(
1774            ["password".into()],
1775            ["password".into()],
1776        ));
1777
1778        assert_eq!(
1779            redact_sql(
1780                "ALTER USER WITH PASSWORD 'rw_password_2'",
1781                redaction.clone()
1782            ),
1783            "ALTER USER WITH PASSWORD [REDACTED]"
1784        );
1785        assert_eq!(
1786            redact_sql(
1787                "ALTER USER foo WITH ENCRYPTED PASSWORD 'md5827ccb0eea8a706c4c34a16891f84e7b'",
1788                redaction.clone(),
1789            ),
1790            "ALTER USER foo WITH ENCRYPTED PASSWORD [REDACTED]"
1791        );
1792        assert_eq!(
1793            redact_sql("CREATE USER foo WITH PASSWORD 'rw_password_2'", redaction),
1794            "CREATE USER foo WITH PASSWORD [REDACTED]"
1795        );
1796    }
1797
1798    #[test]
1799    fn test_parse_options() {
1800        assert_eq!(parse_options("").unwrap(), vec![]);
1801        assert_eq!(
1802            parse_options("-c a=1 -c b=2").unwrap(),
1803            vec![("a".into(), "1".into()), ("b".into(), "2".into())]
1804        );
1805        assert_eq!(
1806            parse_options("-c   key=value").unwrap(),
1807            vec![("key".into(), "value".into())]
1808        );
1809        // Custom parser treats quotes as normal characters, so they are included in value
1810        assert_eq!(
1811            parse_options("-c key='value'").unwrap(),
1812            vec![("key".into(), "'value'".into())]
1813        );
1814
1815        // Test backslash escaping for spaces (standard Postgres way)
1816        assert_eq!(
1817            parse_options(r#"-c key=value\ with\ spaces"#).unwrap(),
1818            vec![("key".into(), "value with spaces".into())]
1819        );
1820        assert_eq!(
1821            parse_options(r#"-c search_path=my\ schema"#).unwrap(),
1822            vec![("search_path".into(), "my schema".into())]
1823        );
1824
1825        assert!(parse_options("-c").is_err());
1826        assert!(parse_options("-c foo").is_err()); // missing =
1827        assert!(parse_options("--foo").is_err()); // missing = in -- option
1828
1829        assert_eq!(
1830            parse_options("--foo=bar").unwrap(),
1831            vec![("foo".into(), "bar".into())]
1832        );
1833        assert_eq!(
1834            parse_options(r#"--foo=bar\ baz"#).unwrap(),
1835            vec![("foo".into(), "bar baz".into())]
1836        );
1837        assert_eq!(
1838            parse_options("-c a=1 --b=2").unwrap(),
1839            vec![("a".into(), "1".into()), ("b".into(), "2".into())]
1840        );
1841        // Unpaired trailing backslash is silently dropped, same as PostgreSQL
1842        assert_eq!(
1843            parse_options(r#"-c a=b\"#).unwrap(),
1844            vec![("a".into(), "b".into())]
1845        );
1846    }
1847}