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