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