LCOV - code coverage report
Current view: top level - proxy/src - stream.rs (source / functions) Coverage Total Hit
Test: 2a9d99866121f170b43760bd62e1e2431e597707.info Lines: 58.2 % 165 96
Test Date: 2024-09-02 14:10:37 Functions: 25.5 % 153 39

            Line data    Source code
       1              : use crate::config::TlsServerEndPoint;
       2              : use crate::error::{ErrorKind, ReportableError, UserFacingError};
       3              : use crate::metrics::Metrics;
       4              : use bytes::BytesMut;
       5              : 
       6              : use pq_proto::framed::{ConnectionError, Framed};
       7              : use pq_proto::{BeMessage, FeMessage, FeStartupPacket, ProtocolError};
       8              : use rustls::ServerConfig;
       9              : use std::pin::Pin;
      10              : use std::sync::Arc;
      11              : use std::{io, task};
      12              : use thiserror::Error;
      13              : use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
      14              : use tokio_rustls::server::TlsStream;
      15              : 
      16              : /// Stream wrapper which implements libpq's protocol.
      17              : /// NOTE: This object deliberately doesn't implement [`AsyncRead`]
      18              : /// or [`AsyncWrite`] to prevent subtle errors (e.g. trying
      19              : /// to pass random malformed bytes through the connection).
      20              : pub struct PqStream<S> {
      21              :     pub(crate) framed: Framed<S>,
      22              : }
      23              : 
      24              : impl<S> PqStream<S> {
      25              :     /// Construct a new libpq protocol wrapper.
      26           25 :     pub fn new(stream: S) -> Self {
      27           25 :         Self {
      28           25 :             framed: Framed::new(stream),
      29           25 :         }
      30           25 :     }
      31              : 
      32              :     /// Extract the underlying stream and read buffer.
      33            0 :     pub fn into_inner(self) -> (S, BytesMut) {
      34            0 :         self.framed.into_inner()
      35            0 :     }
      36              : 
      37              :     /// Get a shared reference to the underlying stream.
      38           35 :     pub(crate) fn get_ref(&self) -> &S {
      39           35 :         self.framed.get_ref()
      40           35 :     }
      41              : }
      42              : 
      43            0 : fn err_connection() -> io::Error {
      44            0 :     io::Error::new(io::ErrorKind::ConnectionAborted, "connection is lost")
      45            0 : }
      46              : 
      47              : impl<S: AsyncRead + Unpin> PqStream<S> {
      48              :     /// Receive [`FeStartupPacket`], which is a first packet sent by a client.
      49           42 :     pub async fn read_startup_packet(&mut self) -> io::Result<FeStartupPacket> {
      50           42 :         self.framed
      51           42 :             .read_startup_message()
      52            7 :             .await
      53           42 :             .map_err(ConnectionError::into_io_error)?
      54           42 :             .ok_or_else(err_connection)
      55           42 :     }
      56              : 
      57           26 :     async fn read_message(&mut self) -> io::Result<FeMessage> {
      58           26 :         self.framed
      59           26 :             .read_message()
      60           26 :             .await
      61           26 :             .map_err(ConnectionError::into_io_error)?
      62           25 :             .ok_or_else(err_connection)
      63           26 :     }
      64              : 
      65           26 :     pub(crate) async fn read_password_message(&mut self) -> io::Result<bytes::Bytes> {
      66           26 :         match self.read_message().await? {
      67           25 :             FeMessage::PasswordMessage(msg) => Ok(msg),
      68            0 :             bad => Err(io::Error::new(
      69            0 :                 io::ErrorKind::InvalidData,
      70            0 :                 format!("unexpected message type: {bad:?}"),
      71            0 :             )),
      72              :         }
      73           26 :     }
      74              : }
      75              : 
      76              : #[derive(Debug)]
      77              : pub struct ReportedError {
      78              :     source: anyhow::Error,
      79              :     error_kind: ErrorKind,
      80              : }
      81              : 
      82              : impl std::fmt::Display for ReportedError {
      83            1 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
      84            1 :         self.source.fmt(f)
      85            1 :     }
      86              : }
      87              : 
      88              : impl std::error::Error for ReportedError {
      89            0 :     fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
      90            0 :         self.source.source()
      91            0 :     }
      92              : }
      93              : 
      94              : impl ReportableError for ReportedError {
      95            0 :     fn get_error_kind(&self) -> ErrorKind {
      96            0 :         self.error_kind
      97            0 :     }
      98              : }
      99              : 
     100              : impl<S: AsyncWrite + Unpin> PqStream<S> {
     101              :     /// Write the message into an internal buffer, but don't flush the underlying stream.
     102           77 :     pub(crate) fn write_message_noflush(
     103           77 :         &mut self,
     104           77 :         message: &BeMessage<'_>,
     105           77 :     ) -> io::Result<&mut Self> {
     106           77 :         self.framed
     107           77 :             .write_message(message)
     108           77 :             .map_err(ProtocolError::into_io_error)?;
     109           77 :         Ok(self)
     110           77 :     }
     111              : 
     112              :     /// Write the message into an internal buffer and flush it.
     113           60 :     pub async fn write_message(&mut self, message: &BeMessage<'_>) -> io::Result<&mut Self> {
     114           60 :         self.write_message_noflush(message)?;
     115           60 :         self.flush().await?;
     116           60 :         Ok(self)
     117           60 :     }
     118              : 
     119              :     /// Flush the output buffer into the underlying stream.
     120           60 :     pub(crate) async fn flush(&mut self) -> io::Result<&mut Self> {
     121           60 :         self.framed.flush().await?;
     122           60 :         Ok(self)
     123           60 :     }
     124              : 
     125              :     /// Write the error message using [`Self::write_message`], then re-throw it.
     126              :     /// Allowing string literals is safe under the assumption they might not contain any runtime info.
     127              :     /// This method exists due to `&str` not implementing `Into<anyhow::Error>`.
     128            1 :     pub async fn throw_error_str<T>(
     129            1 :         &mut self,
     130            1 :         msg: &'static str,
     131            1 :         error_kind: ErrorKind,
     132            1 :     ) -> Result<T, ReportedError> {
     133            1 :         tracing::info!(
     134            0 :             kind = error_kind.to_metric_label(),
     135            0 :             msg,
     136            0 :             "forwarding error to user"
     137              :         );
     138              : 
     139              :         // already error case, ignore client IO error
     140            1 :         let _: Result<_, std::io::Error> = self
     141            1 :             .write_message(&BeMessage::ErrorResponse(msg, None))
     142            0 :             .await;
     143              : 
     144            1 :         Err(ReportedError {
     145            1 :             source: anyhow::anyhow!(msg),
     146            1 :             error_kind,
     147            1 :         })
     148            1 :     }
     149              : 
     150              :     /// Write the error message using [`Self::write_message`], then re-throw it.
     151              :     /// Trait [`UserFacingError`] acts as an allowlist for error types.
     152            0 :     pub(crate) async fn throw_error<T, E>(&mut self, error: E) -> Result<T, ReportedError>
     153            0 :     where
     154            0 :         E: UserFacingError + Into<anyhow::Error>,
     155            0 :     {
     156            0 :         let error_kind = error.get_error_kind();
     157            0 :         let msg = error.to_string_client();
     158            0 :         tracing::info!(
     159            0 :             kind=error_kind.to_metric_label(),
     160            0 :             error=%error,
     161            0 :             msg,
     162            0 :             "forwarding error to user"
     163              :         );
     164              : 
     165              :         // already error case, ignore client IO error
     166            0 :         let _: Result<_, std::io::Error> = self
     167            0 :             .write_message(&BeMessage::ErrorResponse(&msg, None))
     168            0 :             .await;
     169              : 
     170            0 :         Err(ReportedError {
     171            0 :             source: anyhow::anyhow!(error),
     172            0 :             error_kind,
     173            0 :         })
     174            0 :     }
     175              : }
     176              : 
     177              : /// Wrapper for upgrading raw streams into secure streams.
     178              : pub enum Stream<S> {
     179              :     /// We always begin with a raw stream,
     180              :     /// which may then be upgraded into a secure stream.
     181              :     Raw { raw: S },
     182              :     Tls {
     183              :         /// We box [`TlsStream`] since it can be quite large.
     184              :         tls: Box<TlsStream<S>>,
     185              :         /// Channel binding parameter
     186              :         tls_server_end_point: TlsServerEndPoint,
     187              :     },
     188              : }
     189              : 
     190              : impl<S: Unpin> Unpin for Stream<S> {}
     191              : 
     192              : impl<S> Stream<S> {
     193              :     /// Construct a new instance from a raw stream.
     194           25 :     pub fn from_raw(raw: S) -> Self {
     195           25 :         Self::Raw { raw }
     196           25 :     }
     197              : 
     198              :     /// Return SNI hostname when it's available.
     199            0 :     pub fn sni_hostname(&self) -> Option<&str> {
     200            0 :         match self {
     201            0 :             Stream::Raw { .. } => None,
     202            0 :             Stream::Tls { tls, .. } => tls.get_ref().1.server_name(),
     203              :         }
     204            0 :     }
     205              : 
     206           15 :     pub(crate) fn tls_server_end_point(&self) -> TlsServerEndPoint {
     207           15 :         match self {
     208            3 :             Stream::Raw { .. } => TlsServerEndPoint::Undefined,
     209              :             Stream::Tls {
     210           12 :                 tls_server_end_point,
     211           12 :                 ..
     212           12 :             } => *tls_server_end_point,
     213              :         }
     214           15 :     }
     215              : }
     216              : 
     217            0 : #[derive(Debug, Error)]
     218              : #[error("Can't upgrade TLS stream")]
     219              : pub enum StreamUpgradeError {
     220              :     #[error("Bad state reached: can't upgrade TLS stream")]
     221              :     AlreadyTls,
     222              : 
     223              :     #[error("Can't upgrade stream: IO error: {0}")]
     224              :     Io(#[from] io::Error),
     225              : }
     226              : 
     227              : impl<S: AsyncRead + AsyncWrite + Unpin> Stream<S> {
     228              :     /// If possible, upgrade raw stream into a secure TLS-based stream.
     229            0 :     pub async fn upgrade(
     230            0 :         self,
     231            0 :         cfg: Arc<ServerConfig>,
     232            0 :         record_handshake_error: bool,
     233            0 :     ) -> Result<TlsStream<S>, StreamUpgradeError> {
     234            0 :         match self {
     235            0 :             Stream::Raw { raw } => Ok(tokio_rustls::TlsAcceptor::from(cfg)
     236            0 :                 .accept(raw)
     237            0 :                 .await
     238            0 :                 .inspect_err(|_| {
     239            0 :                     if record_handshake_error {
     240            0 :                         Metrics::get().proxy.tls_handshake_failures.inc();
     241            0 :                     }
     242            0 :                 })?),
     243            0 :             Stream::Tls { .. } => Err(StreamUpgradeError::AlreadyTls),
     244              :         }
     245            0 :     }
     246              : }
     247              : 
     248              : impl<S: AsyncRead + AsyncWrite + Unpin> AsyncRead for Stream<S> {
     249          158 :     fn poll_read(
     250          158 :         mut self: Pin<&mut Self>,
     251          158 :         context: &mut task::Context<'_>,
     252          158 :         buf: &mut ReadBuf<'_>,
     253          158 :     ) -> task::Poll<io::Result<()>> {
     254          158 :         match &mut *self {
     255           30 :             Self::Raw { raw } => Pin::new(raw).poll_read(context, buf),
     256          128 :             Self::Tls { tls, .. } => Pin::new(tls).poll_read(context, buf),
     257              :         }
     258          158 :     }
     259              : }
     260              : 
     261              : impl<S: AsyncRead + AsyncWrite + Unpin> AsyncWrite for Stream<S> {
     262           76 :     fn poll_write(
     263           76 :         mut self: Pin<&mut Self>,
     264           76 :         context: &mut task::Context<'_>,
     265           76 :         buf: &[u8],
     266           76 :     ) -> task::Poll<io::Result<usize>> {
     267           76 :         match &mut *self {
     268           27 :             Self::Raw { raw } => Pin::new(raw).poll_write(context, buf),
     269           49 :             Self::Tls { tls, .. } => Pin::new(tls).poll_write(context, buf),
     270              :         }
     271           76 :     }
     272              : 
     273           76 :     fn poll_flush(
     274           76 :         mut self: Pin<&mut Self>,
     275           76 :         context: &mut task::Context<'_>,
     276           76 :     ) -> task::Poll<io::Result<()>> {
     277           76 :         match &mut *self {
     278           27 :             Self::Raw { raw } => Pin::new(raw).poll_flush(context),
     279           49 :             Self::Tls { tls, .. } => Pin::new(tls).poll_flush(context),
     280              :         }
     281           76 :     }
     282              : 
     283            0 :     fn poll_shutdown(
     284            0 :         mut self: Pin<&mut Self>,
     285            0 :         context: &mut task::Context<'_>,
     286            0 :     ) -> task::Poll<io::Result<()>> {
     287            0 :         match &mut *self {
     288            0 :             Self::Raw { raw } => Pin::new(raw).poll_shutdown(context),
     289            0 :             Self::Tls { tls, .. } => Pin::new(tls).poll_shutdown(context),
     290              :         }
     291            0 :     }
     292              : }
        

Generated by: LCOV version 2.1-beta