Skip to main content

halephant_core/proto/
frontend.rs

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