Skip to main content

halephant_core/proto/
frontend.rs

1use bytes::{BufMut, BytesMut};
2use chumsky::prelude::*;
3use chumsky::span::SimpleSpan;
4
5use crate::errors;
6use crate::proto::coding;
7use crate::proto::parser;
8use crate::proto::primitives;
9use crate::proto::types;
10
11// ---------------------------------------------------------------------------
12// Message types
13// ---------------------------------------------------------------------------
14
15/// A message sent by a PostgreSQL frontend (client → server).
16#[derive(Debug, Clone, PartialEq)]
17pub enum FrontendMessage {
18    // -- Initial messages (no type byte on the wire) --
19    Startup(Startup),
20    SslRequest,
21    GssEncRequest,
22    CancelRequest { process_id: i32, secret_key: i32 },
23
24    // -- Regular messages --
25    Bind(Bind),
26    Close(Close),
27    CopyData(Vec<u8>),
28    CopyDone,
29    CopyFail(String),
30    Describe(Describe),
31    Execute(Execute),
32    Flush,
33    FunctionCall(Vec<u8>),
34    Parse(Parse),
35    PasswordMessage(Vec<u8>),
36    Query(String),
37    Sync,
38    Terminate,
39}
40
41#[derive(Debug, Clone, PartialEq)]
42pub struct Startup {
43    pub version: ProtocolVersion,
44    pub parameters: Vec<(String, String)>,
45}
46
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub struct ProtocolVersion {
49    pub major: i16,
50    pub minor: i16,
51}
52
53#[derive(Debug, Clone, PartialEq)]
54pub struct Parse {
55    pub name: String,
56    pub query: String,
57    pub param_types: Vec<types::Oid>,
58}
59
60#[derive(Debug, Clone, PartialEq)]
61pub struct Bind {
62    pub portal: String,
63    pub statement: String,
64    pub param_formats: Vec<types::FormatCode>,
65    pub params: Vec<Option<Vec<u8>>>,
66    pub result_formats: Vec<types::FormatCode>,
67}
68
69#[derive(Debug, Clone, PartialEq)]
70pub struct Describe {
71    pub kind: TargetKind,
72    pub name: String,
73}
74
75#[derive(Debug, Clone, PartialEq)]
76pub struct Execute {
77    pub portal: String,
78    pub max_rows: i32,
79}
80
81#[derive(Debug, Clone, PartialEq)]
82pub struct Close {
83    pub kind: TargetKind,
84    pub name: String,
85}
86
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
88pub enum TargetKind {
89    Statement,
90    Portal,
91}
92
93// ---------------------------------------------------------------------------
94// Well-known codes for initial messages
95// ---------------------------------------------------------------------------
96
97const PROTOCOL_V3: i32 = 196_608; // 3 << 16
98const SSL_REQUEST_CODE: i32 = 80_877_103;
99const CANCEL_REQUEST_CODE: i32 = 80_877_102;
100const GSS_ENC_REQUEST_CODE: i32 = 80_877_104;
101
102// ---------------------------------------------------------------------------
103// Chumsky parsers
104// ---------------------------------------------------------------------------
105
106fn target_kind<'src>() -> impl Parser<'src, &'src [u8], TargetKind, parser::PgExtra<'src>> + Clone {
107    any().try_map(|b, span| match b {
108        b'S' => Ok(TargetKind::Statement),
109        b'P' => Ok(TargetKind::Portal),
110        _ => Err(Rich::custom(
111            span,
112            format!("expected 'S' or 'P' for target kind, got {b:#04x}"),
113        )),
114    })
115}
116
117fn startup_body<'src>() -> impl Parser<'src, &'src [u8], FrontendMessage, parser::PgExtra<'src>> {
118    custom(|inp| {
119        let mut parameters = Vec::new();
120        loop {
121            let key: String = inp.parse(primitives::pg_cstring())?;
122            if key.is_empty() {
123                break;
124            }
125            let value: String = inp.parse(primitives::pg_cstring())?;
126            parameters.push((key, value));
127        }
128        Ok(FrontendMessage::Startup(Startup {
129            version: ProtocolVersion { major: 3, minor: 0 },
130            parameters,
131        }))
132    })
133}
134
135fn query_parser<'src>() -> impl Parser<'src, &'src [u8], FrontendMessage, parser::PgExtra<'src>> {
136    primitives::pg_cstring().map(FrontendMessage::Query)
137}
138
139fn parse_parser<'src>() -> impl Parser<'src, &'src [u8], FrontendMessage, parser::PgExtra<'src>> {
140    custom(|inp| {
141        let name = inp.parse(primitives::pg_cstring())?;
142        let query = inp.parse(primitives::pg_cstring())?;
143        let param_types = inp.parse(primitives::pg_count_prefixed(
144            primitives::pg_int32().map(|v| v as u32),
145        ))?;
146        Ok(FrontendMessage::Parse(Parse {
147            name,
148            query,
149            param_types,
150        }))
151    })
152}
153
154fn bind_parser<'src>() -> impl Parser<'src, &'src [u8], FrontendMessage, parser::PgExtra<'src>> {
155    custom(|inp| {
156        let portal = inp.parse(primitives::pg_cstring())?;
157        let statement = inp.parse(primitives::pg_cstring())?;
158        let param_formats =
159            inp.parse(primitives::pg_count_prefixed(primitives::pg_format_code()))?;
160        let params = inp.parse(primitives::pg_count_prefixed(
161            primitives::pg_nullable_bytes(),
162        ))?;
163        let result_formats =
164            inp.parse(primitives::pg_count_prefixed(primitives::pg_format_code()))?;
165        Ok(FrontendMessage::Bind(Bind {
166            portal,
167            statement,
168            param_formats,
169            params,
170            result_formats,
171        }))
172    })
173}
174
175fn describe_parser<'src>() -> impl Parser<'src, &'src [u8], FrontendMessage, parser::PgExtra<'src>>
176{
177    target_kind()
178        .then(primitives::pg_cstring())
179        .map(|(kind, name)| FrontendMessage::Describe(Describe { kind, name }))
180}
181
182fn execute_parser<'src>() -> impl Parser<'src, &'src [u8], FrontendMessage, parser::PgExtra<'src>> {
183    primitives::pg_cstring()
184        .then(primitives::pg_int32())
185        .map(|(portal, max_rows)| FrontendMessage::Execute(Execute { portal, max_rows }))
186}
187
188fn close_parser<'src>() -> impl Parser<'src, &'src [u8], FrontendMessage, parser::PgExtra<'src>> {
189    target_kind()
190        .then(primitives::pg_cstring())
191        .map(|(kind, name)| FrontendMessage::Close(Close { kind, name }))
192}
193
194fn copy_fail_parser<'src>() -> impl Parser<'src, &'src [u8], FrontendMessage, parser::PgExtra<'src>>
195{
196    primitives::pg_cstring().map(FrontendMessage::CopyFail)
197}
198
199// ---------------------------------------------------------------------------
200// Public parse API
201// ---------------------------------------------------------------------------
202
203impl FrontendMessage {
204    /// Parse an initial message (startup / SSL / cancel / GSS-enc).
205    ///
206    /// The input is the *complete* message including the leading 4-byte length.
207    pub fn parse_initial(input: &[u8]) -> Result<Self, errors::ProtocolError> {
208        let parser = custom(|inp| {
209            let _length: i32 = inp.parse(primitives::pg_int32())?;
210            let code: i32 = inp.parse(primitives::pg_int32())?;
211            match code {
212                PROTOCOL_V3 => inp.parse(startup_body()),
213                SSL_REQUEST_CODE => Ok(FrontendMessage::SslRequest),
214                CANCEL_REQUEST_CODE => {
215                    let process_id = inp.parse(primitives::pg_int32())?;
216                    let secret_key = inp.parse(primitives::pg_int32())?;
217                    Ok(FrontendMessage::CancelRequest {
218                        process_id,
219                        secret_key,
220                    })
221                }
222                GSS_ENC_REQUEST_CODE => Ok(FrontendMessage::GssEncRequest),
223                _ => Err(Rich::custom(
224                    SimpleSpan::new(4, 8),
225                    format!("unknown initial message code: {code}"),
226                )),
227            }
228        });
229        parser::run(parser, input)
230    }
231
232    /// Parse a regular (non-initial) message.
233    ///
234    /// `msg_type` is the leading type byte; `payload` is everything after the
235    /// 4-byte length field (i.e. the length-field's value minus 4).
236    pub fn parse(msg_type: u8, payload: &[u8]) -> Result<Self, errors::ProtocolError> {
237        match msg_type {
238            b'B' => parser::run(bind_parser(), payload),
239            b'C' => parser::run(close_parser(), payload),
240            b'c' => Ok(FrontendMessage::CopyDone),
241            b'd' => Ok(FrontendMessage::CopyData(payload.to_vec())),
242            b'D' => parser::run(describe_parser(), payload),
243            b'E' => parser::run(execute_parser(), payload),
244            b'f' => parser::run(copy_fail_parser(), payload),
245            b'F' => Ok(FrontendMessage::FunctionCall(payload.to_vec())),
246            b'H' => Ok(FrontendMessage::Flush),
247            b'P' => parser::run(parse_parser(), payload),
248            b'p' => Ok(FrontendMessage::PasswordMessage(payload.to_vec())),
249            b'Q' => parser::run(query_parser(), payload),
250            b'S' => Ok(FrontendMessage::Sync),
251            b'X' => Ok(FrontendMessage::Terminate),
252            _ => Err(errors::ProtocolError::UnknownMessageType(msg_type)),
253        }
254    }
255}
256
257// ---------------------------------------------------------------------------
258// Encoding
259// ---------------------------------------------------------------------------
260
261impl FrontendMessage {
262    /// Encode this message into `dst` in PostgreSQL wire format.
263    pub fn encode(&self, dst: &mut BytesMut) {
264        match self {
265            FrontendMessage::Startup(startup) => coding::encode_initial(dst, |dst| {
266                dst.put_i16(startup.version.major);
267                dst.put_i16(startup.version.minor);
268                for (key, value) in &startup.parameters {
269                    coding::encode_cstring(dst, key);
270                    coding::encode_cstring(dst, value);
271                }
272                dst.put_u8(0); // trailing null terminator
273            }),
274
275            FrontendMessage::SslRequest => coding::encode_initial(dst, |dst| {
276                dst.put_i32(SSL_REQUEST_CODE);
277            }),
278
279            FrontendMessage::GssEncRequest => coding::encode_initial(dst, |dst| {
280                dst.put_i32(GSS_ENC_REQUEST_CODE);
281            }),
282
283            FrontendMessage::CancelRequest {
284                process_id,
285                secret_key,
286            } => coding::encode_initial(dst, |dst| {
287                dst.put_i32(CANCEL_REQUEST_CODE);
288                dst.put_i32(*process_id);
289                dst.put_i32(*secret_key);
290            }),
291
292            FrontendMessage::Query(query) => coding::encode_message(dst, b'Q', |dst| {
293                coding::encode_cstring(dst, query);
294            }),
295
296            FrontendMessage::Parse(p) => coding::encode_message(dst, b'P', |dst| {
297                coding::encode_cstring(dst, &p.name);
298                coding::encode_cstring(dst, &p.query);
299                coding::encode_count_prefixed(dst, &p.param_types, |dst, oid| {
300                    dst.put_i32(*oid as i32);
301                });
302            }),
303
304            FrontendMessage::Bind(b) => coding::encode_message(dst, b'B', |dst| {
305                coding::encode_cstring(dst, &b.portal);
306                coding::encode_cstring(dst, &b.statement);
307                coding::encode_count_prefixed(dst, &b.param_formats, |dst, fc| {
308                    dst.put_i16(*fc as i16);
309                });
310                coding::encode_count_prefixed(dst, &b.params, |dst, param| match param {
311                    None => dst.put_i32(-1),
312                    Some(data) => {
313                        dst.put_i32(data.len() as i32);
314                        dst.extend_from_slice(data);
315                    }
316                });
317                coding::encode_count_prefixed(dst, &b.result_formats, |dst, fc| {
318                    dst.put_i16(*fc as i16);
319                });
320            }),
321
322            FrontendMessage::Describe(d) => coding::encode_message(dst, b'D', |dst| {
323                dst.put_u8(encode_target_kind(d.kind));
324                coding::encode_cstring(dst, &d.name);
325            }),
326
327            FrontendMessage::Execute(e) => coding::encode_message(dst, b'E', |dst| {
328                coding::encode_cstring(dst, &e.portal);
329                dst.put_i32(e.max_rows);
330            }),
331
332            FrontendMessage::Close(c) => coding::encode_message(dst, b'C', |dst| {
333                dst.put_u8(encode_target_kind(c.kind));
334                coding::encode_cstring(dst, &c.name);
335            }),
336
337            FrontendMessage::Sync => coding::encode_message(dst, b'S', |_| {}),
338            FrontendMessage::Flush => coding::encode_message(dst, b'H', |_| {}),
339            FrontendMessage::Terminate => coding::encode_message(dst, b'X', |_| {}),
340            FrontendMessage::CopyDone => coding::encode_message(dst, b'c', |_| {}),
341
342            FrontendMessage::CopyData(data) => coding::encode_message(dst, b'd', |dst| {
343                dst.extend_from_slice(data);
344            }),
345
346            FrontendMessage::CopyFail(msg) => coding::encode_message(dst, b'f', |dst| {
347                coding::encode_cstring(dst, msg);
348            }),
349
350            FrontendMessage::FunctionCall(data) => coding::encode_message(dst, b'F', |dst| {
351                dst.extend_from_slice(data);
352            }),
353
354            FrontendMessage::PasswordMessage(data) => coding::encode_message(dst, b'p', |dst| {
355                dst.extend_from_slice(data);
356            }),
357        }
358    }
359}
360
361fn encode_target_kind(kind: TargetKind) -> u8 {
362    match kind {
363        TargetKind::Statement => b'S',
364        TargetKind::Portal => b'P',
365    }
366}