Line data Source code
1 : //! Postgres protocol messages serialization-deserialization. See
2 : //! <https://www.postgresql.org/docs/devel/protocol-message-formats.html>
3 : //! on message formats.
4 : #![deny(clippy::undocumented_unsafe_blocks)]
5 :
6 : pub mod framed;
7 :
8 : use byteorder::{BigEndian, ReadBytesExt};
9 : use bytes::{Buf, BufMut, Bytes, BytesMut};
10 : use std::{borrow::Cow, collections::HashMap, fmt, io, str};
11 :
12 : // re-export for use in utils pageserver_feedback.rs
13 : pub use postgres_protocol::PG_EPOCH;
14 :
15 : pub type Oid = u32;
16 : pub type SystemId = u64;
17 :
18 : pub const INT8_OID: Oid = 20;
19 : pub const INT4_OID: Oid = 23;
20 : pub const TEXT_OID: Oid = 25;
21 :
22 57 : #[derive(Debug)]
23 : pub enum FeMessage {
24 : // Simple query.
25 : Query(Bytes),
26 : // Extended query protocol.
27 : Parse(FeParseMessage),
28 : Describe(FeDescribeMessage),
29 : Bind(FeBindMessage),
30 : Execute(FeExecuteMessage),
31 : Close(FeCloseMessage),
32 : Sync,
33 : Terminate,
34 : CopyData(Bytes),
35 : CopyDone,
36 : CopyFail,
37 : PasswordMessage(Bytes),
38 : }
39 :
40 222 : #[derive(Debug)]
41 : pub enum FeStartupPacket {
42 : CancelRequest(CancelKeyData),
43 : SslRequest,
44 : GssEncRequest,
45 : StartupMessage {
46 : major_version: u32,
47 : minor_version: u32,
48 : params: StartupMessageParams,
49 : },
50 : }
51 :
52 122 : #[derive(Debug)]
53 : pub struct StartupMessageParams {
54 : params: HashMap<String, String>,
55 : }
56 :
57 : impl StartupMessageParams {
58 : /// Get parameter's value by its name.
59 7111 : pub fn get(&self, name: &str) -> Option<&str> {
60 7111 : self.params.get(name).map(|s| s.as_str())
61 7111 : }
62 :
63 : /// Split command-line options according to PostgreSQL's logic,
64 : /// taking into account all escape sequences but leaving them as-is.
65 : /// [`None`] means that there's no `options` in [`Self`].
66 3485 : pub fn options_raw(&self) -> Option<impl Iterator<Item = &str>> {
67 3485 : self.get("options").map(Self::parse_options_raw)
68 3485 : }
69 :
70 : /// Split command-line options according to PostgreSQL's logic,
71 : /// applying all escape sequences (using owned strings as needed).
72 : /// [`None`] means that there's no `options` in [`Self`].
73 10 : pub fn options_escaped(&self) -> Option<impl Iterator<Item = Cow<'_, str>>> {
74 10 : self.get("options").map(Self::parse_options_escaped)
75 10 : }
76 :
77 : /// Split command-line options according to PostgreSQL's logic,
78 : /// taking into account all escape sequences but leaving them as-is.
79 3485 : pub fn parse_options_raw(input: &str) -> impl Iterator<Item = &str> {
80 3485 : // See `postgres: pg_split_opts`.
81 3485 : let mut last_was_escape = false;
82 3485 : input
83 302398 : .split(move |c: char| {
84 : // We split by non-escaped whitespace symbols.
85 302398 : let should_split = c.is_ascii_whitespace() && !last_was_escape;
86 302398 : last_was_escape = c == '\\' && !last_was_escape;
87 302398 : should_split
88 302398 : })
89 10319 : .filter(|s| !s.is_empty())
90 3485 : }
91 :
92 : /// Split command-line options according to PostgreSQL's logic,
93 : /// applying all escape sequences (using owned strings as needed).
94 8 : pub fn parse_options_escaped(input: &str) -> impl Iterator<Item = Cow<'_, str>> {
95 8 : // See `postgres: pg_split_opts`.
96 14 : Self::parse_options_raw(input).map(|s| {
97 14 : let mut preserve_next_escape = false;
98 34 : let escape = |c| {
99 : // We should remove '\\' unless it's preceded by '\\'.
100 34 : let should_remove = c == '\\' && !preserve_next_escape;
101 34 : preserve_next_escape = should_remove;
102 34 : should_remove
103 34 : };
104 :
105 14 : match s.contains('\\') {
106 6 : true => Cow::Owned(s.replace(escape, "")),
107 8 : false => Cow::Borrowed(s),
108 : }
109 14 : })
110 8 : }
111 :
112 : /// Iterate through key-value pairs in an arbitrary order.
113 14 : pub fn iter(&self) -> impl Iterator<Item = (&str, &str)> {
114 42 : self.params.iter().map(|(k, v)| (k.as_str(), v.as_str()))
115 14 : }
116 :
117 : // This function is mostly useful in tests.
118 : #[doc(hidden)]
119 46 : pub fn new<'a, const N: usize>(pairs: [(&'a str, &'a str); N]) -> Self {
120 46 : Self {
121 62 : params: pairs.map(|(k, v)| (k.to_owned(), v.to_owned())).into(),
122 46 : }
123 46 : }
124 : }
125 :
126 287 : #[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)]
127 : pub struct CancelKeyData {
128 : pub backend_pid: i32,
129 : pub cancel_key: i32,
130 : }
131 :
132 : impl fmt::Display for CancelKeyData {
133 156 : fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
134 156 : let hi = (self.backend_pid as u64) << 32;
135 156 : let lo = self.cancel_key as u64;
136 156 : let id = hi | lo;
137 156 :
138 156 : // This format is more compact and might work better for logs.
139 156 : f.debug_tuple("CancelKeyData")
140 156 : .field(&format_args!("{:x}", id))
141 156 : .finish()
142 156 : }
143 : }
144 :
145 : use rand::distributions::{Distribution, Standard};
146 : impl Distribution<CancelKeyData> for Standard {
147 41 : fn sample<R: rand::Rng + ?Sized>(&self, rng: &mut R) -> CancelKeyData {
148 41 : CancelKeyData {
149 41 : backend_pid: rng.gen(),
150 41 : cancel_key: rng.gen(),
151 41 : }
152 41 : }
153 : }
154 :
155 : // We only support the simple case of Parse on unnamed prepared statement and
156 : // no params
157 0 : #[derive(Debug)]
158 : pub struct FeParseMessage {
159 : pub query_string: Bytes,
160 : }
161 :
162 0 : #[derive(Debug)]
163 : pub struct FeDescribeMessage {
164 : pub kind: u8, // 'S' to describe a prepared statement; or 'P' to describe a portal.
165 : // we only support unnamed prepared stmt or portal
166 : }
167 :
168 : // we only support unnamed prepared stmt and portal
169 0 : #[derive(Debug)]
170 : pub struct FeBindMessage;
171 :
172 : // we only support unnamed prepared stmt or portal
173 0 : #[derive(Debug)]
174 : pub struct FeExecuteMessage {
175 : /// max # of rows
176 : pub maxrows: i32,
177 : }
178 :
179 : // we only support unnamed prepared stmt and portal
180 0 : #[derive(Debug)]
181 : pub struct FeCloseMessage;
182 :
183 : /// An error occurred while parsing or serializing raw stream into Postgres
184 : /// messages.
185 5 : #[derive(thiserror::Error, Debug)]
186 : pub enum ProtocolError {
187 : /// Invalid packet was received from the client (e.g. unexpected message
188 : /// type or broken len).
189 : #[error("Protocol error: {0}")]
190 : Protocol(String),
191 : /// Failed to parse or, (unlikely), serialize a protocol message.
192 : #[error("Message parse error: {0}")]
193 : BadMessage(String),
194 : }
195 :
196 : impl ProtocolError {
197 : /// Proxy stream.rs uses only io::Error; provide it.
198 0 : pub fn into_io_error(self) -> io::Error {
199 0 : io::Error::new(io::ErrorKind::Other, self.to_string())
200 0 : }
201 : }
202 :
203 : impl FeMessage {
204 : /// Read and parse one message from the `buf` input buffer. If there is at
205 : /// least one valid message, returns it, advancing `buf`; redundant copies
206 : /// are avoided, as thanks to `bytes` crate ptrs in parsed message point
207 : /// directly into the `buf` (processed data is garbage collected after
208 : /// parsed message is dropped).
209 : ///
210 : /// Returns None if `buf` doesn't contain enough data for a single message.
211 : /// For efficiency, tries to reserve large enough space in `buf` for the
212 : /// next message in this case to save the repeated calls.
213 : ///
214 : /// Returns Error if message is malformed, the only possible ErrorKind is
215 : /// InvalidInput.
216 : //
217 : // Inspired by rust-postgres Message::parse.
218 17364276 : pub fn parse(buf: &mut BytesMut) -> Result<Option<FeMessage>, ProtocolError> {
219 17364276 : // Every message contains message type byte and 4 bytes len; can't do
220 17364276 : // much without them.
221 17364276 : if buf.len() < 5 {
222 7976138 : let to_read = 5 - buf.len();
223 7976138 : buf.reserve(to_read);
224 7976138 : return Ok(None);
225 9388138 : }
226 9388138 :
227 9388138 : // We shouldn't advance `buf` as probably full message is not there yet,
228 9388138 : // so can't directly use Bytes::get_u32 etc.
229 9388138 : let tag = buf[0];
230 9388138 : let len = (&buf[1..5]).read_u32::<BigEndian>().unwrap();
231 9388138 : if len < 4 {
232 0 : return Err(ProtocolError::Protocol(format!(
233 0 : "invalid message length {}",
234 0 : len
235 0 : )));
236 9388138 : }
237 9388138 :
238 9388138 : // length field includes itself, but not message type.
239 9388138 : let total_len = len as usize + 1;
240 9388138 : if buf.len() < total_len {
241 : // Don't have full message yet.
242 181429 : let to_read = total_len - buf.len();
243 181429 : buf.reserve(to_read);
244 181429 : return Ok(None);
245 9206709 : }
246 9206709 :
247 9206709 : // got the message, advance buffer
248 9206709 : let mut msg = buf.split_to(total_len).freeze();
249 9206709 : msg.advance(5); // consume message type and len
250 9206709 :
251 9206709 : match tag {
252 14154 : b'Q' => Ok(Some(FeMessage::Query(msg))),
253 632 : b'P' => Ok(Some(FeParseMessage::parse(msg)?)),
254 632 : b'D' => Ok(Some(FeDescribeMessage::parse(msg)?)),
255 632 : b'E' => Ok(Some(FeExecuteMessage::parse(msg)?)),
256 632 : b'B' => Ok(Some(FeBindMessage::parse(msg)?)),
257 631 : b'C' => Ok(Some(FeCloseMessage::parse(msg)?)),
258 1915 : b'S' => Ok(Some(FeMessage::Sync)),
259 2171 : b'X' => Ok(Some(FeMessage::Terminate)),
260 9184882 : b'd' => Ok(Some(FeMessage::CopyData(msg))),
261 14 : b'c' => Ok(Some(FeMessage::CopyDone)),
262 84 : b'f' => Ok(Some(FeMessage::CopyFail)),
263 330 : b'p' => Ok(Some(FeMessage::PasswordMessage(msg))),
264 0 : tag => Err(ProtocolError::Protocol(format!(
265 0 : "unknown message tag: {tag},'{msg:?}'"
266 0 : ))),
267 : }
268 17364276 : }
269 : }
270 :
271 : impl FeStartupPacket {
272 : /// Read and parse startup message from the `buf` input buffer. It is
273 : /// different from [`FeMessage::parse`] because startup messages don't have
274 : /// message type byte; otherwise, its comments apply.
275 52401 : pub fn parse(buf: &mut BytesMut) -> Result<Option<FeStartupPacket>, ProtocolError> {
276 52401 : const MAX_STARTUP_PACKET_LENGTH: usize = 10000;
277 52401 : const RESERVED_INVALID_MAJOR_VERSION: u32 = 1234;
278 52401 : const CANCEL_REQUEST_CODE: u32 = 5678;
279 52401 : const NEGOTIATE_SSL_CODE: u32 = 5679;
280 52401 : const NEGOTIATE_GSS_CODE: u32 = 5680;
281 52401 :
282 52401 : // need at least 4 bytes with packet len
283 52401 : if buf.len() < 4 {
284 26200 : let to_read = 4 - buf.len();
285 26200 : buf.reserve(to_read);
286 26200 : return Ok(None);
287 26201 : }
288 26201 :
289 26201 : // We shouldn't advance `buf` as probably full message is not there yet,
290 26201 : // so can't directly use Bytes::get_u32 etc.
291 26201 : let len = (&buf[0..4]).read_u32::<BigEndian>().unwrap() as usize;
292 26201 : // The proposed replacement is `!(8..=MAX_STARTUP_PACKET_LENGTH).contains(&len)`
293 26201 : // which is less readable
294 26201 : #[allow(clippy::manual_range_contains)]
295 26201 : if len < 8 || len > MAX_STARTUP_PACKET_LENGTH {
296 2 : return Err(ProtocolError::Protocol(format!(
297 2 : "invalid startup packet message length {}",
298 2 : len
299 2 : )));
300 26199 : }
301 26199 :
302 26199 : if buf.len() < len {
303 : // Don't have full message yet.
304 0 : let to_read = len - buf.len();
305 0 : buf.reserve(to_read);
306 0 : return Ok(None);
307 26199 : }
308 26199 :
309 26199 : // got the message, advance buffer
310 26199 : let mut msg = buf.split_to(len).freeze();
311 26199 : msg.advance(4); // consume len
312 26199 :
313 26199 : let request_code = msg.get_u32();
314 26199 : let req_hi = request_code >> 16;
315 26199 : let req_lo = request_code & ((1 << 16) - 1);
316 : // StartupMessage, CancelRequest, SSLRequest etc are differentiated by request code.
317 26199 : let message = match (req_hi, req_lo) {
318 : (RESERVED_INVALID_MAJOR_VERSION, CANCEL_REQUEST_CODE) => {
319 0 : if msg.remaining() != 8 {
320 0 : return Err(ProtocolError::BadMessage(
321 0 : "CancelRequest message is malformed, backend PID / secret key missing"
322 0 : .to_owned(),
323 0 : ));
324 0 : }
325 0 : FeStartupPacket::CancelRequest(CancelKeyData {
326 0 : backend_pid: msg.get_i32(),
327 0 : cancel_key: msg.get_i32(),
328 0 : })
329 : }
330 : (RESERVED_INVALID_MAJOR_VERSION, NEGOTIATE_SSL_CODE) => {
331 : // Requested upgrade to SSL (aka TLS)
332 12076 : FeStartupPacket::SslRequest
333 : }
334 : (RESERVED_INVALID_MAJOR_VERSION, NEGOTIATE_GSS_CODE) => {
335 : // Requested upgrade to GSSAPI
336 0 : FeStartupPacket::GssEncRequest
337 : }
338 0 : (RESERVED_INVALID_MAJOR_VERSION, unrecognized_code) => {
339 0 : return Err(ProtocolError::Protocol(format!(
340 0 : "Unrecognized request code {unrecognized_code}"
341 0 : )));
342 : }
343 : // TODO bail if protocol major_version is not 3?
344 14123 : (major_version, minor_version) => {
345 : // StartupMessage
346 :
347 : // Parse pairs of null-terminated strings (key, value).
348 : // See `postgres: ProcessStartupPacket, build_startup_packet`.
349 14123 : let mut tokens = str::from_utf8(&msg)
350 14123 : .map_err(|_e| {
351 0 : ProtocolError::BadMessage("StartupMessage params: invalid utf-8".to_owned())
352 14123 : })?
353 14123 : .strip_suffix('\0') // drop packet's own null
354 14123 : .ok_or_else(|| {
355 0 : ProtocolError::Protocol(
356 0 : "StartupMessage params: missing null terminator".to_string(),
357 0 : )
358 14123 : })?
359 14123 : .split_terminator('\0');
360 14123 :
361 14123 : let mut params = HashMap::new();
362 46596 : while let Some(name) = tokens.next() {
363 32473 : let value = tokens.next().ok_or_else(|| {
364 0 : ProtocolError::Protocol(
365 0 : "StartupMessage params: key without value".to_string(),
366 0 : )
367 32473 : })?;
368 :
369 32473 : params.insert(name.to_owned(), value.to_owned());
370 : }
371 :
372 14123 : FeStartupPacket::StartupMessage {
373 14123 : major_version,
374 14123 : minor_version,
375 14123 : params: StartupMessageParams { params },
376 14123 : }
377 : }
378 : };
379 26199 : Ok(Some(message))
380 52401 : }
381 : }
382 :
383 : impl FeParseMessage {
384 632 : fn parse(mut buf: Bytes) -> Result<FeMessage, ProtocolError> {
385 : // FIXME: the rust-postgres driver uses a named prepared statement
386 : // for copy_out(). We're not prepared to handle that correctly. For
387 : // now, just ignore the statement name, assuming that the client never
388 : // uses more than one prepared statement at a time.
389 :
390 632 : let _pstmt_name = read_cstr(&mut buf)?;
391 632 : let query_string = read_cstr(&mut buf)?;
392 632 : if buf.remaining() < 2 {
393 0 : return Err(ProtocolError::BadMessage(
394 0 : "Parse message is malformed, nparams missing".to_string(),
395 0 : ));
396 632 : }
397 632 : let nparams = buf.get_i16();
398 632 :
399 632 : if nparams != 0 {
400 0 : return Err(ProtocolError::BadMessage(
401 0 : "query params not implemented".to_string(),
402 0 : ));
403 632 : }
404 632 :
405 632 : Ok(FeMessage::Parse(FeParseMessage { query_string }))
406 632 : }
407 : }
408 :
409 : impl FeDescribeMessage {
410 632 : fn parse(mut buf: Bytes) -> Result<FeMessage, ProtocolError> {
411 632 : let kind = buf.get_u8();
412 632 : let _pstmt_name = read_cstr(&mut buf)?;
413 :
414 : // FIXME: see FeParseMessage::parse
415 632 : if kind != b'S' {
416 0 : return Err(ProtocolError::BadMessage(
417 0 : "only prepared statemement Describe is implemented".to_string(),
418 0 : ));
419 632 : }
420 632 :
421 632 : Ok(FeMessage::Describe(FeDescribeMessage { kind }))
422 632 : }
423 : }
424 :
425 : impl FeExecuteMessage {
426 632 : fn parse(mut buf: Bytes) -> Result<FeMessage, ProtocolError> {
427 632 : let portal_name = read_cstr(&mut buf)?;
428 632 : if buf.remaining() < 4 {
429 0 : return Err(ProtocolError::BadMessage(
430 0 : "FeExecuteMessage message is malformed, maxrows missing".to_string(),
431 0 : ));
432 632 : }
433 632 : let maxrows = buf.get_i32();
434 632 :
435 632 : if !portal_name.is_empty() {
436 0 : return Err(ProtocolError::BadMessage(
437 0 : "named portals not implemented".to_string(),
438 0 : ));
439 632 : }
440 632 : if maxrows != 0 {
441 0 : return Err(ProtocolError::BadMessage(
442 0 : "row limit in Execute message not implemented".to_string(),
443 0 : ));
444 632 : }
445 632 :
446 632 : Ok(FeMessage::Execute(FeExecuteMessage { maxrows }))
447 632 : }
448 : }
449 :
450 : impl FeBindMessage {
451 632 : fn parse(mut buf: Bytes) -> Result<FeMessage, ProtocolError> {
452 632 : let portal_name = read_cstr(&mut buf)?;
453 632 : let _pstmt_name = read_cstr(&mut buf)?;
454 :
455 : // FIXME: see FeParseMessage::parse
456 632 : if !portal_name.is_empty() {
457 0 : return Err(ProtocolError::BadMessage(
458 0 : "named portals not implemented".to_string(),
459 0 : ));
460 632 : }
461 632 :
462 632 : Ok(FeMessage::Bind(FeBindMessage))
463 632 : }
464 : }
465 :
466 : impl FeCloseMessage {
467 631 : fn parse(mut buf: Bytes) -> Result<FeMessage, ProtocolError> {
468 631 : let _kind = buf.get_u8();
469 631 : let _pstmt_or_portal_name = read_cstr(&mut buf)?;
470 :
471 : // FIXME: we do nothing with Close
472 631 : Ok(FeMessage::Close(FeCloseMessage))
473 631 : }
474 : }
475 :
476 : // Backend
477 :
478 0 : #[derive(Debug)]
479 : pub enum BeMessage<'a> {
480 : AuthenticationOk,
481 : AuthenticationMD5Password([u8; 4]),
482 : AuthenticationSasl(BeAuthenticationSaslMessage<'a>),
483 : AuthenticationCleartextPassword,
484 : BackendKeyData(CancelKeyData),
485 : BindComplete,
486 : CommandComplete(&'a [u8]),
487 : CopyData(&'a [u8]),
488 : CopyDone,
489 : CopyFail,
490 : CopyInResponse,
491 : CopyOutResponse,
492 : CopyBothResponse,
493 : CloseComplete,
494 : // None means column is NULL
495 : DataRow(&'a [Option<&'a [u8]>]),
496 : // None errcode means internal_error will be sent.
497 : ErrorResponse(&'a str, Option<&'a [u8; 5]>),
498 : /// Single byte - used in response to SSLRequest/GSSENCRequest.
499 : EncryptionResponse(bool),
500 : NoData,
501 : ParameterDescription,
502 : ParameterStatus {
503 : name: &'a [u8],
504 : value: &'a [u8],
505 : },
506 : ParseComplete,
507 : ReadyForQuery,
508 : RowDescription(&'a [RowDescriptor<'a>]),
509 : XLogData(XLogDataBody<'a>),
510 : NoticeResponse(&'a str),
511 : KeepAlive(WalSndKeepAlive),
512 : }
513 :
514 : /// Common shorthands.
515 : impl<'a> BeMessage<'a> {
516 : /// A [`BeMessage::ParameterStatus`] holding the client encoding, i.e. UTF-8.
517 : /// This is a sensible default, given that:
518 : /// * rust strings only support this encoding out of the box.
519 : /// * tokio-postgres, postgres-jdbc (and probably more) mandate it.
520 : ///
521 : /// TODO: do we need to report `server_encoding` as well?
522 : pub const CLIENT_ENCODING: Self = Self::ParameterStatus {
523 : name: b"client_encoding",
524 : value: b"UTF8",
525 : };
526 :
527 : pub const INTEGER_DATETIMES: Self = Self::ParameterStatus {
528 : name: b"integer_datetimes",
529 : value: b"on",
530 : };
531 :
532 : /// Build a [`BeMessage::ParameterStatus`] holding the server version.
533 13802 : pub fn server_version(version: &'a str) -> Self {
534 13802 : Self::ParameterStatus {
535 13802 : name: b"server_version",
536 13802 : value: version.as_bytes(),
537 13802 : }
538 13802 : }
539 : }
540 :
541 0 : #[derive(Debug)]
542 : pub enum BeAuthenticationSaslMessage<'a> {
543 : Methods(&'a [&'a str]),
544 : Continue(&'a [u8]),
545 : Final(&'a [u8]),
546 : }
547 :
548 0 : #[derive(Debug)]
549 : pub enum BeParameterStatusMessage<'a> {
550 : Encoding(&'a str),
551 : ServerVersion(&'a str),
552 : }
553 :
554 : // One row description in RowDescription packet.
555 0 : #[derive(Debug)]
556 : pub struct RowDescriptor<'a> {
557 : pub name: &'a [u8],
558 : pub tableoid: Oid,
559 : pub attnum: i16,
560 : pub typoid: Oid,
561 : pub typlen: i16,
562 : pub typmod: i32,
563 : pub formatcode: i16,
564 : }
565 :
566 : impl Default for RowDescriptor<'_> {
567 3023 : fn default() -> RowDescriptor<'static> {
568 3023 : RowDescriptor {
569 3023 : name: b"",
570 3023 : tableoid: 0,
571 3023 : attnum: 0,
572 3023 : typoid: 0,
573 3023 : typlen: 0,
574 3023 : typmod: 0,
575 3023 : formatcode: 0,
576 3023 : }
577 3023 : }
578 : }
579 :
580 : impl RowDescriptor<'_> {
581 : /// Convenience function to create a RowDescriptor message for an int8 column
582 45 : pub const fn int8_col(name: &[u8]) -> RowDescriptor {
583 45 : RowDescriptor {
584 45 : name,
585 45 : tableoid: 0,
586 45 : attnum: 0,
587 45 : typoid: INT8_OID,
588 45 : typlen: 8,
589 45 : typmod: 0,
590 45 : formatcode: 0,
591 45 : }
592 45 : }
593 :
594 1340 : pub const fn text_col(name: &[u8]) -> RowDescriptor {
595 1340 : RowDescriptor {
596 1340 : name,
597 1340 : tableoid: 0,
598 1340 : attnum: 0,
599 1340 : typoid: TEXT_OID,
600 1340 : typlen: -1,
601 1340 : typmod: 0,
602 1340 : formatcode: 0,
603 1340 : }
604 1340 : }
605 : }
606 :
607 0 : #[derive(Debug)]
608 : pub struct XLogDataBody<'a> {
609 : pub wal_start: u64,
610 : pub wal_end: u64, // current end of WAL on the server
611 : pub timestamp: i64,
612 : pub data: &'a [u8],
613 : }
614 :
615 0 : #[derive(Debug)]
616 : pub struct WalSndKeepAlive {
617 : pub wal_end: u64, // current end of WAL on the server
618 : pub timestamp: i64,
619 : pub request_reply: bool,
620 : }
621 :
622 : pub static HELLO_WORLD_ROW: BeMessage = BeMessage::DataRow(&[Some(b"hello world")]);
623 :
624 : // single text column
625 : pub static SINGLE_COL_ROWDESC: BeMessage = BeMessage::RowDescription(&[RowDescriptor {
626 : name: b"data",
627 : tableoid: 0,
628 : attnum: 0,
629 : typoid: TEXT_OID,
630 : typlen: -1,
631 : typmod: 0,
632 : formatcode: 0,
633 : }]);
634 :
635 : /// Call f() to write body of the message and prepend it with 4-byte len as
636 : /// prescribed by the protocol.
637 9170234 : fn write_body<R>(buf: &mut BytesMut, f: impl FnOnce(&mut BytesMut) -> R) -> R {
638 9170234 : let base = buf.len();
639 9170234 : buf.extend_from_slice(&[0; 4]);
640 9170234 :
641 9170234 : let res = f(buf);
642 9170234 :
643 9170234 : let size = i32::try_from(buf.len() - base).expect("message too big to transmit");
644 9170234 : (&mut buf[base..]).put_slice(&size.to_be_bytes());
645 9170234 :
646 9170234 : res
647 9170234 : }
648 :
649 : /// Safe write of s into buf as cstring (String in the protocol).
650 91192 : fn write_cstr(s: impl AsRef<[u8]>, buf: &mut BytesMut) -> Result<(), ProtocolError> {
651 91192 : let bytes = s.as_ref();
652 91192 : if bytes.contains(&0) {
653 0 : return Err(ProtocolError::BadMessage(
654 0 : "string contains embedded null".to_owned(),
655 0 : ));
656 91192 : }
657 91192 : buf.put_slice(bytes);
658 91192 : buf.put_u8(0);
659 91192 : Ok(())
660 91192 : }
661 :
662 : /// Read cstring from buf, advancing it.
663 3981565 : pub fn read_cstr(buf: &mut Bytes) -> Result<Bytes, ProtocolError> {
664 3981565 : let pos = buf
665 3981565 : .iter()
666 56536644 : .position(|x| *x == 0)
667 3981565 : .ok_or_else(|| ProtocolError::BadMessage("missing cstring terminator".to_owned()))?;
668 3981565 : let result = buf.split_to(pos);
669 3981565 : buf.advance(1); // drop the null terminator
670 3981565 : Ok(result)
671 3981565 : }
672 :
673 : pub const SQLSTATE_INTERNAL_ERROR: &[u8; 5] = b"XX000";
674 : pub const SQLSTATE_ADMIN_SHUTDOWN: &[u8; 5] = b"57P01";
675 : pub const SQLSTATE_SUCCESSFUL_COMPLETION: &[u8; 5] = b"00000";
676 :
677 : impl<'a> BeMessage<'a> {
678 : /// Serialize `message` to the given `buf`.
679 : /// Apart from smart memory managemet, BytesMut is good here as msg len
680 : /// precedes its body and it is handy to write it down first and then fill
681 : /// the length. With Write we would have to either calc it manually or have
682 : /// one more buffer.
683 9182310 : pub fn write(buf: &mut BytesMut, message: &BeMessage) -> Result<(), ProtocolError> {
684 9182310 : match message {
685 14065 : BeMessage::AuthenticationOk => {
686 14065 : buf.put_u8(b'R');
687 14065 : write_body(buf, |buf| {
688 14065 : buf.put_i32(0); // Specifies that the authentication was successful.
689 14065 : });
690 14065 : }
691 :
692 219 : BeMessage::AuthenticationCleartextPassword => {
693 219 : buf.put_u8(b'R');
694 219 : write_body(buf, |buf| {
695 219 : buf.put_i32(3); // Specifies that clear text password is required.
696 219 : });
697 219 : }
698 :
699 0 : BeMessage::AuthenticationMD5Password(salt) => {
700 0 : buf.put_u8(b'R');
701 0 : write_body(buf, |buf| {
702 0 : buf.put_i32(5); // Specifies that an MD5-encrypted password is required.
703 0 : buf.put_slice(&salt[..]);
704 0 : });
705 0 : }
706 :
707 162 : BeMessage::AuthenticationSasl(msg) => {
708 162 : buf.put_u8(b'R');
709 162 : write_body(buf, |buf| {
710 162 : use BeAuthenticationSaslMessage::*;
711 162 : match msg {
712 61 : Methods(methods) => {
713 61 : buf.put_i32(10); // Specifies that SASL auth method is used.
714 122 : for method in methods.iter() {
715 122 : write_cstr(method, buf)?;
716 : }
717 61 : buf.put_u8(0); // zero terminator for the list
718 : }
719 57 : Continue(extra) => {
720 57 : buf.put_i32(11); // Continue SASL auth.
721 57 : buf.put_slice(extra);
722 57 : }
723 44 : Final(extra) => {
724 44 : buf.put_i32(12); // Send final SASL message.
725 44 : buf.put_slice(extra);
726 44 : }
727 : }
728 162 : Ok(())
729 162 : })?;
730 : }
731 :
732 39 : BeMessage::BackendKeyData(key_data) => {
733 39 : buf.put_u8(b'K');
734 39 : write_body(buf, |buf| {
735 39 : buf.put_i32(key_data.backend_pid);
736 39 : buf.put_i32(key_data.cancel_key);
737 39 : });
738 39 : }
739 :
740 632 : BeMessage::BindComplete => {
741 632 : buf.put_u8(b'2');
742 632 : write_body(buf, |_| {});
743 632 : }
744 :
745 631 : BeMessage::CloseComplete => {
746 631 : buf.put_u8(b'3');
747 631 : write_body(buf, |_| {});
748 631 : }
749 :
750 2079 : BeMessage::CommandComplete(cmd) => {
751 2079 : buf.put_u8(b'C');
752 2079 : write_body(buf, |buf| write_cstr(cmd, buf))?;
753 : }
754 :
755 8240821 : BeMessage::CopyData(data) => {
756 8240821 : buf.put_u8(b'd');
757 8240821 : write_body(buf, |buf| {
758 8240821 : buf.put_slice(data);
759 8240821 : });
760 8240821 : }
761 :
762 597 : BeMessage::CopyDone => {
763 597 : buf.put_u8(b'c');
764 597 : write_body(buf, |_| {});
765 597 : }
766 :
767 0 : BeMessage::CopyFail => {
768 0 : buf.put_u8(b'f');
769 0 : write_body(buf, |_| {});
770 0 : }
771 :
772 15 : BeMessage::CopyInResponse => {
773 15 : buf.put_u8(b'G');
774 15 : write_body(buf, |buf| {
775 15 : buf.put_u8(1); // copy_is_binary
776 15 : buf.put_i16(0); // numAttributes
777 15 : });
778 15 : }
779 :
780 609 : BeMessage::CopyOutResponse => {
781 609 : buf.put_u8(b'H');
782 609 : write_body(buf, |buf| {
783 609 : buf.put_u8(0); // copy_is_binary
784 609 : buf.put_i16(0); // numAttributes
785 609 : });
786 609 : }
787 :
788 12638 : BeMessage::CopyBothResponse => {
789 12638 : buf.put_u8(b'W');
790 12638 : write_body(buf, |buf| {
791 12638 : // doesn't matter, used only for replication
792 12638 : buf.put_u8(0); // copy_is_binary
793 12638 : buf.put_i16(0); // numAttributes
794 12638 : });
795 12638 : }
796 :
797 965 : BeMessage::DataRow(vals) => {
798 965 : buf.put_u8(b'D');
799 965 : write_body(buf, |buf| {
800 965 : buf.put_u16(vals.len() as u16); // num of cols
801 3465 : for val_opt in vals.iter() {
802 3465 : if let Some(val) = val_opt {
803 2710 : buf.put_u32(val.len() as u32);
804 2710 : buf.put_slice(val);
805 2710 : } else {
806 755 : buf.put_i32(-1);
807 755 : }
808 : }
809 965 : });
810 965 : }
811 :
812 : // ErrorResponse is a zero-terminated array of zero-terminated fields.
813 : // First byte of each field represents type of this field. Set just enough fields
814 : // to satisfy rust-postgres client: 'S' -- severity, 'C' -- error, 'M' -- error
815 : // message text.
816 294 : BeMessage::ErrorResponse(error_msg, pg_error_code) => {
817 294 : // 'E' signalizes ErrorResponse messages
818 294 : buf.put_u8(b'E');
819 294 : write_body(buf, |buf| {
820 294 : buf.put_u8(b'S'); // severity
821 294 : buf.put_slice(b"ERROR\0");
822 294 :
823 294 : buf.put_u8(b'C'); // SQLSTATE error code
824 294 : buf.put_slice(&terminate_code(
825 294 : pg_error_code.unwrap_or(SQLSTATE_INTERNAL_ERROR),
826 294 : ));
827 294 :
828 294 : buf.put_u8(b'M'); // the message
829 294 : write_cstr(error_msg, buf)?;
830 :
831 294 : buf.put_u8(0); // terminator
832 294 : Ok(())
833 294 : })?;
834 : }
835 :
836 : // NoticeResponse has the same format as ErrorResponse. From doc: "The frontend should display the
837 : // message but continue listening for ReadyForQuery or ErrorResponse"
838 6 : BeMessage::NoticeResponse(error_msg) => {
839 6 : // For all the errors set Severity to Error and error code to
840 6 : // 'internal error'.
841 6 :
842 6 : // 'N' signalizes NoticeResponse messages
843 6 : buf.put_u8(b'N');
844 6 : write_body(buf, |buf| {
845 6 : buf.put_u8(b'S'); // severity
846 6 : buf.put_slice(b"NOTICE\0");
847 6 :
848 6 : buf.put_u8(b'C'); // SQLSTATE error code
849 6 : buf.put_slice(&terminate_code(SQLSTATE_INTERNAL_ERROR));
850 6 :
851 6 : buf.put_u8(b'M'); // the message
852 6 : write_cstr(error_msg.as_bytes(), buf)?;
853 :
854 6 : buf.put_u8(0); // terminator
855 6 : Ok(())
856 6 : })?;
857 : }
858 :
859 632 : BeMessage::NoData => {
860 632 : buf.put_u8(b'n');
861 632 : write_body(buf, |_| {});
862 632 : }
863 :
864 12076 : BeMessage::EncryptionResponse(should_negotiate) => {
865 12076 : let response = if *should_negotiate { b'S' } else { b'N' };
866 12076 : buf.put_u8(response);
867 : }
868 :
869 42140 : BeMessage::ParameterStatus { name, value } => {
870 42140 : buf.put_u8(b'S');
871 42140 : write_body(buf, |buf| {
872 42140 : write_cstr(name, buf)?;
873 42140 : write_cstr(value, buf)
874 42140 : })?;
875 : }
876 :
877 632 : BeMessage::ParameterDescription => {
878 632 : buf.put_u8(b't');
879 632 : write_body(buf, |buf| {
880 632 : // we don't support params, so always 0
881 632 : buf.put_i16(0);
882 632 : });
883 632 : }
884 :
885 632 : BeMessage::ParseComplete => {
886 632 : buf.put_u8(b'1');
887 632 : write_body(buf, |_| {});
888 632 : }
889 :
890 29495 : BeMessage::ReadyForQuery => {
891 29495 : buf.put_u8(b'Z');
892 29495 : write_body(buf, |buf| {
893 29495 : buf.put_u8(b'I');
894 29495 : });
895 29495 : }
896 :
897 1438 : BeMessage::RowDescription(rows) => {
898 1438 : buf.put_u8(b'T');
899 1438 : write_body(buf, |buf| {
900 1438 : buf.put_i16(rows.len() as i16); // # of fields
901 4411 : for row in rows.iter() {
902 4411 : write_cstr(row.name, buf)?;
903 4411 : buf.put_i32(0); /* table oid */
904 4411 : buf.put_i16(0); /* attnum */
905 4411 : buf.put_u32(row.typoid);
906 4411 : buf.put_i16(row.typlen);
907 4411 : buf.put_i32(-1); /* typmod */
908 4411 : buf.put_i16(0); /* format code */
909 : }
910 1438 : Ok(())
911 1438 : })?;
912 : }
913 :
914 818191 : BeMessage::XLogData(body) => {
915 818191 : buf.put_u8(b'd');
916 818191 : write_body(buf, |buf| {
917 818191 : buf.put_u8(b'w');
918 818191 : buf.put_u64(body.wal_start);
919 818191 : buf.put_u64(body.wal_end);
920 818191 : buf.put_i64(body.timestamp);
921 818191 : buf.put_slice(body.data);
922 818191 : });
923 818191 : }
924 :
925 3302 : BeMessage::KeepAlive(req) => {
926 3302 : buf.put_u8(b'd');
927 3302 : write_body(buf, |buf| {
928 3302 : buf.put_u8(b'k');
929 3302 : buf.put_u64(req.wal_end);
930 3302 : buf.put_i64(req.timestamp);
931 3302 : buf.put_u8(u8::from(req.request_reply));
932 3302 : });
933 3302 : }
934 : }
935 9182310 : Ok(())
936 9182310 : }
937 : }
938 :
939 300 : fn terminate_code(code: &[u8; 5]) -> [u8; 6] {
940 300 : let mut terminated = [0; 6];
941 1500 : for (i, &elem) in code.iter().enumerate() {
942 1500 : terminated[i] = elem;
943 1500 : }
944 :
945 300 : terminated
946 300 : }
947 :
948 : #[cfg(test)]
949 : mod tests {
950 : use super::*;
951 :
952 2 : #[test]
953 2 : fn test_startup_message_params_options_escaped() {
954 8 : fn split_options(params: &StartupMessageParams) -> Vec<Cow<'_, str>> {
955 8 : params
956 8 : .options_escaped()
957 8 : .expect("options are None")
958 8 : .collect()
959 8 : }
960 2 :
961 8 : let make_params = |options| StartupMessageParams::new([("options", options)]);
962 :
963 2 : let params = StartupMessageParams::new([]);
964 2 : assert!(params.options_escaped().is_none());
965 :
966 2 : let params = make_params("");
967 2 : assert!(split_options(¶ms).is_empty());
968 :
969 2 : let params = make_params("foo");
970 2 : assert_eq!(split_options(¶ms), ["foo"]);
971 :
972 2 : let params = make_params(" foo bar ");
973 2 : assert_eq!(split_options(¶ms), ["foo", "bar"]);
974 :
975 2 : let params = make_params("foo\\ bar \\ \\\\ baz\\ lol");
976 2 : assert_eq!(split_options(¶ms), ["foo bar", " \\", "baz ", "lol"]);
977 2 : }
978 :
979 2 : #[test]
980 2 : fn parse_fe_startup_packet_regression() {
981 2 : let data = [0, 0, 0, 7, 0, 0, 0, 0];
982 2 : FeStartupPacket::parse(&mut BytesMut::from_iter(data)).unwrap_err();
983 2 : }
984 : }
|