/// PostgreSQL's wire protocol, version 3.0 (issue gabla108/louise#145): pure encoding /// and decoding of messages — no IO here, so every exchange is testable /// against recorded byte transcripts. /// /// Frames on the wire: a type byte, a big-endian 32-bit length that /// counts itself, then the payload. (`Startup` and `SslRequest` have no /// type byte; the answer to `SslRequest` is one byte, not a frame.) import std/bytes import std/int import std/list import std/result // ---- outgoing (frontend) --------------------------------------------------- /// A message the client sends. pub type Out { /// Ask whether the server upgrades this connection to TLS. SslRequest /// Protocol 3.0, with the user, the database and the application name. , Startup(user: String, database: String, application: String) /// The (cleartext, or hashed) password. , Password(String) /// One step of a SCRAM exchange. , SaslResponse(Bytes) /// The first SCRAM message names the mechanism: `SASLInitialResponse`. , SaslInitialResponse(mechanism: String, data: Bytes) /// The simple query protocol (used for `BEGIN`/`COMMIT`/`ROLLBACK` only). , Query(String) /// Name a statement for the SQL. `param_oids` declares parameter types /// (`0` leaves one to the server's inference): a `bytea` parameter is /// declared `17` so its binary form is taken however the SQL reads. , Parse(name: String, sql: String, param_oids: List) /// A portal for a statement with its parameters and the result columns' /// formats wanted (`0` text, `1` binary; empty is all text). , Bind( portal: String , statement: String , params: List , result_formats: List ) /// Ask for a statement's description (`RowDescription`). , DescribeStatement(String) /// Ask for a portal's description. , DescribePortal(String) /// Run a portal (`max_rows` 0 = all rows). , Execute(portal: String, max_rows: Int) /// End the extended-protocol exchange. , Sync /// Ask for the pending responses now. , Flush /// End the connection politely. , Terminate /// `CancelRequest` (no type byte): ask the server to stop the query the /// connection with this process id and secret key is running. , CancelRequest(process: Int, secret: Int) } /// A `Bind` parameter: its value (`None` is SQL `NULL`) and its format /// (`0` text, `1` binary). pub type BindParam { BindParam(value: Option, format: Int) } /// A message as bytes on the wire. pub fn encode :: msg: Out -> Bytes { match msg { SslRequest -> { let b = be32 (bytes.builder ()) 8 bytes.build (be32 b 80877103) } , Startup(user, database, application) -> { let p = bytes.builder () let p = be32 p 196608 // 3.0 let p = cstr p "user" let p = cstr p user let p = cstr p "database" let p = cstr p database let p = cstr p "application_name" let p = cstr p application let p = bytes.append_byte p 0 let payload = bytes.build p let b = be32 (bytes.builder ()) (bytes.length payload + 4) bytes.build (bytes.append b payload) } , Password(password) -> frame 112 (bytes.build (cstr (bytes.builder ()) password)) , SaslResponse(data) -> frame 112 data , SaslInitialResponse(mechanism, data) -> { let p = cstr (bytes.builder ()) mechanism let p = be32 p (bytes.length data) frame 112 (bytes.build (bytes.append p data)) } , Query(sql) -> frame 81 (bytes.build (cstr (bytes.builder ()) sql)) , Parse(name, sql, param_oids) -> { let p = cstr (bytes.builder ()) name let p = cstr p sql let p = be16 p (list.length param_oids) frame 80 (bytes.build (list.fold param_oids p parse_param_oid)) } , Bind(portal, statement, params, result_formats) -> { let p = cstr (bytes.builder ()) portal let p = cstr p statement let p = be16 p (list.length params) let p = list.fold params p bind_param_format let p = be16 p (list.length params) let p = list.fold params p bind_param let p = be16 p (list.length result_formats) frame 66 (bytes.build (list.fold result_formats p bind_result_format)) } , DescribeStatement(name) -> describe 83 name , DescribePortal(name) -> describe 80 name , Execute(portal, max_rows) -> { let p = cstr (bytes.builder ()) portal frame 69 (bytes.build (be32 p max_rows)) } , Sync -> frame 83 (bytes.empty ()) , Flush -> frame 72 (bytes.empty ()) , Terminate -> frame 88 (bytes.empty ()) , CancelRequest(process, secret) -> { // No type byte: length 16, the cancel code 80877102, then the key. let b = be32 (bytes.builder ()) 16 let b = be32 b 80877102 let b = be32 b process bytes.build (be32 b secret) } } } fn bind_param :: p: bytes.Builder param: BindParam -> bytes.Builder { match param.value { None -> be32 p (-1) , Some(data) -> { let p = be32 p (bytes.length data) bytes.append p data } } } /// The parameter's format code, before the parameters. fn bind_param_format :: p: bytes.Builder param: BindParam -> bytes.Builder { be16 p param.format } /// A result column's format code. fn bind_result_format :: p: bytes.Builder format: Int -> bytes.Builder { be16 p format } /// A parameter's declared type oid in a `Parse` (`0` is "infer it"). fn parse_param_oid :: p: bytes.Builder oid: Int -> bytes.Builder { be32 p oid } /// A Describe frame: the tag, then 'S' or 'P' and the name. fn describe :: what: Int name: String -> Bytes { let p = bytes.append_byte (bytes.builder ()) what frame 68 (bytes.build (cstr p name)) } /// A frame: the tag byte, then the big-endian length (counting itself) /// and the payload. fn frame :: tag: Int payload: Bytes -> Bytes { let b = bytes.append_byte (bytes.builder ()) tag let b = be32 b (bytes.length payload + 4) bytes.build (bytes.append b payload) } /// `n` as 4 big-endian bytes (its low 32 bits). fn be32 :: b: bytes.Builder n: Int -> bytes.Builder { let n = int.low_bits n 32 let b = bytes.append_byte b (int.and (int.shift_right n 24) 255) let b = bytes.append_byte b (int.and (int.shift_right n 16) 255) let b = bytes.append_byte b (int.and (int.shift_right n 8) 255) bytes.append_byte b (int.and n 255) } /// `n` as 2 big-endian bytes. fn be16 :: b: bytes.Builder n: Int -> bytes.Builder { let b = bytes.append_byte b (int.and (int.shift_right n 8) 255) bytes.append_byte b (int.and n 255) } /// `s` as UTF-8, then a zero byte. fn cstr :: b: bytes.Builder s: String -> bytes.Builder { bytes.append_byte (bytes.append_string b s) 0 } // ---- the TLS negotiation answer --------------------------------------------- /// What the server answered to `SslRequest`. pub type SslAnswer { /// 'S': send the TLS handshake now. Upgrade /// 'N': the server does not do TLS. , Plain } /// The one byte that answers `SslRequest` (it is not a frame). pub fn ssl_answer :: byte: Int -> Option { match byte { 83 -> Some(Upgrade), 78 -> Some(Plain), _ -> None } } // ---- incoming (backend) ----------------------------------------------------- /// A message the server sent. @derive Eq Debug pub type In { /// Authentication succeeded. AuthenticationOk /// The server wants a cleartext password (only over TLS, documented). , AuthenticationCleartext /// The server wants SASL, offering these mechanisms. , AuthenticationSasl(List) /// A SCRAM step's data (`AuthenticationSASLContinue`). , SaslContinue(Bytes) /// The last SCRAM step's data (`AuthenticationSASLFinal`). , SaslFinal(Bytes) /// A run-time parameter the server reports (`server_version`, ...). , ParameterStatus(name: String, value: String) /// The connection's process id and secret key (for `CancelRequest`). , BackendKeyData(process: Int, secret: Int) /// The server is ready for a query, in this transaction state. , ReadyForQuery(TxStatus) /// An error, as (field code, text) pairs (`"C"` is the SQLSTATE). , ErrorResponse(List<(String, String)>) /// A notice, with the same fields. , NoticeResponse(List<(String, String)>) , ParseComplete , BindComplete /// A row set's columns. , RowDescription(List) /// A statement's parameters' type OIDs (the `Describe` of a statement). , ParameterDescription(List) /// A row (`None` is SQL `NULL`). , DataRow(List>) /// The command's tag (`"SELECT 2"`, ...). , CommandComplete(String) /// A `NOTIFY`: process id, channel, payload. , NotificationResponse(process: Int, channel: String, payload: String) /// A `Query` that returned nothing. , EmptyQueryResponse /// A portal with no rows (Describe's answer). , NoData } /// A `RowDescription` field. @derive Eq Debug pub type Field { Field( name: String , table: Int , column: Int , type_oid: Int , size: Int , modifier: Int , format: Int ) } /// The transaction state a `ReadyForQuery` reports. @derive Eq Debug pub type TxStatus { /// 'I': not in a transaction. Idle /// 'T': in a transaction. , InTx /// 'E': in a failed transaction (rolled back on `COMMIT`). , Failed } /// What [`next`] found in the buffer. pub type Next { /// Not all of the message's bytes are there yet. Incomplete /// A message, and the offset just past it. , Message(In, Int) /// A frame that cannot be one: the connection is broken. , Malformed(String) } /// The most payload a message may declare (1 GiB). A bigger length marks /// a broken connection: nothing allocates before the check. pub fn max_message :: -> Int { 1073741824 } /// The whole frame's size in bytes (tag, length and payload), read from /// a buffer holding at least its first 5 bytes from `at`; `Error` when /// the declared length cannot be a frame's. pub fn frame_total :: buffer: Bytes at: Int -> Result { let length = bytes.read_u32be buffer (at + 1) if length < 4 || length > max_message () + 4 { Error("invalid frame length {length}") } else { Ok(length + 1) } } /// The first message in `buffer` at `at`, if its bytes are all there, /// and the offset just past it. Nothing is copied: the message's fields /// are read in place (a column's value is one fresh `Bytes` each). pub fn next :: buffer: Bytes at: Int -> Next { if bytes.length buffer - at < 5 { Incomplete } else { match frame_total buffer at { Error(e) -> Malformed(e) , Ok ( total ) -> if bytes.length buffer - at < total { Incomplete } else { match parse (bytes.read_u8 buffer at) Cursor(buffer, at + 5, at + total) { Ok(msg) -> Message(msg, at + total), Error(e) -> Malformed(e) } } } } } /// A cursor over a message's payload: `end` is one past its last byte /// in `bytes`. type Cursor { Cursor(bytes: Bytes, at: Int, end: Int) } fn parse :: tag: Int cur: Cursor -> Result { match tag { 82 -> authentication cur // 'R' , 83 -> parameter_status cur // 'S' , 75 -> backend_key_data cur // 'K' , 90 -> ready_for_query cur // 'Z' , 69 -> error_fields cur ErrorResponse_of // 'E' , 78 -> error_fields cur NoticeResponse_of // 'N' , 84 -> row_description cur // 'T' , 116 -> parameter_description cur // 't' , 68 -> data_row cur // 'D' , 67 -> command_complete cur // 'C' , 65 -> notification cur // 'A' , 49 -> plain cur ParseComplete // '1' , 50 -> plain cur BindComplete // '2' , 73 -> plain cur EmptyQueryResponse // 'I' , 110 -> plain cur NoData // 'n' , _ -> Error("a message type the driver does not know: tag {tag}") } } // The constructors as values (for the error fields' two shapes). fn ErrorResponse_of :: fields: List<(String, String)> -> In { ErrorResponse(fields) } fn NoticeResponse_of :: fields: List<(String, String)> -> In { NoticeResponse(fields) } /// A message with an empty payload. fn plain :: cur: Cursor msg: In -> Result { if cur.at == cur.end { Ok(msg) } else { Error("the message has bytes left over") } } fn authentication :: cur: Cursor -> Result { use (kind, cur) <- result.try (read_be32 cur) match kind { 0 -> Ok(AuthenticationOk) , 3 -> Ok(AuthenticationCleartext) , 10 -> mechanism_list cur [] , 11 -> read_rest cur SaslContinue_of , 12 -> read_rest cur SaslFinal_of , _ -> Error("an authentication method the driver does not know: {kind}") } } fn SaslContinue_of :: data: Bytes -> In { SaslContinue(data) } fn SaslFinal_of :: data: Bytes -> In { SaslFinal(data) } /// The list of mechanism names, ended by an empty string. fn mechanism_list :: cur: Cursor acc: List -> Result { use (name, cur) <- result.try (read_cstr cur) if name == "" { Ok(AuthenticationSasl(list.reverse acc)) } else { mechanism_list cur [name, ..acc] } } /// The rest of the payload as bytes. fn read_rest :: cur: Cursor of: fn(Bytes) -> In -> Result { Ok(of (bytes.slice cur.bytes cur.at cur.end)) } fn parameter_status :: cur: Cursor -> Result { use (name, cur) <- result.try (read_cstr cur) use (value, _) <- result.try (read_cstr cur) Ok(ParameterStatus(name, value)) } fn backend_key_data :: cur: Cursor -> Result { use (process, cur) <- result.try (read_be32 cur) use (secret, _) <- result.try (read_be32 cur) Ok(BackendKeyData(process, secret)) } fn ready_for_query :: cur: Cursor -> Result { use (status, _) <- result.try (read_u8 cur) match status { 73 -> Ok(ReadyForQuery(Idle)) , 84 -> Ok(ReadyForQuery(InTx)) , 69 -> Ok(ReadyForQuery(Failed)) , _ -> Error("a transaction status the driver does not know: {status}") } } /// The `(code, text)` fields of an error or a notice, ended by a zero /// byte. fn error_fields :: cur: Cursor of: fn(List<(String, String)>) -> In -> Result { use (code, cur) <- result.try (read_u8 cur) if code == 0 { Ok(of []) } else { error_fields_loop cur of code [] } } fn error_fields_loop :: cur: Cursor of: fn(List<(String, String)>) -> In code: Int acc: List<(String, String)> -> Result { use (text, cur) <- result.try (read_cstr cur) let field = (code_string code, text) use (next_code, cur) <- result.try (read_u8 cur) if next_code == 0 { Ok(of (list.reverse [field, ..acc])) } else { error_fields_loop cur of next_code [field, ..acc] } } fn row_description :: cur: Cursor -> Result { use (count, cur) <- result.try (read_be16 cur) field_list cur count [] } /// The parameters' type OIDs: an i16 count, then a be32 each. fn parameter_description :: cur: Cursor -> Result { use (count, cur) <- result.try (read_be16 cur) oid_list cur count [] } fn oid_list :: cur: Cursor count: Int acc: List -> Result { if count <= 0 { Ok(ParameterDescription(list.reverse acc)) } else { use (oid, cur) <- result.try (read_be32 cur) oid_list cur (count - 1) [oid, ..acc] } } fn field_list :: cur: Cursor count: Int acc: List -> Result { if count <= 0 { Ok(RowDescription(list.reverse acc)) } else { use (name, cur) <- result.try (read_cstr cur) use (table, cur) <- result.try (read_be32 cur) use (column, cur) <- result.try (read_be16 cur) use (type_oid, cur) <- result.try (read_be32 cur) use (size, cur) <- result.try (read_be16 cur) use (modifier, cur) <- result.try (read_be32 cur) use (format, cur) <- result.try (read_be16 cur) let field = Field(name, table, column, type_oid, size, modifier, format) field_list cur (count - 1) [field, ..acc] } } fn data_row :: cur: Cursor -> Result { use (count, cur) <- result.try (read_be16 cur) value_list cur count [] } fn value_list :: cur: Cursor count: Int acc: List> -> Result { if count <= 0 { Ok(DataRow(list.reverse acc)) } else { use (value, cur) <- result.try (read_value cur) value_list cur (count - 1) [value, ..acc] } } /// A column's value: its big-endian length, then its bytes (`-1` is SQL /// `NULL`). Fused, so a field is one read, not two. fn read_value :: cur: Cursor -> Result<(Option, Cursor), String> { if cur.at + 4 > cur.end { Error("the message ends early") } else { let n = bytes.read_u32be cur.bytes cur.at let length = if n >= 2147483648 { n - 4294967296 } else { n } if length == -1 { Ok((None, Cursor(..cur, at: cur.at + 4))) } else if length < 0 { Error("a column length of {length}") } else if cur.at + 4 + length > cur.end { Error("the message ends early") } else { let value = bytes.slice cur.bytes (cur.at + 4) (cur.at + 4 + length) Ok((Some(value), Cursor(..cur, at: cur.at + 4 + length))) } } } fn command_complete :: cur: Cursor -> Result { use (tag, _) <- result.try (read_cstr cur) Ok(CommandComplete(tag)) } fn notification :: cur: Cursor -> Result { use (process, cur) <- result.try (read_be32 cur) use (channel, cur) <- result.try (read_cstr cur) use (payload, _) <- result.try (read_cstr cur) Ok(NotificationResponse(process, channel, payload)) } // ---- the cursor's reads ----------------------------------------------------- // Every read checks its bounds against the payload's end first, then // reads in place: no slice, no list, no allocation. fn read_u8 :: cur: Cursor -> Result<(Int, Cursor), String> { if cur.at >= cur.end { Error("the message ends early") } else { Ok((bytes.read_u8 cur.bytes cur.at, Cursor(..cur, at: cur.at + 1))) } } fn read_be16 :: cur: Cursor -> Result<(Int, Cursor), String> { if cur.at + 2 > cur.end { Error("the message ends early") } else { Ok((bytes.read_u16be cur.bytes cur.at, Cursor(..cur, at: cur.at + 2))) } } /// The big-endian 32-bit integer, signed. fn read_be32 :: cur: Cursor -> Result<(Int, Cursor), String> { if cur.at + 4 > cur.end { Error("the message ends early") } else { let n = bytes.read_u32be cur.bytes cur.at let n = if n >= 2147483648 { n - 4294967296 } else { n } Ok((n, Cursor(..cur, at: cur.at + 4))) } } /// The next zero-terminated string. fn read_cstr :: cur: Cursor -> Result<(String, Cursor), String> { match find_zero cur.bytes cur.at cur.end { None -> Error("the string is not terminated") , Some(end) -> { match bytes.to_string_range cur.bytes cur.at (end - cur.at) { Ok(s) -> Ok((s, Cursor(..cur, at: end + 1))) , Error(e) -> Error("the string is not UTF-8: {e}") } } } } fn find_zero :: b: Bytes at: Int end: Int -> Option { if at >= end { None } else { let byte = bytes.read_u8 b at if byte == 0 { Some(at) } else { find_zero b (at + 1) end } } } fn code_string :: code: Int -> String { match bytes.to_string (bytes.from_list [code]) { Ok(s) -> s, Error(_) -> "?" } }