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