Skip to main content

giong_postgres/
protocol.rs

1//! The PostgreSQL wire protocol, version 3.0: encoding what the client sends
2//! and taking apart what the server sends.
3
4use 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
11/// The largest number of parameters a statement can have: the protocol counts
12/// them in an unsigned 16-bit field.
13pub(crate) const MAX_PARAMS: usize = u16::MAX as usize;
14
15// ------------------------------------------------------------------ frontend
16
17/// Appends a message with `tag`, whose body `body` writes; the length field is
18/// filled in afterwards.
19fn 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
24/// Appends a length-prefixed body (the length counts itself).
25fn 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
35/// A NUL-terminated string. The caller has checked that it holds no NUL.
36fn cstr(out: &mut Vec<u8>, s: &str) {
37    out.extend_from_slice(s.as_bytes());
38    out.push(0);
39}
40
41/// Refuses text that the protocol cannot carry.
42pub(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
79/// `PasswordMessage`, which also carries SASL responses.
80pub(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
96/// A simple query: the text may hold several statements, and has no
97/// parameters.
98pub(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
103/// `Parse` into the named statement `name`, letting the server infer every
104/// parameter type.
105pub(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
121/// `Execute` of the unnamed portal, all rows.
122pub(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/// How a parameter value was written by [`ToSql`](crate::ToSql).
145///
146/// A parameter of any type may be sent as text, which the server parses as
147/// it would a literal; binary needs the type's binary format exactly. The
148/// enum is complete: PostgreSQL's protocol has only these two formats.
149#[derive(Clone, Copy, Debug, PartialEq, Eq)]
150pub enum Encoded {
151    /// SQL `NULL`; nothing was written.
152    Null,
153    /// The bytes are in PostgreSQL's binary format for the parameter's type.
154    Binary,
155    /// The bytes are text that the server parses as the parameter's type, as
156    /// it would a literal in the SQL.
157    Text,
158}
159
160/// `Bind` of the named statement to the unnamed portal. `encode(i, out)`
161/// appends parameter `i` and says how. `binary_results[i]` asks for column
162/// `i` in binary.
163pub(crate) fn bind(
164    out: &mut Vec<u8>,
165    statement: &str,
166    params: usize,
167    mut encode: impl FnMut(usize, &mut Vec<u8>) -> Result<Encoded, Error>,
168    binary_results: impl ExactSizeIterator<Item = bool>,
169) -> Result<(), Error> {
170    debug_assert!(params <= MAX_PARAMS);
171    out.push(b'B');
172    let start = out.len();
173    out.extend_from_slice(&[0; 4]);
174    out.push(0); // the unnamed portal
175    cstr(out, statement);
176    // The format of each parameter is only known once it is encoded: reserve
177    // the codes and fill them in as the values are written.
178    out.extend_from_slice(&(params as u16).to_be_bytes());
179    let formats = out.len();
180    out.resize(formats + 2 * params, 0);
181    out.extend_from_slice(&(params as u16).to_be_bytes());
182    for i in 0..params {
183        let at = out.len();
184        out.extend_from_slice(&[0; 4]);
185        let len = match encode(i, out)? {
186            Encoded::Null => {
187                out.truncate(at + 4);
188                -1i32
189            }
190            how => {
191                if how == Encoded::Binary {
192                    out[formats + 2 * i + 1] = 1;
193                }
194                i32::try_from(out.len() - at - 4).map_err(|_| {
195                    Error::conversion(format!("parameter ${} is larger than 2 GiB", i + 1))
196                })?
197            }
198        };
199        out[at..at + 4].copy_from_slice(&len.to_be_bytes());
200    }
201    out.extend_from_slice(&(binary_results.len() as u16).to_be_bytes());
202    for binary in binary_results {
203        out.extend_from_slice(&(binary as i16).to_be_bytes());
204    }
205    let len = i32::try_from(out.len() - start)
206        .map_err(|_| Error::conversion("the parameters add up to more than 2 GiB"))?;
207    out[start..start + 4].copy_from_slice(&len.to_be_bytes());
208    Ok(())
209}
210
211// ------------------------------------------------------------------- backend
212
213/// A message from the server, borrowing from the read buffer.
214#[derive(Debug, PartialEq)]
215pub(crate) enum Backend<'a> {
216    AuthenticationOk,
217    AuthenticationCleartextPassword,
218    AuthenticationMd5Password([u8; 4]),
219    AuthenticationSasl(Vec<&'a str>),
220    AuthenticationSaslContinue(&'a [u8]),
221    AuthenticationSaslFinal(&'a [u8]),
222    /// Kerberos, GSSAPI, SSPI, SCM credentials: the code.
223    AuthenticationOther(i32),
224    KeyData {
225        process_id: i32,
226        secret_key: i32,
227    },
228    BindComplete,
229    CloseComplete,
230    CommandComplete(&'a str),
231    CopyData,
232    CopyDone,
233    CopyInResponse,
234    CopyOutResponse,
235    CopyBothResponse,
236    /// The body of a `DataRow`: read it with [`DataRow`].
237    DataRow(&'a [u8]),
238    EmptyQueryResponse,
239    /// The fields; read them with [`DbError::parse`](crate::DbError).
240    ErrorResponse(&'a [u8]),
241    NegotiateProtocolVersion,
242    NoData,
243    NoticeResponse,
244    NotificationResponse,
245    ParameterDescription(Vec<Type>),
246    ParameterStatus {
247        name: &'a str,
248        value: &'a str,
249    },
250    ParseComplete,
251    PortalSuspended,
252    ReadyForQuery(u8),
253    RowDescription(Vec<FieldDescription<'a>>),
254}
255
256/// One column of a `RowDescription`.
257#[derive(Debug, PartialEq)]
258pub(crate) struct FieldDescription<'a> {
259    pub name: &'a str,
260    pub table_oid: u32,
261    pub column_id: i16,
262    pub type_oid: u32,
263}
264
265/// The tag and total length of the message at the start of `buf`, if all of
266/// its header is there.
267pub(crate) fn frame(buf: &[u8]) -> Result<Option<(u8, usize)>, Error> {
268    if buf.len() < 5 {
269        return Ok(None);
270    }
271    let len = i32::from_be_bytes([buf[1], buf[2], buf[3], buf[4]]);
272    if len < 4 {
273        return Err(Error::protocol(format!(
274            "the server sent a message ({:?}) with an invalid length {len}",
275            buf[0] as char
276        )));
277    }
278    Ok(Some((buf[0], len as usize + 1)))
279}
280
281/// A cursor over a message body.
282struct Cursor<'a> {
283    buf: &'a [u8],
284    what: &'static str,
285}
286
287impl<'a> Cursor<'a> {
288    fn new(buf: &'a [u8], what: &'static str) -> Self {
289        Self { buf, what }
290    }
291
292    fn bad(&self) -> Error {
293        Error::protocol(format!("the server sent a malformed {} message", self.what))
294    }
295
296    fn bytes(&mut self, n: usize) -> Result<&'a [u8], Error> {
297        if self.buf.len() < n {
298            return Err(self.bad());
299        }
300        let (head, tail) = self.buf.split_at(n);
301        self.buf = tail;
302        Ok(head)
303    }
304
305    fn u8(&mut self) -> Result<u8, Error> {
306        Ok(self.bytes(1)?[0])
307    }
308
309    fn i16(&mut self) -> Result<i16, Error> {
310        let b = self.bytes(2)?;
311        Ok(i16::from_be_bytes([b[0], b[1]]))
312    }
313
314    fn i32(&mut self) -> Result<i32, Error> {
315        let b = self.bytes(4)?;
316        Ok(i32::from_be_bytes([b[0], b[1], b[2], b[3]]))
317    }
318
319    fn cstr(&mut self) -> Result<&'a str, Error> {
320        let end = self
321            .buf
322            .iter()
323            .position(|&b| b == 0)
324            .ok_or_else(|| self.bad())?;
325        let s = std::str::from_utf8(&self.buf[..end]).map_err(|_| self.bad())?;
326        self.buf = &self.buf[end + 1..];
327        Ok(s)
328    }
329
330    fn rest(&mut self) -> &'a [u8] {
331        std::mem::take(&mut self.buf)
332    }
333
334    fn end(&self) -> Result<(), Error> {
335        if self.buf.is_empty() {
336            Ok(())
337        } else {
338            Err(self.bad())
339        }
340    }
341}
342
343/// Takes apart one message: `tag` and its body (without the length).
344pub(crate) fn parse_backend(tag: u8, body: &[u8]) -> Result<Backend<'_>, Error> {
345    use Backend::*;
346    let empty = |m: Backend<'static>, what| {
347        if body.is_empty() {
348            Ok(m)
349        } else {
350            Err(Cursor::new(body, what).bad())
351        }
352    };
353    match tag {
354        b'R' => {
355            let mut c = Cursor::new(body, "authentication");
356            let msg = match c.i32()? {
357                0 => AuthenticationOk,
358                3 => AuthenticationCleartextPassword,
359                5 => {
360                    let salt = c.bytes(4)?;
361                    AuthenticationMd5Password([salt[0], salt[1], salt[2], salt[3]])
362                }
363                10 => {
364                    let mut mechanisms = Vec::new();
365                    loop {
366                        let m = c.cstr()?;
367                        if m.is_empty() {
368                            break;
369                        }
370                        mechanisms.push(m);
371                    }
372                    AuthenticationSasl(mechanisms)
373                }
374                11 => return Ok(AuthenticationSaslContinue(c.rest())),
375                12 => return Ok(AuthenticationSaslFinal(c.rest())),
376                other => return Ok(AuthenticationOther(other)),
377            };
378            c.end()?;
379            Ok(msg)
380        }
381        b'K' => {
382            let mut c = Cursor::new(body, "BackendKeyData");
383            let process_id = c.i32()?;
384            let secret_key = c.i32()?;
385            // Protocol 3.2 allows longer keys; 3.0, which this client asks
386            // for, has exactly four bytes.
387            c.end()?;
388            Ok(KeyData {
389                process_id,
390                secret_key,
391            })
392        }
393        b'2' => empty(BindComplete, "BindComplete"),
394        b'3' => empty(CloseComplete, "CloseComplete"),
395        b'C' => {
396            let mut c = Cursor::new(body, "CommandComplete");
397            let tag = c.cstr()?;
398            c.end()?;
399            Ok(CommandComplete(tag))
400        }
401        b'd' => Ok(CopyData),
402        b'c' => empty(CopyDone, "CopyDone"),
403        b'G' => Ok(CopyInResponse),
404        b'H' => Ok(CopyOutResponse),
405        b'W' => Ok(CopyBothResponse),
406        b'D' => Ok(DataRow(body)),
407        b'I' => empty(EmptyQueryResponse, "EmptyQueryResponse"),
408        b'E' => Ok(ErrorResponse(body)),
409        b'v' => Ok(NegotiateProtocolVersion),
410        b'n' => empty(NoData, "NoData"),
411        b'N' => Ok(NoticeResponse),
412        b'A' => Ok(NotificationResponse),
413        b't' => {
414            let mut c = Cursor::new(body, "ParameterDescription");
415            let n = c.i16()? as u16 as usize;
416            let mut types = Vec::with_capacity(n);
417            for _ in 0..n {
418                types.push(Type::from_oid(c.i32()? as u32));
419            }
420            c.end()?;
421            Ok(ParameterDescription(types))
422        }
423        b'S' => {
424            let mut c = Cursor::new(body, "ParameterStatus");
425            let name = c.cstr()?;
426            let value = c.cstr()?;
427            c.end()?;
428            Ok(ParameterStatus { name, value })
429        }
430        b'1' => empty(ParseComplete, "ParseComplete"),
431        b's' => empty(PortalSuspended, "PortalSuspended"),
432        b'Z' => {
433            let mut c = Cursor::new(body, "ReadyForQuery");
434            let status = c.u8()?;
435            c.end()?;
436            if !matches!(status, b'I' | b'T' | b'E') {
437                return Err(c.bad());
438            }
439            Ok(ReadyForQuery(status))
440        }
441        b'T' => {
442            let mut c = Cursor::new(body, "RowDescription");
443            let n = c.i16()? as u16 as usize;
444            let mut fields = Vec::with_capacity(n.min(1024));
445            for _ in 0..n {
446                let name = c.cstr()?;
447                let table_oid = c.i32()? as u32;
448                let column_id = c.i16()?;
449                let type_oid = c.i32()? as u32;
450                let _size = c.i16()?;
451                let _modifier = c.i32()?;
452                let _format = c.i16()?;
453                fields.push(FieldDescription {
454                    name,
455                    table_oid,
456                    column_id,
457                    type_oid,
458                });
459            }
460            c.end()?;
461            Ok(RowDescription(fields))
462        }
463        other => Err(Error::protocol(format!(
464            "the server sent a message of unknown type {:?}",
465            other as char
466        ))),
467    }
468}
469
470/// Walks the values of a `DataRow` body, checking the column count against
471/// `columns`: `value(Some(range))` gives where a value is in `body`,
472/// `value(None)` a `NULL`.
473pub(crate) fn data_row(
474    body: &[u8],
475    columns: usize,
476    mut value: impl FnMut(Option<std::ops::Range<usize>>),
477) -> Result<(), Error> {
478    let mut c = Cursor::new(body, "DataRow");
479    let n = c.i16()? as u16 as usize;
480    if n != columns {
481        return Err(Error::protocol(format!(
482            "the server sent a row with {n} values for a statement with {columns} columns"
483        )));
484    }
485    for _ in 0..n {
486        let len = c.i32()?;
487        if len == -1 {
488            value(None);
489            continue;
490        }
491        if len < 0 {
492            return Err(c.bad());
493        }
494        let at = body.len() - c.buf.len();
495        c.bytes(len as usize)?;
496        value(Some(at..at + len as usize));
497    }
498    c.end()
499}
500
501#[cfg(test)]
502mod tests {
503    use super::*;
504
505    #[test]
506    fn startup_is_framed_with_the_protocol_version() {
507        let mut out = Vec::new();
508        startup(&mut out, &[("user", "app"), ("database", "db")]).unwrap();
509        let len = i32::from_be_bytes([out[0], out[1], out[2], out[3]]) as usize;
510        assert_eq!(len, out.len());
511        assert_eq!(&out[4..8], &PROTOCOL_3_0.to_be_bytes());
512        assert_eq!(&out[8..], b"user\0app\0database\0db\0\0");
513    }
514
515    #[test]
516    fn text_with_a_nul_is_refused() {
517        let mut out = Vec::new();
518        let e = query(&mut out, "SELECT 1\0").unwrap_err();
519        assert!(e.to_string().contains("NUL byte"), "{e}");
520    }
521
522    #[test]
523    fn bind_fills_in_formats_and_lengths() {
524        let mut out = Vec::new();
525        bind(
526            &mut out,
527            "s1",
528            3,
529            |i, out| match i {
530                0 => {
531                    out.extend_from_slice(&7i32.to_be_bytes());
532                    Ok(Encoded::Binary)
533                }
534                1 => Ok(Encoded::Null),
535                _ => {
536                    out.extend_from_slice(b"abc");
537                    Ok(Encoded::Text)
538                }
539            },
540            [true, false].into_iter(),
541        )
542        .unwrap();
543        let mut expected = vec![b'B', 0, 0, 0, 0, 0, b's', b'1', 0];
544        expected.extend_from_slice(&[0, 3, 0, 1, 0, 0, 0, 0]); // formats
545        expected.extend_from_slice(&[0, 3]);
546        expected.extend_from_slice(&[0, 0, 0, 4, 0, 0, 0, 7]);
547        expected.extend_from_slice(&[0xff, 0xff, 0xff, 0xff]);
548        expected.extend_from_slice(&[0, 0, 0, 3, b'a', b'b', b'c']);
549        expected.extend_from_slice(&[0, 2, 0, 1, 0, 0]);
550        let len = (expected.len() - 1) as i32;
551        expected[1..5].copy_from_slice(&len.to_be_bytes());
552        assert_eq!(out, expected);
553    }
554
555    #[test]
556    fn messages_are_taken_apart() {
557        assert_eq!(
558            parse_backend(b'Z', b"I").unwrap(),
559            Backend::ReadyForQuery(b'I')
560        );
561        assert!(parse_backend(b'Z', b"X").is_err());
562        assert!(parse_backend(b'Z', b"II").is_err());
563        assert_eq!(
564            parse_backend(b'C', b"INSERT 0 3\0").unwrap(),
565            Backend::CommandComplete("INSERT 0 3")
566        );
567        assert_eq!(
568            parse_backend(b'R', b"\0\0\0\x0aSCRAM-SHA-256\0SCRAM-SHA-256-PLUS\0\0").unwrap(),
569            Backend::AuthenticationSasl(vec!["SCRAM-SHA-256", "SCRAM-SHA-256-PLUS"])
570        );
571        assert_eq!(
572            parse_backend(b't', &[0, 2, 0, 0, 0, 23, 0, 0, 0, 25]).unwrap(),
573            Backend::ParameterDescription(vec![Type::INT4, Type::TEXT])
574        );
575        assert!(parse_backend(b'?', b"").is_err());
576        assert!(parse_backend(b'1', b"x").is_err());
577    }
578
579    #[test]
580    fn data_rows_are_checked() {
581        let body = [0, 2, 0, 0, 0, 1, b'x', 0xff, 0xff, 0xff, 0xff];
582        let mut values = Vec::new();
583        data_row(&body, 2, |v| values.push(v)).unwrap();
584        assert_eq!(values, vec![Some(6..7), None]);
585        assert!(data_row(&body, 3, |_| {}).is_err());
586        assert!(data_row(&[0, 1, 0, 0, 0, 9, b'x'], 1, |_| {}).is_err());
587        assert!(data_row(&[0, 1, 0, 0, 0, 0, b'x'], 1, |_| {}).is_err());
588        assert!(data_row(&[0, 1, 0xff, 0xff, 0xff, 0xfe], 1, |_| {}).is_err());
589    }
590
591    #[test]
592    fn frames_need_a_sane_length() {
593        assert_eq!(frame(b"Z\0\0").unwrap(), None);
594        assert_eq!(frame(b"Z\0\0\0\x05I").unwrap(), Some((b'Z', 6)));
595        assert!(frame(b"Z\0\0\0\x03").is_err());
596        assert!(frame(b"Z\xff\xff\xff\xff").is_err());
597    }
598}