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