Line data Source code
1 : //! Server-side asynchronous Postgres connection, as limited as we need.
2 : //! To use, create PostgresBackend and run() it, passing the Handler
3 : //! implementation determining how to process the queries. Currently its API
4 : //! is rather narrow, but we can extend it once required.
5 : #![deny(unsafe_code)]
6 : #![deny(clippy::undocumented_unsafe_blocks)]
7 : use anyhow::Context;
8 : use bytes::Bytes;
9 : use serde::{Deserialize, Serialize};
10 : use std::io::ErrorKind;
11 : use std::net::SocketAddr;
12 : use std::pin::Pin;
13 : use std::sync::Arc;
14 : use std::task::{ready, Poll};
15 : use std::{fmt, io};
16 : use std::{future::Future, str::FromStr};
17 : use tokio::io::{AsyncRead, AsyncWrite};
18 : use tokio_rustls::TlsAcceptor;
19 : use tokio_util::sync::CancellationToken;
20 : use tracing::{debug, error, info, trace, warn};
21 :
22 : use pq_proto::framed::{ConnectionError, Framed, FramedReader, FramedWriter};
23 : use pq_proto::{
24 : BeMessage, FeMessage, FeStartupPacket, ProtocolError, SQLSTATE_ADMIN_SHUTDOWN,
25 : SQLSTATE_INTERNAL_ERROR, SQLSTATE_SUCCESSFUL_COMPLETION,
26 : };
27 :
28 : /// An error, occurred during query processing:
29 : /// either during the connection ([`ConnectionError`]) or before/after it.
30 0 : #[derive(thiserror::Error, Debug)]
31 : pub enum QueryError {
32 : /// The connection was lost while processing the query.
33 : #[error(transparent)]
34 : Disconnected(#[from] ConnectionError),
35 : /// We were instructed to shutdown while processing the query
36 : #[error("Shutting down")]
37 : Shutdown,
38 : /// Query handler indicated that client should reconnect
39 : #[error("Server requested reconnect")]
40 : Reconnect,
41 : /// Query named an entity that was not found
42 : #[error("Not found: {0}")]
43 : NotFound(std::borrow::Cow<'static, str>),
44 : /// Authentication failure
45 : #[error("Unauthorized: {0}")]
46 : Unauthorized(std::borrow::Cow<'static, str>),
47 : #[error("Simulated Connection Error")]
48 : SimulatedConnectionError,
49 : /// Some other error
50 : #[error(transparent)]
51 : Other(#[from] anyhow::Error),
52 : }
53 :
54 : impl From<io::Error> for QueryError {
55 0 : fn from(e: io::Error) -> Self {
56 0 : Self::Disconnected(ConnectionError::Io(e))
57 0 : }
58 : }
59 :
60 : impl QueryError {
61 0 : pub fn pg_error_code(&self) -> &'static [u8; 5] {
62 0 : match self {
63 0 : Self::Disconnected(_) | Self::SimulatedConnectionError | Self::Reconnect => b"08006", // connection failure
64 0 : Self::Shutdown => SQLSTATE_ADMIN_SHUTDOWN,
65 0 : Self::Unauthorized(_) | Self::NotFound(_) => SQLSTATE_INTERNAL_ERROR,
66 0 : Self::Other(_) => SQLSTATE_INTERNAL_ERROR, // internal error
67 : }
68 0 : }
69 : }
70 :
71 : /// Returns true if the given error is a normal consequence of a network issue,
72 : /// or the client closing the connection.
73 : ///
74 : /// These errors can happen during normal operations,
75 : /// and don't indicate a bug in our code.
76 0 : pub fn is_expected_io_error(e: &io::Error) -> bool {
77 : use io::ErrorKind::*;
78 0 : matches!(
79 0 : e.kind(),
80 : BrokenPipe | ConnectionRefused | ConnectionAborted | ConnectionReset | TimedOut
81 : )
82 0 : }
83 :
84 : #[async_trait::async_trait]
85 : pub trait Handler<IO> {
86 : /// Handle single query.
87 : /// postgres_backend will issue ReadyForQuery after calling this (this
88 : /// might be not what we want after CopyData streaming, but currently we don't
89 : /// care). It will also flush out the output buffer.
90 : async fn process_query(
91 : &mut self,
92 : pgb: &mut PostgresBackend<IO>,
93 : query_string: &str,
94 : ) -> Result<(), QueryError>;
95 :
96 : /// Called on startup packet receival, allows to process params.
97 : ///
98 : /// If Ok(false) is returned postgres_backend will skip auth -- that is needed for new users
99 : /// creation is the proxy code. That is quite hacky and ad-hoc solution, may be we could allow
100 : /// to override whole init logic in implementations.
101 2 : fn startup(
102 2 : &mut self,
103 2 : _pgb: &mut PostgresBackend<IO>,
104 2 : _sm: &FeStartupPacket,
105 2 : ) -> Result<(), QueryError> {
106 2 : Ok(())
107 2 : }
108 :
109 : /// Check auth jwt
110 0 : fn check_auth_jwt(
111 0 : &mut self,
112 0 : _pgb: &mut PostgresBackend<IO>,
113 0 : _jwt_response: &[u8],
114 0 : ) -> Result<(), QueryError> {
115 0 : Err(QueryError::Other(anyhow::anyhow!("JWT auth failed")))
116 0 : }
117 : }
118 :
119 : /// PostgresBackend protocol state.
120 : /// XXX: The order of the constructors matters.
121 : #[derive(Clone, Copy, PartialEq, Eq, PartialOrd)]
122 : pub enum ProtoState {
123 : /// Nothing happened yet.
124 : Initialization,
125 : /// Encryption handshake is done; waiting for encrypted Startup message.
126 : Encrypted,
127 : /// Waiting for password (auth token).
128 : Authentication,
129 : /// Performed handshake and auth, ReadyForQuery is issued.
130 : Established,
131 : Closed,
132 : }
133 :
134 : #[derive(Clone, Copy)]
135 : pub enum ProcessMsgResult {
136 : Continue,
137 : Break,
138 : }
139 :
140 : /// Either plain TCP stream or encrypted one, implementing AsyncRead + AsyncWrite.
141 : pub enum MaybeTlsStream<IO> {
142 : Unencrypted(IO),
143 : Tls(Box<tokio_rustls::server::TlsStream<IO>>),
144 : }
145 :
146 : impl<IO: AsyncRead + AsyncWrite + Unpin> AsyncWrite for MaybeTlsStream<IO> {
147 5 : fn poll_write(
148 5 : self: Pin<&mut Self>,
149 5 : cx: &mut std::task::Context<'_>,
150 5 : buf: &[u8],
151 5 : ) -> Poll<io::Result<usize>> {
152 5 : match self.get_mut() {
153 3 : Self::Unencrypted(stream) => Pin::new(stream).poll_write(cx, buf),
154 2 : Self::Tls(stream) => Pin::new(stream).poll_write(cx, buf),
155 : }
156 5 : }
157 5 : fn poll_flush(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<io::Result<()>> {
158 5 : match self.get_mut() {
159 3 : Self::Unencrypted(stream) => Pin::new(stream).poll_flush(cx),
160 2 : Self::Tls(stream) => Pin::new(stream).poll_flush(cx),
161 : }
162 5 : }
163 0 : fn poll_shutdown(
164 0 : self: Pin<&mut Self>,
165 0 : cx: &mut std::task::Context<'_>,
166 0 : ) -> Poll<io::Result<()>> {
167 0 : match self.get_mut() {
168 0 : Self::Unencrypted(stream) => Pin::new(stream).poll_shutdown(cx),
169 0 : Self::Tls(stream) => Pin::new(stream).poll_shutdown(cx),
170 : }
171 0 : }
172 : }
173 : impl<IO: AsyncRead + AsyncWrite + Unpin> AsyncRead for MaybeTlsStream<IO> {
174 12 : fn poll_read(
175 12 : self: Pin<&mut Self>,
176 12 : cx: &mut std::task::Context<'_>,
177 12 : buf: &mut tokio::io::ReadBuf<'_>,
178 12 : ) -> Poll<io::Result<()>> {
179 12 : match self.get_mut() {
180 7 : Self::Unencrypted(stream) => Pin::new(stream).poll_read(cx, buf),
181 5 : Self::Tls(stream) => Pin::new(stream).poll_read(cx, buf),
182 : }
183 12 : }
184 : }
185 :
186 0 : #[derive(Debug, PartialEq, Eq, Clone, Copy, Serialize, Deserialize)]
187 : pub enum AuthType {
188 : Trust,
189 : // This mimics postgres's AuthenticationCleartextPassword but instead of password expects JWT
190 : NeonJWT,
191 : }
192 :
193 : impl FromStr for AuthType {
194 : type Err = anyhow::Error;
195 :
196 0 : fn from_str(s: &str) -> Result<Self, Self::Err> {
197 0 : match s {
198 0 : "Trust" => Ok(Self::Trust),
199 0 : "NeonJWT" => Ok(Self::NeonJWT),
200 0 : _ => anyhow::bail!("invalid value \"{s}\" for auth type"),
201 : }
202 0 : }
203 : }
204 :
205 : impl fmt::Display for AuthType {
206 0 : fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
207 0 : f.write_str(match self {
208 0 : AuthType::Trust => "Trust",
209 0 : AuthType::NeonJWT => "NeonJWT",
210 : })
211 0 : }
212 : }
213 :
214 : /// Either full duplex Framed or write only half; the latter is left in
215 : /// PostgresBackend after call to `split`. In principle we could always store a
216 : /// pair of splitted handles, but that would force to to pay splitting price
217 : /// (Arc and kinda mutex inside polling) for all uses (e.g. pageserver).
218 : enum MaybeWriteOnly<IO> {
219 : Full(Framed<MaybeTlsStream<IO>>),
220 : WriteOnly(FramedWriter<MaybeTlsStream<IO>>),
221 : Broken, // temporary value palmed off during the split
222 : }
223 :
224 : impl<IO: AsyncRead + AsyncWrite + Unpin> MaybeWriteOnly<IO> {
225 3 : async fn read_startup_message(&mut self) -> Result<Option<FeStartupPacket>, ConnectionError> {
226 3 : match self {
227 3 : MaybeWriteOnly::Full(framed) => framed.read_startup_message().await,
228 : MaybeWriteOnly::WriteOnly(_) => {
229 0 : Err(io::Error::new(ErrorKind::Other, "reading from write only half").into())
230 : }
231 0 : MaybeWriteOnly::Broken => panic!("IO on invalid MaybeWriteOnly"),
232 : }
233 3 : }
234 :
235 4 : async fn read_message(&mut self) -> Result<Option<FeMessage>, ConnectionError> {
236 4 : match self {
237 4 : MaybeWriteOnly::Full(framed) => framed.read_message().await,
238 : MaybeWriteOnly::WriteOnly(_) => {
239 0 : Err(io::Error::new(ErrorKind::Other, "reading from write only half").into())
240 : }
241 0 : MaybeWriteOnly::Broken => panic!("IO on invalid MaybeWriteOnly"),
242 : }
243 2 : }
244 :
245 19 : fn write_message_noflush(&mut self, msg: &BeMessage<'_>) -> Result<(), ProtocolError> {
246 19 : match self {
247 19 : MaybeWriteOnly::Full(framed) => framed.write_message(msg),
248 0 : MaybeWriteOnly::WriteOnly(framed_writer) => framed_writer.write_message_noflush(msg),
249 0 : MaybeWriteOnly::Broken => panic!("IO on invalid MaybeWriteOnly"),
250 : }
251 19 : }
252 :
253 5 : async fn flush(&mut self) -> io::Result<()> {
254 5 : match self {
255 5 : MaybeWriteOnly::Full(framed) => framed.flush().await,
256 0 : MaybeWriteOnly::WriteOnly(framed_writer) => framed_writer.flush().await,
257 0 : MaybeWriteOnly::Broken => panic!("IO on invalid MaybeWriteOnly"),
258 : }
259 5 : }
260 :
261 : /// Cancellation safe as long as the underlying IO is cancellation safe.
262 0 : async fn shutdown(&mut self) -> io::Result<()> {
263 0 : match self {
264 0 : MaybeWriteOnly::Full(framed) => framed.shutdown().await,
265 0 : MaybeWriteOnly::WriteOnly(framed_writer) => framed_writer.shutdown().await,
266 0 : MaybeWriteOnly::Broken => panic!("IO on invalid MaybeWriteOnly"),
267 : }
268 0 : }
269 : }
270 :
271 : pub struct PostgresBackend<IO> {
272 : framed: MaybeWriteOnly<IO>,
273 :
274 : pub state: ProtoState,
275 :
276 : auth_type: AuthType,
277 :
278 : peer_addr: SocketAddr,
279 : pub tls_config: Option<Arc<rustls::ServerConfig>>,
280 : }
281 :
282 : pub type PostgresBackendTCP = PostgresBackend<tokio::net::TcpStream>;
283 :
284 0 : pub fn query_from_cstring(query_string: Bytes) -> Vec<u8> {
285 0 : let mut query_string = query_string.to_vec();
286 0 : if let Some(ch) = query_string.last() {
287 0 : if *ch == 0 {
288 0 : query_string.pop();
289 0 : }
290 0 : }
291 0 : query_string
292 0 : }
293 :
294 : /// Cast a byte slice to a string slice, dropping null terminator if there's one.
295 2 : fn cstr_to_str(bytes: &[u8]) -> anyhow::Result<&str> {
296 2 : let without_null = bytes.strip_suffix(&[0]).unwrap_or(bytes);
297 2 : std::str::from_utf8(without_null).map_err(|e| e.into())
298 2 : }
299 :
300 : impl PostgresBackend<tokio::net::TcpStream> {
301 2 : pub fn new(
302 2 : socket: tokio::net::TcpStream,
303 2 : auth_type: AuthType,
304 2 : tls_config: Option<Arc<rustls::ServerConfig>>,
305 2 : ) -> io::Result<Self> {
306 2 : let peer_addr = socket.peer_addr()?;
307 2 : let stream = MaybeTlsStream::Unencrypted(socket);
308 2 :
309 2 : Ok(Self {
310 2 : framed: MaybeWriteOnly::Full(Framed::new(stream)),
311 2 : state: ProtoState::Initialization,
312 2 : auth_type,
313 2 : tls_config,
314 2 : peer_addr,
315 2 : })
316 2 : }
317 : }
318 :
319 : impl<IO: AsyncRead + AsyncWrite + Unpin> PostgresBackend<IO> {
320 0 : pub fn new_from_io(
321 0 : socket: IO,
322 0 : peer_addr: SocketAddr,
323 0 : auth_type: AuthType,
324 0 : tls_config: Option<Arc<rustls::ServerConfig>>,
325 0 : ) -> io::Result<Self> {
326 0 : let stream = MaybeTlsStream::Unencrypted(socket);
327 0 :
328 0 : Ok(Self {
329 0 : framed: MaybeWriteOnly::Full(Framed::new(stream)),
330 0 : state: ProtoState::Initialization,
331 0 : auth_type,
332 0 : tls_config,
333 0 : peer_addr,
334 0 : })
335 0 : }
336 :
337 0 : pub fn get_peer_addr(&self) -> &SocketAddr {
338 0 : &self.peer_addr
339 0 : }
340 :
341 : /// Read full message or return None if connection is cleanly closed with no
342 : /// unprocessed data.
343 4 : pub async fn read_message(&mut self) -> Result<Option<FeMessage>, ConnectionError> {
344 4 : if let ProtoState::Closed = self.state {
345 0 : Ok(None)
346 : } else {
347 4 : match self.framed.read_message().await {
348 2 : Ok(m) => {
349 2 : trace!("read msg {:?}", m);
350 2 : Ok(m)
351 : }
352 0 : Err(e) => {
353 0 : // remember not to try to read anymore
354 0 : self.state = ProtoState::Closed;
355 0 : Err(e)
356 : }
357 : }
358 : }
359 2 : }
360 :
361 : /// Write message into internal output buffer, doesn't flush it. Technically
362 : /// error type can be only ProtocolError here (if, unlikely, serialization
363 : /// fails), but callers typically wrap it anyway.
364 19 : pub fn write_message_noflush(
365 19 : &mut self,
366 19 : message: &BeMessage<'_>,
367 19 : ) -> Result<&mut Self, ConnectionError> {
368 19 : self.framed.write_message_noflush(message)?;
369 19 : trace!("wrote msg {:?}", message);
370 19 : Ok(self)
371 19 : }
372 :
373 : /// Flush output buffer into the socket.
374 5 : pub async fn flush(&mut self) -> io::Result<()> {
375 5 : self.framed.flush().await
376 5 : }
377 :
378 : /// Polling version of `flush()`, saves the caller need to pin.
379 0 : pub fn poll_flush(
380 0 : &mut self,
381 0 : cx: &mut std::task::Context<'_>,
382 0 : ) -> Poll<Result<(), std::io::Error>> {
383 0 : let flush_fut = std::pin::pin!(self.flush());
384 0 : flush_fut.poll(cx)
385 0 : }
386 :
387 : /// Write message into internal output buffer and flush it to the stream.
388 3 : pub async fn write_message(
389 3 : &mut self,
390 3 : message: &BeMessage<'_>,
391 3 : ) -> Result<&mut Self, ConnectionError> {
392 3 : self.write_message_noflush(message)?;
393 3 : self.flush().await?;
394 3 : Ok(self)
395 3 : }
396 :
397 : /// Returns an AsyncWrite implementation that wraps all the data written
398 : /// to it in CopyData messages, and writes them to the connection
399 : ///
400 : /// The caller is responsible for sending CopyOutResponse and CopyDone messages.
401 0 : pub fn copyout_writer(&mut self) -> CopyDataWriter<IO> {
402 0 : CopyDataWriter { pgb: self }
403 0 : }
404 :
405 : /// Wrapper for run_message_loop() that shuts down socket when we are done
406 2 : pub async fn run(
407 2 : mut self,
408 2 : handler: &mut impl Handler<IO>,
409 2 : cancel: &CancellationToken,
410 2 : ) -> Result<(), QueryError> {
411 7 : let ret = self.run_message_loop(handler, cancel).await;
412 :
413 0 : tokio::select! {
414 0 : _ = cancel.cancelled() => {
415 0 : // do nothing; we most likely got already stopped by shutdown and will log it next.
416 0 : }
417 0 : _ = self.framed.shutdown() => {
418 0 : // socket might be already closed, e.g. if previously received error,
419 0 : // so ignore result.
420 0 : },
421 : }
422 :
423 0 : match ret {
424 0 : Ok(()) => Ok(()),
425 : Err(QueryError::Shutdown) => {
426 0 : info!("Stopped due to shutdown");
427 0 : Ok(())
428 : }
429 : Err(QueryError::Reconnect) => {
430 : // Dropping out of this loop implicitly disconnects
431 0 : info!("Stopped due to handler reconnect request");
432 0 : Ok(())
433 : }
434 0 : Err(QueryError::Disconnected(e)) => {
435 0 : info!("Disconnected ({e:#})");
436 : // Disconnection is not an error: we just use it that way internally to drop
437 : // out of loops.
438 0 : Ok(())
439 : }
440 0 : e => e,
441 : }
442 0 : }
443 :
444 2 : async fn run_message_loop(
445 2 : &mut self,
446 2 : handler: &mut impl Handler<IO>,
447 2 : cancel: &CancellationToken,
448 2 : ) -> Result<(), QueryError> {
449 2 : trace!("postgres backend to {:?} started", self.peer_addr);
450 :
451 2 : tokio::select!(
452 : biased;
453 :
454 2 : _ = cancel.cancelled() => {
455 : // We were requested to shut down.
456 0 : tracing::info!("shutdown request received during handshake");
457 0 : return Err(QueryError::Shutdown)
458 : },
459 :
460 2 : handshake_r = self.handshake(handler) => {
461 2 : handshake_r?;
462 : }
463 : );
464 :
465 : // Authentication completed
466 2 : let mut query_string = Bytes::new();
467 4 : while let Some(msg) = tokio::select!(
468 : biased;
469 4 : _ = cancel.cancelled() => {
470 : // We were requested to shut down.
471 0 : tracing::info!("shutdown request received in run_message_loop");
472 0 : return Err(QueryError::Shutdown)
473 : },
474 4 : msg = self.read_message() => { msg },
475 0 : )? {
476 2 : trace!("got message {:?}", msg);
477 :
478 2 : let result = self.process_message(handler, msg, &mut query_string).await;
479 2 : tokio::select!(
480 : biased;
481 2 : _ = cancel.cancelled() => {
482 : // We were requested to shut down.
483 0 : tracing::info!("shutdown request received during response flush");
484 :
485 : // If we exited process_message with a shutdown error, there may be
486 : // some valid response content on in our transmit buffer: permit sending
487 : // this within a short timeout. This is a best effort thing so we don't
488 : // care about the result.
489 0 : tokio::time::timeout(std::time::Duration::from_millis(500), self.flush()).await.ok();
490 0 :
491 0 : return Err(QueryError::Shutdown)
492 : },
493 2 : flush_r = self.flush() => {
494 2 : flush_r?;
495 : }
496 : );
497 :
498 2 : match result? {
499 : ProcessMsgResult::Continue => {
500 2 : continue;
501 : }
502 0 : ProcessMsgResult::Break => break,
503 : }
504 : }
505 :
506 0 : trace!("postgres backend to {:?} exited", self.peer_addr);
507 0 : Ok(())
508 0 : }
509 :
510 : /// Try to upgrade MaybeTlsStream into actual TLS one, performing handshake.
511 1 : async fn tls_upgrade(
512 1 : src: MaybeTlsStream<IO>,
513 1 : tls_config: Arc<rustls::ServerConfig>,
514 1 : ) -> anyhow::Result<MaybeTlsStream<IO>> {
515 1 : match src {
516 1 : MaybeTlsStream::Unencrypted(s) => {
517 1 : let acceptor = TlsAcceptor::from(tls_config);
518 2 : let tls_stream = acceptor.accept(s).await?;
519 1 : Ok(MaybeTlsStream::Tls(Box::new(tls_stream)))
520 : }
521 : MaybeTlsStream::Tls(_) => {
522 0 : anyhow::bail!("TLS already started");
523 : }
524 : }
525 1 : }
526 :
527 1 : async fn start_tls(&mut self) -> anyhow::Result<()> {
528 1 : // temporary replace stream with fake to cook TLS one, Indiana Jones style
529 1 : match std::mem::replace(&mut self.framed, MaybeWriteOnly::Broken) {
530 1 : MaybeWriteOnly::Full(framed) => {
531 1 : let tls_config = self
532 1 : .tls_config
533 1 : .as_ref()
534 1 : .context("start_tls called without conf")?
535 1 : .clone();
536 1 : let tls_framed = framed
537 1 : .map_stream(|s| PostgresBackend::tls_upgrade(s, tls_config))
538 2 : .await?;
539 : // push back ready TLS stream
540 1 : self.framed = MaybeWriteOnly::Full(tls_framed);
541 1 : Ok(())
542 : }
543 : MaybeWriteOnly::WriteOnly(_) => {
544 0 : anyhow::bail!("TLS upgrade attempt in split state")
545 : }
546 0 : MaybeWriteOnly::Broken => panic!("TLS upgrade on framed in invalid state"),
547 : }
548 1 : }
549 :
550 : /// Split off owned read part from which messages can be read in different
551 : /// task/thread.
552 0 : pub fn split(&mut self) -> anyhow::Result<PostgresBackendReader<IO>> {
553 0 : // temporary replace stream with fake to cook split one, Indiana Jones style
554 0 : match std::mem::replace(&mut self.framed, MaybeWriteOnly::Broken) {
555 0 : MaybeWriteOnly::Full(framed) => {
556 0 : let (reader, writer) = framed.split();
557 0 : self.framed = MaybeWriteOnly::WriteOnly(writer);
558 0 : Ok(PostgresBackendReader {
559 0 : reader,
560 0 : closed: false,
561 0 : })
562 : }
563 : MaybeWriteOnly::WriteOnly(_) => {
564 0 : anyhow::bail!("PostgresBackend is already split")
565 : }
566 0 : MaybeWriteOnly::Broken => panic!("split on framed in invalid state"),
567 : }
568 0 : }
569 :
570 : /// Join read part back.
571 0 : pub fn unsplit(&mut self, reader: PostgresBackendReader<IO>) -> anyhow::Result<()> {
572 0 : // temporary replace stream with fake to cook joined one, Indiana Jones style
573 0 : match std::mem::replace(&mut self.framed, MaybeWriteOnly::Broken) {
574 : MaybeWriteOnly::Full(_) => {
575 0 : anyhow::bail!("PostgresBackend is not split")
576 : }
577 0 : MaybeWriteOnly::WriteOnly(writer) => {
578 0 : let joined = Framed::unsplit(reader.reader, writer);
579 0 : self.framed = MaybeWriteOnly::Full(joined);
580 0 : // if reader encountered connection error, do not attempt reading anymore
581 0 : if reader.closed {
582 0 : self.state = ProtoState::Closed;
583 0 : }
584 0 : Ok(())
585 : }
586 0 : MaybeWriteOnly::Broken => panic!("unsplit on framed in invalid state"),
587 : }
588 0 : }
589 :
590 : /// Perform handshake with the client, transitioning to Established.
591 : /// In case of EOF during handshake logs this, sets state to Closed and returns Ok(()).
592 2 : async fn handshake(&mut self, handler: &mut impl Handler<IO>) -> Result<(), QueryError> {
593 5 : while self.state < ProtoState::Authentication {
594 3 : match self.framed.read_startup_message().await? {
595 3 : Some(msg) => {
596 3 : self.process_startup_message(handler, msg).await?;
597 : }
598 : None => {
599 0 : trace!(
600 0 : "postgres backend to {:?} received EOF during handshake",
601 : self.peer_addr
602 : );
603 0 : self.state = ProtoState::Closed;
604 0 : return Err(QueryError::Disconnected(ConnectionError::Protocol(
605 0 : ProtocolError::Protocol("EOF during handshake".to_string()),
606 0 : )));
607 : }
608 : }
609 : }
610 :
611 : // Perform auth, if needed.
612 2 : if self.state == ProtoState::Authentication {
613 0 : match self.framed.read_message().await? {
614 0 : Some(FeMessage::PasswordMessage(m)) => {
615 0 : assert!(self.auth_type == AuthType::NeonJWT);
616 :
617 0 : let (_, jwt_response) = m.split_last().context("protocol violation")?;
618 :
619 0 : if let Err(e) = handler.check_auth_jwt(self, jwt_response) {
620 0 : self.write_message_noflush(&BeMessage::ErrorResponse(
621 0 : &short_error(&e),
622 0 : Some(e.pg_error_code()),
623 0 : ))?;
624 0 : return Err(e);
625 0 : }
626 0 :
627 0 : self.write_message_noflush(&BeMessage::AuthenticationOk)?
628 0 : .write_message_noflush(&BeMessage::CLIENT_ENCODING)?
629 0 : .write_message(&BeMessage::ReadyForQuery)
630 0 : .await?;
631 0 : self.state = ProtoState::Established;
632 : }
633 0 : Some(m) => {
634 0 : return Err(QueryError::Other(anyhow::anyhow!(
635 0 : "Unexpected message {:?} while waiting for handshake",
636 0 : m
637 0 : )));
638 : }
639 : None => {
640 0 : trace!(
641 0 : "postgres backend to {:?} received EOF during auth",
642 : self.peer_addr
643 : );
644 0 : self.state = ProtoState::Closed;
645 0 : return Err(QueryError::Disconnected(ConnectionError::Protocol(
646 0 : ProtocolError::Protocol("EOF during auth".to_string()),
647 0 : )));
648 : }
649 : }
650 2 : }
651 :
652 2 : Ok(())
653 2 : }
654 :
655 : /// Process startup packet:
656 : /// - transition to Established if auth type is trust
657 : /// - transition to Authentication if auth type is NeonJWT.
658 : /// - or perform TLS handshake -- then need to call this again to receive
659 : /// actual startup packet.
660 3 : async fn process_startup_message(
661 3 : &mut self,
662 3 : handler: &mut impl Handler<IO>,
663 3 : msg: FeStartupPacket,
664 3 : ) -> Result<(), QueryError> {
665 3 : assert!(self.state < ProtoState::Authentication);
666 3 : let have_tls = self.tls_config.is_some();
667 3 : match msg {
668 1 : FeStartupPacket::SslRequest { direct } => {
669 1 : debug!("SSL requested");
670 :
671 1 : if !direct {
672 1 : self.write_message(&BeMessage::EncryptionResponse(have_tls))
673 0 : .await?;
674 0 : } else if !have_tls {
675 0 : return Err(QueryError::Other(anyhow::anyhow!(
676 0 : "direct SSL negotiation but no TLS support"
677 0 : )));
678 0 : }
679 :
680 1 : if have_tls {
681 2 : self.start_tls().await?;
682 1 : self.state = ProtoState::Encrypted;
683 0 : }
684 : }
685 : FeStartupPacket::GssEncRequest => {
686 0 : debug!("GSS requested");
687 0 : self.write_message(&BeMessage::EncryptionResponse(false))
688 0 : .await?;
689 : }
690 : FeStartupPacket::StartupMessage { .. } => {
691 2 : if have_tls && !matches!(self.state, ProtoState::Encrypted) {
692 0 : self.write_message(&BeMessage::ErrorResponse("must connect with TLS", None))
693 0 : .await?;
694 0 : return Err(QueryError::Other(anyhow::anyhow!(
695 0 : "client did not connect with TLS"
696 0 : )));
697 2 : }
698 2 :
699 2 : // NB: startup() may change self.auth_type -- we are using that in proxy code
700 2 : // to bypass auth for new users.
701 2 : handler.startup(self, &msg)?;
702 :
703 2 : match self.auth_type {
704 : AuthType::Trust => {
705 2 : self.write_message_noflush(&BeMessage::AuthenticationOk)?
706 2 : .write_message_noflush(&BeMessage::CLIENT_ENCODING)?
707 2 : .write_message_noflush(&BeMessage::INTEGER_DATETIMES)?
708 : // The async python driver requires a valid server_version
709 2 : .write_message_noflush(&BeMessage::server_version("14.1"))?
710 2 : .write_message(&BeMessage::ReadyForQuery)
711 0 : .await?;
712 2 : self.state = ProtoState::Established;
713 : }
714 : AuthType::NeonJWT => {
715 0 : self.write_message(&BeMessage::AuthenticationCleartextPassword)
716 0 : .await?;
717 0 : self.state = ProtoState::Authentication;
718 : }
719 : }
720 : }
721 : FeStartupPacket::CancelRequest { .. } => {
722 0 : return Err(QueryError::Other(anyhow::anyhow!(
723 0 : "Unexpected CancelRequest message during handshake"
724 0 : )));
725 : }
726 : }
727 3 : Ok(())
728 3 : }
729 :
730 2 : async fn process_message(
731 2 : &mut self,
732 2 : handler: &mut impl Handler<IO>,
733 2 : msg: FeMessage,
734 2 : unnamed_query_string: &mut Bytes,
735 2 : ) -> Result<ProcessMsgResult, QueryError> {
736 2 : // Allow only startup and password messages during auth. Otherwise client would be able to bypass auth
737 2 : // TODO: change that to proper top-level match of protocol state with separate message handling for each state
738 2 : assert!(self.state == ProtoState::Established);
739 :
740 2 : match msg {
741 2 : FeMessage::Query(body) => {
742 : // remove null terminator
743 2 : let query_string = cstr_to_str(&body)?;
744 :
745 2 : trace!("got query {query_string:?}");
746 2 : if let Err(e) = handler.process_query(self, query_string).await {
747 0 : match e {
748 0 : QueryError::Shutdown => return Ok(ProcessMsgResult::Break),
749 : QueryError::SimulatedConnectionError => {
750 0 : return Err(QueryError::SimulatedConnectionError)
751 : }
752 0 : e => {
753 0 : log_query_error(query_string, &e);
754 0 : let short_error = short_error(&e);
755 0 : self.write_message_noflush(&BeMessage::ErrorResponse(
756 0 : &short_error,
757 0 : Some(e.pg_error_code()),
758 0 : ))?;
759 : }
760 : }
761 2 : }
762 2 : self.write_message_noflush(&BeMessage::ReadyForQuery)?;
763 : }
764 :
765 0 : FeMessage::Parse(m) => {
766 0 : *unnamed_query_string = m.query_string;
767 0 : self.write_message_noflush(&BeMessage::ParseComplete)?;
768 : }
769 :
770 : FeMessage::Describe(_) => {
771 0 : self.write_message_noflush(&BeMessage::ParameterDescription)?
772 0 : .write_message_noflush(&BeMessage::NoData)?;
773 : }
774 :
775 : FeMessage::Bind(_) => {
776 0 : self.write_message_noflush(&BeMessage::BindComplete)?;
777 : }
778 :
779 : FeMessage::Close(_) => {
780 0 : self.write_message_noflush(&BeMessage::CloseComplete)?;
781 : }
782 :
783 : FeMessage::Execute(_) => {
784 0 : let query_string = cstr_to_str(unnamed_query_string)?;
785 0 : trace!("got execute {query_string:?}");
786 0 : if let Err(e) = handler.process_query(self, query_string).await {
787 0 : log_query_error(query_string, &e);
788 0 : self.write_message_noflush(&BeMessage::ErrorResponse(
789 0 : &e.to_string(),
790 0 : Some(e.pg_error_code()),
791 0 : ))?;
792 0 : }
793 : // NOTE there is no ReadyForQuery message. This handler is used
794 : // for basebackup and it uses CopyOut which doesn't require
795 : // ReadyForQuery message and backend just switches back to
796 : // processing mode after sending CopyDone or ErrorResponse.
797 : }
798 :
799 : FeMessage::Sync => {
800 0 : self.write_message_noflush(&BeMessage::ReadyForQuery)?;
801 : }
802 :
803 : FeMessage::Terminate => {
804 0 : return Ok(ProcessMsgResult::Break);
805 : }
806 :
807 : // We prefer explicit pattern matching to wildcards, because
808 : // this helps us spot the places where new variants are missing
809 : FeMessage::CopyData(_)
810 : | FeMessage::CopyDone
811 : | FeMessage::CopyFail
812 : | FeMessage::PasswordMessage(_) => {
813 0 : return Err(QueryError::Other(anyhow::anyhow!(
814 0 : "unexpected message type: {msg:?}",
815 0 : )));
816 : }
817 : }
818 :
819 2 : Ok(ProcessMsgResult::Continue)
820 2 : }
821 :
822 : /// - Log as info/error result of handling COPY stream and send back
823 : /// ErrorResponse if that makes sense.
824 : /// - Shutdown the stream if we got Terminate.
825 : /// - Then close the connection because we don't handle exiting from COPY
826 : /// stream normally.
827 0 : pub async fn handle_copy_stream_end(&mut self, end: CopyStreamHandlerEnd) {
828 : use CopyStreamHandlerEnd::*;
829 :
830 0 : let expected_end = match &end {
831 0 : ServerInitiated(_) | CopyDone | CopyFail | Terminate | EOF => true,
832 0 : CopyStreamHandlerEnd::Disconnected(ConnectionError::Io(io_error))
833 0 : if is_expected_io_error(io_error) =>
834 0 : {
835 0 : true
836 : }
837 0 : _ => false,
838 : };
839 0 : if expected_end {
840 0 : info!("terminated: {:#}", end);
841 : } else {
842 0 : error!("terminated: {:?}", end);
843 : }
844 :
845 : // Note: no current usages ever send this
846 0 : if let CopyDone = &end {
847 0 : if let Err(e) = self.write_message(&BeMessage::CopyDone).await {
848 0 : error!("failed to send CopyDone: {}", e);
849 0 : }
850 0 : }
851 :
852 0 : let err_to_send_and_errcode = match &end {
853 0 : ServerInitiated(_) => Some((end.to_string(), SQLSTATE_SUCCESSFUL_COMPLETION)),
854 0 : Other(_) => Some((format!("{end:#}"), SQLSTATE_INTERNAL_ERROR)),
855 : // Note: CopyFail in duplex copy is somewhat unexpected (at least to
856 : // PG walsender; evidently and per my docs reading client should
857 : // finish it with CopyDone). It is not a problem to recover from it
858 : // finishing the stream in both directions like we do, but note that
859 : // sync rust-postgres client (which we don't use anymore) hangs if
860 : // socket is not closed here.
861 : // https://github.com/sfackler/rust-postgres/issues/755
862 : // https://github.com/neondatabase/neon/issues/935
863 : //
864 : // Currently, the version of tokio_postgres replication patch we use
865 : // sends this when it closes the stream (e.g. pageserver decided to
866 : // switch conn to another safekeeper and client gets dropped).
867 : // Moreover, seems like 'connection' task errors with 'unexpected
868 : // message from server' when it receives ErrorResponse (anything but
869 : // CopyData/CopyDone) back.
870 0 : CopyFail => Some((end.to_string(), SQLSTATE_SUCCESSFUL_COMPLETION)),
871 0 : _ => None,
872 : };
873 0 : if let Some((err, errcode)) = err_to_send_and_errcode {
874 0 : if let Err(ee) = self
875 0 : .write_message(&BeMessage::ErrorResponse(&err, Some(errcode)))
876 0 : .await
877 : {
878 0 : error!("failed to send ErrorResponse: {}", ee);
879 0 : }
880 0 : }
881 :
882 : // Proper COPY stream finishing to continue using the connection is not
883 : // implemented at the server side (we don't need it so far). To prevent
884 : // further usages of the connection, close it.
885 0 : self.framed.shutdown().await.ok();
886 0 : self.state = ProtoState::Closed;
887 0 : }
888 : }
889 :
890 : pub struct PostgresBackendReader<IO> {
891 : reader: FramedReader<MaybeTlsStream<IO>>,
892 : closed: bool, // true if received error closing the connection
893 : }
894 :
895 : impl<IO: AsyncRead + AsyncWrite + Unpin> PostgresBackendReader<IO> {
896 : /// Read full message or return None if connection is cleanly closed with no
897 : /// unprocessed data.
898 0 : pub async fn read_message(&mut self) -> Result<Option<FeMessage>, ConnectionError> {
899 0 : match self.reader.read_message().await {
900 0 : Ok(m) => {
901 0 : trace!("read msg {:?}", m);
902 0 : Ok(m)
903 : }
904 0 : Err(e) => {
905 0 : self.closed = true;
906 0 : Err(e)
907 : }
908 : }
909 0 : }
910 :
911 : /// Get CopyData contents of the next message in COPY stream or error
912 : /// closing it. The error type is wider than actual errors which can happen
913 : /// here -- it includes 'Other' and 'ServerInitiated', but that's ok for
914 : /// current callers.
915 0 : pub async fn read_copy_message(&mut self) -> Result<Bytes, CopyStreamHandlerEnd> {
916 0 : match self.read_message().await? {
917 0 : Some(msg) => match msg {
918 0 : FeMessage::CopyData(m) => Ok(m),
919 0 : FeMessage::CopyDone => Err(CopyStreamHandlerEnd::CopyDone),
920 0 : FeMessage::CopyFail => Err(CopyStreamHandlerEnd::CopyFail),
921 0 : FeMessage::Terminate => Err(CopyStreamHandlerEnd::Terminate),
922 0 : _ => Err(CopyStreamHandlerEnd::from(ConnectionError::Protocol(
923 0 : ProtocolError::Protocol(format!("unexpected message in COPY stream {:?}", msg)),
924 0 : ))),
925 : },
926 0 : None => Err(CopyStreamHandlerEnd::EOF),
927 : }
928 0 : }
929 : }
930 :
931 : ///
932 : /// A futures::AsyncWrite implementation that wraps all data written to it in CopyData
933 : /// messages.
934 : ///
935 :
936 : pub struct CopyDataWriter<'a, IO> {
937 : pgb: &'a mut PostgresBackend<IO>,
938 : }
939 :
940 : impl<'a, IO: AsyncRead + AsyncWrite + Unpin> AsyncWrite for CopyDataWriter<'a, IO> {
941 0 : fn poll_write(
942 0 : self: Pin<&mut Self>,
943 0 : cx: &mut std::task::Context<'_>,
944 0 : buf: &[u8],
945 0 : ) -> Poll<Result<usize, std::io::Error>> {
946 0 : let this = self.get_mut();
947 :
948 : // It's not strictly required to flush between each message, but makes it easier
949 : // to view in wireshark, and usually the messages that the callers write are
950 : // decently-sized anyway.
951 0 : if let Err(err) = ready!(this.pgb.poll_flush(cx)) {
952 0 : return Poll::Ready(Err(err));
953 0 : }
954 0 :
955 0 : // CopyData
956 0 : // XXX: if the input is large, we should split it into multiple messages.
957 0 : // Not sure what the threshold should be, but the ultimate hard limit is that
958 0 : // the length cannot exceed u32.
959 0 : this.pgb
960 0 : .write_message_noflush(&BeMessage::CopyData(buf))
961 0 : // write_message only writes to the buffer, so it can fail iff the
962 0 : // message is invaid, but CopyData can't be invalid.
963 0 : .map_err(|_| io::Error::new(ErrorKind::Other, "failed to serialize CopyData"))?;
964 :
965 0 : Poll::Ready(Ok(buf.len()))
966 0 : }
967 :
968 0 : fn poll_flush(
969 0 : self: Pin<&mut Self>,
970 0 : cx: &mut std::task::Context<'_>,
971 0 : ) -> Poll<Result<(), std::io::Error>> {
972 0 : let this = self.get_mut();
973 0 : this.pgb.poll_flush(cx)
974 0 : }
975 :
976 0 : fn poll_shutdown(
977 0 : self: Pin<&mut Self>,
978 0 : cx: &mut std::task::Context<'_>,
979 0 : ) -> Poll<Result<(), std::io::Error>> {
980 0 : let this = self.get_mut();
981 0 : this.pgb.poll_flush(cx)
982 0 : }
983 : }
984 :
985 0 : pub fn short_error(e: &QueryError) -> String {
986 0 : match e {
987 0 : QueryError::Disconnected(connection_error) => connection_error.to_string(),
988 0 : QueryError::Reconnect => "reconnect".to_string(),
989 0 : QueryError::Shutdown => "shutdown".to_string(),
990 0 : QueryError::NotFound(_) => "not found".to_string(),
991 0 : QueryError::Unauthorized(_e) => "JWT authentication error".to_string(),
992 0 : QueryError::SimulatedConnectionError => "simulated connection error".to_string(),
993 0 : QueryError::Other(e) => format!("{e:#}"),
994 : }
995 0 : }
996 :
997 0 : fn log_query_error(query: &str, e: &QueryError) {
998 0 : match e {
999 0 : QueryError::Disconnected(ConnectionError::Io(io_error)) => {
1000 0 : if is_expected_io_error(io_error) {
1001 0 : info!("query handler for '{query}' failed with expected io error: {io_error}");
1002 : } else {
1003 0 : error!("query handler for '{query}' failed with io error: {io_error}");
1004 : }
1005 : }
1006 0 : QueryError::Disconnected(other_connection_error) => {
1007 0 : error!("query handler for '{query}' failed with connection error: {other_connection_error:?}")
1008 : }
1009 : QueryError::SimulatedConnectionError => {
1010 0 : error!("query handler for query '{query}' failed due to a simulated connection error")
1011 : }
1012 : QueryError::Reconnect => {
1013 0 : info!("query handler for '{query}' requested client to reconnect")
1014 : }
1015 : QueryError::Shutdown => {
1016 0 : info!("query handler for '{query}' cancelled during tenant shutdown")
1017 : }
1018 0 : QueryError::NotFound(reason) => {
1019 0 : info!("query handler for '{query}' entity not found: {reason}")
1020 : }
1021 0 : QueryError::Unauthorized(e) => {
1022 0 : warn!("query handler for '{query}' failed with authentication error: {e}");
1023 : }
1024 0 : QueryError::Other(e) => {
1025 0 : error!("query handler for '{query}' failed: {e:?}");
1026 : }
1027 : }
1028 0 : }
1029 :
1030 : /// Something finishing handling of COPY stream, see handle_copy_stream_end.
1031 : /// This is not always a real error, but it allows to use ? and thiserror impls.
1032 0 : #[derive(thiserror::Error, Debug)]
1033 : pub enum CopyStreamHandlerEnd {
1034 : /// Handler initiates the end of streaming.
1035 : #[error("{0}")]
1036 : ServerInitiated(String),
1037 : #[error("received CopyDone")]
1038 : CopyDone,
1039 : #[error("received CopyFail")]
1040 : CopyFail,
1041 : #[error("received Terminate")]
1042 : Terminate,
1043 : #[error("EOF on COPY stream")]
1044 : EOF,
1045 : /// The connection was lost
1046 : #[error("connection error: {0}")]
1047 : Disconnected(#[from] ConnectionError),
1048 : /// Some other error
1049 : #[error(transparent)]
1050 : Other(#[from] anyhow::Error),
1051 : }
|