1use crate::error::Error;
5use crate::types::Type;
6
7pub(crate) const PROTOCOL_3_0: i32 = 196_608;
8const SSL_REQUEST: i32 = 80_877_103;
9const CANCEL_REQUEST: i32 = 80_877_102;
10
11pub(crate) const MAX_PARAMS: usize = u16::MAX as usize;
14
15fn message(out: &mut Vec<u8>, tag: u8, body: impl FnOnce(&mut Vec<u8>)) -> Result<(), Error> {
20 out.push(tag);
21 framed(out, body)
22}
23
24fn framed(out: &mut Vec<u8>, body: impl FnOnce(&mut Vec<u8>)) -> Result<(), Error> {
26 let start = out.len();
27 out.extend_from_slice(&[0; 4]);
28 body(out);
29 let len = i32::try_from(out.len() - start)
30 .map_err(|_| Error::conversion("a message to the server would be larger than 2 GiB"))?;
31 out[start..start + 4].copy_from_slice(&len.to_be_bytes());
32 Ok(())
33}
34
35fn cstr(out: &mut Vec<u8>, s: &str) {
37 out.extend_from_slice(s.as_bytes());
38 out.push(0);
39}
40
41pub(crate) fn check_text(what: &str, s: &str) -> Result<(), Error> {
43 if s.as_bytes().contains(&0) {
44 return Err(Error::conversion(format!(
45 "{what} contains a NUL byte, which PostgreSQL cannot store in text; \
46 remove it, or use bytea and &[u8] for binary data"
47 )));
48 }
49 Ok(())
50}
51
52pub(crate) fn startup(out: &mut Vec<u8>, params: &[(&str, &str)]) -> Result<(), Error> {
53 for (name, value) in params {
54 check_text("a connection parameter", name)?;
55 check_text("a connection parameter", value)?;
56 }
57 framed(out, |out| {
58 out.extend_from_slice(&PROTOCOL_3_0.to_be_bytes());
59 for (name, value) in params {
60 cstr(out, name);
61 cstr(out, value);
62 }
63 out.push(0);
64 })
65}
66
67pub(crate) fn ssl_request(out: &mut Vec<u8>) {
68 out.extend_from_slice(&8i32.to_be_bytes());
69 out.extend_from_slice(&SSL_REQUEST.to_be_bytes());
70}
71
72pub(crate) fn cancel_request(out: &mut Vec<u8>, process_id: i32, secret_key: i32) {
73 out.extend_from_slice(&16i32.to_be_bytes());
74 out.extend_from_slice(&CANCEL_REQUEST.to_be_bytes());
75 out.extend_from_slice(&process_id.to_be_bytes());
76 out.extend_from_slice(&secret_key.to_be_bytes());
77}
78
79pub(crate) fn password(out: &mut Vec<u8>, data: &[u8]) -> Result<(), Error> {
81 message(out, b'p', |out| out.extend_from_slice(data))
82}
83
84pub(crate) fn sasl_initial_response(
85 out: &mut Vec<u8>,
86 mechanism: &str,
87 data: &[u8],
88) -> Result<(), Error> {
89 message(out, b'p', |out| {
90 cstr(out, mechanism);
91 out.extend_from_slice(&(data.len() as i32).to_be_bytes());
92 out.extend_from_slice(data);
93 })
94}
95
96pub(crate) fn query(out: &mut Vec<u8>, sql: &str) -> Result<(), Error> {
99 check_text("the SQL text", sql)?;
100 message(out, b'Q', |out| cstr(out, sql))
101}
102
103pub(crate) fn parse(out: &mut Vec<u8>, name: &str, sql: &str) -> Result<(), Error> {
106 check_text("the SQL text", sql)?;
107 message(out, b'P', |out| {
108 cstr(out, name);
109 cstr(out, sql);
110 out.extend_from_slice(&0i16.to_be_bytes());
111 })
112}
113
114pub(crate) fn describe_statement(out: &mut Vec<u8>, name: &str) -> Result<(), Error> {
115 message(out, b'D', |out| {
116 out.push(b'S');
117 cstr(out, name);
118 })
119}
120
121pub(crate) fn execute(out: &mut Vec<u8>) -> Result<(), Error> {
123 message(out, b'E', |out| {
124 out.push(0);
125 out.extend_from_slice(&0i32.to_be_bytes());
126 })
127}
128
129pub(crate) fn close_statement(out: &mut Vec<u8>, name: &str) -> Result<(), Error> {
130 message(out, b'C', |out| {
131 out.push(b'S');
132 cstr(out, name);
133 })
134}
135
136pub(crate) fn sync(out: &mut Vec<u8>) {
137 out.extend_from_slice(&[b'S', 0, 0, 0, 4]);
138}
139
140pub(crate) fn terminate(out: &mut Vec<u8>) {
141 out.extend_from_slice(&[b'X', 0, 0, 0, 4]);
142}
143
144#[derive(Clone, Copy, Debug, PartialEq, Eq)]
146pub enum Encoded {
147 Null,
149 Binary,
151 Text,
154}
155
156pub(crate) fn bind(
160 out: &mut Vec<u8>,
161 statement: &str,
162 params: usize,
163 mut encode: impl FnMut(usize, &mut Vec<u8>) -> Result<Encoded, Error>,
164 binary_results: impl ExactSizeIterator<Item = bool>,
165) -> Result<(), Error> {
166 debug_assert!(params <= MAX_PARAMS);
167 out.push(b'B');
168 let start = out.len();
169 out.extend_from_slice(&[0; 4]);
170 out.push(0); cstr(out, statement);
172 out.extend_from_slice(&(params as u16).to_be_bytes());
175 let formats = out.len();
176 out.resize(formats + 2 * params, 0);
177 out.extend_from_slice(&(params as u16).to_be_bytes());
178 for i in 0..params {
179 let at = out.len();
180 out.extend_from_slice(&[0; 4]);
181 let len = match encode(i, out)? {
182 Encoded::Null => {
183 out.truncate(at + 4);
184 -1i32
185 }
186 how => {
187 if how == Encoded::Binary {
188 out[formats + 2 * i + 1] = 1;
189 }
190 i32::try_from(out.len() - at - 4).map_err(|_| {
191 Error::conversion(format!("parameter ${} is larger than 2 GiB", i + 1))
192 })?
193 }
194 };
195 out[at..at + 4].copy_from_slice(&len.to_be_bytes());
196 }
197 out.extend_from_slice(&(binary_results.len() as u16).to_be_bytes());
198 for binary in binary_results {
199 out.extend_from_slice(&(binary as i16).to_be_bytes());
200 }
201 let len = i32::try_from(out.len() - start)
202 .map_err(|_| Error::conversion("the parameters add up to more than 2 GiB"))?;
203 out[start..start + 4].copy_from_slice(&len.to_be_bytes());
204 Ok(())
205}
206
207#[derive(Debug, PartialEq)]
211pub(crate) enum Backend<'a> {
212 AuthenticationOk,
213 AuthenticationCleartextPassword,
214 AuthenticationMd5Password([u8; 4]),
215 AuthenticationSasl(Vec<&'a str>),
216 AuthenticationSaslContinue(&'a [u8]),
217 AuthenticationSaslFinal(&'a [u8]),
218 AuthenticationOther(i32),
220 KeyData {
221 process_id: i32,
222 secret_key: i32,
223 },
224 BindComplete,
225 CloseComplete,
226 CommandComplete(&'a str),
227 CopyData,
228 CopyDone,
229 CopyInResponse,
230 CopyOutResponse,
231 CopyBothResponse,
232 DataRow(&'a [u8]),
234 EmptyQueryResponse,
235 ErrorResponse(&'a [u8]),
237 NegotiateProtocolVersion,
238 NoData,
239 NoticeResponse,
240 NotificationResponse,
241 ParameterDescription(Vec<Type>),
242 ParameterStatus {
243 name: &'a str,
244 value: &'a str,
245 },
246 ParseComplete,
247 PortalSuspended,
248 ReadyForQuery(u8),
249 RowDescription(Vec<FieldDescription<'a>>),
250}
251
252#[derive(Debug, PartialEq)]
254pub(crate) struct FieldDescription<'a> {
255 pub name: &'a str,
256 pub table_oid: u32,
257 pub column_id: i16,
258 pub type_oid: u32,
259}
260
261pub(crate) fn frame(buf: &[u8]) -> Result<Option<(u8, usize)>, Error> {
264 if buf.len() < 5 {
265 return Ok(None);
266 }
267 let len = i32::from_be_bytes([buf[1], buf[2], buf[3], buf[4]]);
268 if len < 4 {
269 return Err(Error::protocol(format!(
270 "the server sent a message ({:?}) with an invalid length {len}",
271 buf[0] as char
272 )));
273 }
274 Ok(Some((buf[0], len as usize + 1)))
275}
276
277struct Cursor<'a> {
279 buf: &'a [u8],
280 what: &'static str,
281}
282
283impl<'a> Cursor<'a> {
284 fn new(buf: &'a [u8], what: &'static str) -> Self {
285 Self { buf, what }
286 }
287
288 fn bad(&self) -> Error {
289 Error::protocol(format!("the server sent a malformed {} message", self.what))
290 }
291
292 fn bytes(&mut self, n: usize) -> Result<&'a [u8], Error> {
293 if self.buf.len() < n {
294 return Err(self.bad());
295 }
296 let (head, tail) = self.buf.split_at(n);
297 self.buf = tail;
298 Ok(head)
299 }
300
301 fn u8(&mut self) -> Result<u8, Error> {
302 Ok(self.bytes(1)?[0])
303 }
304
305 fn i16(&mut self) -> Result<i16, Error> {
306 let b = self.bytes(2)?;
307 Ok(i16::from_be_bytes([b[0], b[1]]))
308 }
309
310 fn i32(&mut self) -> Result<i32, Error> {
311 let b = self.bytes(4)?;
312 Ok(i32::from_be_bytes([b[0], b[1], b[2], b[3]]))
313 }
314
315 fn cstr(&mut self) -> Result<&'a str, Error> {
316 let end = self
317 .buf
318 .iter()
319 .position(|&b| b == 0)
320 .ok_or_else(|| self.bad())?;
321 let s = std::str::from_utf8(&self.buf[..end]).map_err(|_| self.bad())?;
322 self.buf = &self.buf[end + 1..];
323 Ok(s)
324 }
325
326 fn rest(&mut self) -> &'a [u8] {
327 std::mem::take(&mut self.buf)
328 }
329
330 fn end(&self) -> Result<(), Error> {
331 if self.buf.is_empty() {
332 Ok(())
333 } else {
334 Err(self.bad())
335 }
336 }
337}
338
339pub(crate) fn parse_backend(tag: u8, body: &[u8]) -> Result<Backend<'_>, Error> {
341 use Backend::*;
342 let empty = |m: Backend<'static>, what| {
343 if body.is_empty() {
344 Ok(m)
345 } else {
346 Err(Cursor::new(body, what).bad())
347 }
348 };
349 match tag {
350 b'R' => {
351 let mut c = Cursor::new(body, "authentication");
352 let msg = match c.i32()? {
353 0 => AuthenticationOk,
354 3 => AuthenticationCleartextPassword,
355 5 => {
356 let salt = c.bytes(4)?;
357 AuthenticationMd5Password([salt[0], salt[1], salt[2], salt[3]])
358 }
359 10 => {
360 let mut mechanisms = Vec::new();
361 loop {
362 let m = c.cstr()?;
363 if m.is_empty() {
364 break;
365 }
366 mechanisms.push(m);
367 }
368 AuthenticationSasl(mechanisms)
369 }
370 11 => return Ok(AuthenticationSaslContinue(c.rest())),
371 12 => return Ok(AuthenticationSaslFinal(c.rest())),
372 other => return Ok(AuthenticationOther(other)),
373 };
374 c.end()?;
375 Ok(msg)
376 }
377 b'K' => {
378 let mut c = Cursor::new(body, "BackendKeyData");
379 let process_id = c.i32()?;
380 let secret_key = c.i32()?;
381 c.end()?;
384 Ok(KeyData {
385 process_id,
386 secret_key,
387 })
388 }
389 b'2' => empty(BindComplete, "BindComplete"),
390 b'3' => empty(CloseComplete, "CloseComplete"),
391 b'C' => {
392 let mut c = Cursor::new(body, "CommandComplete");
393 let tag = c.cstr()?;
394 c.end()?;
395 Ok(CommandComplete(tag))
396 }
397 b'd' => Ok(CopyData),
398 b'c' => empty(CopyDone, "CopyDone"),
399 b'G' => Ok(CopyInResponse),
400 b'H' => Ok(CopyOutResponse),
401 b'W' => Ok(CopyBothResponse),
402 b'D' => Ok(DataRow(body)),
403 b'I' => empty(EmptyQueryResponse, "EmptyQueryResponse"),
404 b'E' => Ok(ErrorResponse(body)),
405 b'v' => Ok(NegotiateProtocolVersion),
406 b'n' => empty(NoData, "NoData"),
407 b'N' => Ok(NoticeResponse),
408 b'A' => Ok(NotificationResponse),
409 b't' => {
410 let mut c = Cursor::new(body, "ParameterDescription");
411 let n = c.i16()? as u16 as usize;
412 let mut types = Vec::with_capacity(n);
413 for _ in 0..n {
414 types.push(Type::from_oid(c.i32()? as u32));
415 }
416 c.end()?;
417 Ok(ParameterDescription(types))
418 }
419 b'S' => {
420 let mut c = Cursor::new(body, "ParameterStatus");
421 let name = c.cstr()?;
422 let value = c.cstr()?;
423 c.end()?;
424 Ok(ParameterStatus { name, value })
425 }
426 b'1' => empty(ParseComplete, "ParseComplete"),
427 b's' => empty(PortalSuspended, "PortalSuspended"),
428 b'Z' => {
429 let mut c = Cursor::new(body, "ReadyForQuery");
430 let status = c.u8()?;
431 c.end()?;
432 if !matches!(status, b'I' | b'T' | b'E') {
433 return Err(c.bad());
434 }
435 Ok(ReadyForQuery(status))
436 }
437 b'T' => {
438 let mut c = Cursor::new(body, "RowDescription");
439 let n = c.i16()? as u16 as usize;
440 let mut fields = Vec::with_capacity(n.min(1024));
441 for _ in 0..n {
442 let name = c.cstr()?;
443 let table_oid = c.i32()? as u32;
444 let column_id = c.i16()?;
445 let type_oid = c.i32()? as u32;
446 let _size = c.i16()?;
447 let _modifier = c.i32()?;
448 let _format = c.i16()?;
449 fields.push(FieldDescription {
450 name,
451 table_oid,
452 column_id,
453 type_oid,
454 });
455 }
456 c.end()?;
457 Ok(RowDescription(fields))
458 }
459 other => Err(Error::protocol(format!(
460 "the server sent a message of unknown type {:?}",
461 other as char
462 ))),
463 }
464}
465
466pub(crate) fn data_row(
470 body: &[u8],
471 columns: usize,
472 mut value: impl FnMut(Option<std::ops::Range<usize>>),
473) -> Result<(), Error> {
474 let mut c = Cursor::new(body, "DataRow");
475 let n = c.i16()? as u16 as usize;
476 if n != columns {
477 return Err(Error::protocol(format!(
478 "the server sent a row with {n} values for a statement with {columns} columns"
479 )));
480 }
481 for _ in 0..n {
482 let len = c.i32()?;
483 if len == -1 {
484 value(None);
485 continue;
486 }
487 if len < 0 {
488 return Err(c.bad());
489 }
490 let at = body.len() - c.buf.len();
491 c.bytes(len as usize)?;
492 value(Some(at..at + len as usize));
493 }
494 c.end()
495}
496
497#[cfg(test)]
498mod tests {
499 use super::*;
500
501 #[test]
502 fn startup_is_framed_with_the_protocol_version() {
503 let mut out = Vec::new();
504 startup(&mut out, &[("user", "app"), ("database", "db")]).unwrap();
505 let len = i32::from_be_bytes([out[0], out[1], out[2], out[3]]) as usize;
506 assert_eq!(len, out.len());
507 assert_eq!(&out[4..8], &PROTOCOL_3_0.to_be_bytes());
508 assert_eq!(&out[8..], b"user\0app\0database\0db\0\0");
509 }
510
511 #[test]
512 fn text_with_a_nul_is_refused() {
513 let mut out = Vec::new();
514 let e = query(&mut out, "SELECT 1\0").unwrap_err();
515 assert!(e.to_string().contains("NUL byte"), "{e}");
516 }
517
518 #[test]
519 fn bind_fills_in_formats_and_lengths() {
520 let mut out = Vec::new();
521 bind(
522 &mut out,
523 "s1",
524 3,
525 |i, out| match i {
526 0 => {
527 out.extend_from_slice(&7i32.to_be_bytes());
528 Ok(Encoded::Binary)
529 }
530 1 => Ok(Encoded::Null),
531 _ => {
532 out.extend_from_slice(b"abc");
533 Ok(Encoded::Text)
534 }
535 },
536 [true, false].into_iter(),
537 )
538 .unwrap();
539 let mut expected = vec![b'B', 0, 0, 0, 0, 0, b's', b'1', 0];
540 expected.extend_from_slice(&[0, 3, 0, 1, 0, 0, 0, 0]); expected.extend_from_slice(&[0, 3]);
542 expected.extend_from_slice(&[0, 0, 0, 4, 0, 0, 0, 7]);
543 expected.extend_from_slice(&[0xff, 0xff, 0xff, 0xff]);
544 expected.extend_from_slice(&[0, 0, 0, 3, b'a', b'b', b'c']);
545 expected.extend_from_slice(&[0, 2, 0, 1, 0, 0]);
546 let len = (expected.len() - 1) as i32;
547 expected[1..5].copy_from_slice(&len.to_be_bytes());
548 assert_eq!(out, expected);
549 }
550
551 #[test]
552 fn messages_are_taken_apart() {
553 assert_eq!(
554 parse_backend(b'Z', b"I").unwrap(),
555 Backend::ReadyForQuery(b'I')
556 );
557 assert!(parse_backend(b'Z', b"X").is_err());
558 assert!(parse_backend(b'Z', b"II").is_err());
559 assert_eq!(
560 parse_backend(b'C', b"INSERT 0 3\0").unwrap(),
561 Backend::CommandComplete("INSERT 0 3")
562 );
563 assert_eq!(
564 parse_backend(b'R', b"\0\0\0\x0aSCRAM-SHA-256\0SCRAM-SHA-256-PLUS\0\0").unwrap(),
565 Backend::AuthenticationSasl(vec!["SCRAM-SHA-256", "SCRAM-SHA-256-PLUS"])
566 );
567 assert_eq!(
568 parse_backend(b't', &[0, 2, 0, 0, 0, 23, 0, 0, 0, 25]).unwrap(),
569 Backend::ParameterDescription(vec![Type::INT4, Type::TEXT])
570 );
571 assert!(parse_backend(b'?', b"").is_err());
572 assert!(parse_backend(b'1', b"x").is_err());
573 }
574
575 #[test]
576 fn data_rows_are_checked() {
577 let body = [0, 2, 0, 0, 0, 1, b'x', 0xff, 0xff, 0xff, 0xff];
578 let mut values = Vec::new();
579 data_row(&body, 2, |v| values.push(v)).unwrap();
580 assert_eq!(values, vec![Some(6..7), None]);
581 assert!(data_row(&body, 3, |_| {}).is_err());
582 assert!(data_row(&[0, 1, 0, 0, 0, 9, b'x'], 1, |_| {}).is_err());
583 assert!(data_row(&[0, 1, 0, 0, 0, 0, b'x'], 1, |_| {}).is_err());
584 assert!(data_row(&[0, 1, 0xff, 0xff, 0xff, 0xfe], 1, |_| {}).is_err());
585 }
586
587 #[test]
588 fn frames_need_a_sane_length() {
589 assert_eq!(frame(b"Z\0\0").unwrap(), None);
590 assert_eq!(frame(b"Z\0\0\0\x05I").unwrap(), Some((b'Z', 6)));
591 assert!(frame(b"Z\0\0\0\x03").is_err());
592 assert!(frame(b"Z\xff\xff\xff\xff").is_err());
593 }
594}