1
0
mirror of https://github.com/aziascreations/BakaShrot.git synced 2026-11-23 20:58:46 +01:00

Moved the PureBasic version to OldSource/, Started the Rust rewrite in Source/

The rewrite's plan and decisions are in revamp.md. Steps 0 to 10 are done:
the workspace and checks, bakashrot-proto, bakashrot-pki and
bakashrot-cert, bakashrot-config, bakashrot-storage (schema v9), the
server and the client library (every request but replication's,
attachments and retention included), the C DLL with its C, PureBasic and
Python bindings, and the bakashrot tool. Step 11 (replication) is next.

OldSource/ is the old implementation, kept building and passing as the
reference.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RwFeVTGs2SsufaH6zquzcb
This commit is contained in:
2026-11-14 12:47:40 +01:00
parent d0048b17c8
commit e044fcf359
225 changed files with 21849 additions and 123 deletions
+11
View File
@@ -0,0 +1,11 @@
# The C runtime linked statically on Windows (MSVC): the DLL and the
# programs need no Visual C++ redistributable (../revamp.md, "Decided" 2).
[target.'cfg(all(windows, target_env = "msvc"))']
rustflags = ["-C", "target-feature=+crt-static"]
# aws-lc seeds its random generator from the OS's (and RDRAND), without CPU
# Jitter Entropy: that one takes about 25 ms in every process, at its first
# connection (every tool command, every script through the DLL). Decided
# 2026-11-14 (../revamp.md, "Randomness from the OS"; ../docs/certificates.md).
[env]
AWS_LC_SYS_NO_JITTER_ENTROPY = "1"
+3
View File
@@ -0,0 +1,3 @@
# The new sources use LF everywhere, whatever the platform.
* text=auto eol=lf
*.ps1 text eol=crlf
+1423
View File
File diff suppressed because it is too large Load Diff
+32
View File
@@ -0,0 +1,32 @@
# The BakaShrot workspace: every crate is in crates/, see README.md for the
# layout and ../revamp.md for the plan.
[workspace]
resolver = "3"
members = ["crates/*"]
[workspace.package]
version = "0.0.1"
edition = "2024"
rust-version = "1.100"
license = "CC0-1.0"
authors = ["Herwin Bozet (NibblePoker)"]
repository = "https://github.com/aziascreations/BakaShrot"
publish = false
# Every crate takes these with `[lints] workspace = true`. `unsafe_code` is
# "deny", not "forbid", so the C API crate can allow it at its root.
[workspace.lints.rust]
unsafe_code = "deny"
missing_docs = "warn"
[workspace.lints.clippy]
all = { level = "warn", priority = -1 }
[profile.release]
lto = true
codegen-units = 1
strip = true
# Kept on purpose: the C DLL catches panics at every export (catch_unwind),
# which "abort" would make impossible.
panic = "unwind"
+57
View File
@@ -0,0 +1,57 @@
# BakaShrot - new sources (Rust)
The new implementation, see `../revamp.md` (why, decisions, the plan and
where it stands).
## Layout
A Cargo workspace. What's marked with a step number is planned, added by
that step of the plan; the rest exists:
```
Source/
Cargo.toml the workspace: shared lints, release profile
rust-toolchain.toml the pinned toolchain (1.100.0)
check.ps1 what CI runs: fmt, clippy, tests, docs
docs/ designs across crates: protocol.md, certificates.md, oid.md, config.md,
storage.md, server.md, client.md
crates/
bakashrot-proto/ packets, frames, names, limits, error codes, shared by everything
bakashrot-pki/ certificates: issuing, identities, CRLs, the TLS setup
bakashrot-config/ the server's config (TOML): topics, retention, replication, roles
bakashrot-storage/ SQLite, schema v9: the writer, reads, attachments, queries
bakashrot-server/ the server: TLS, identities, requests, the writer thread (and its program)
bakashrot-client/ the client library, Rust API, blocking
bakashrot-capi/ the C DLL over bakashrot-client: the BakaShrot_* exports (bakashrot.dll)
bakashrot-tools/ the CLI tools: bakashrot (push, read, query, list), bakashrot-cert
bindings/
c/ bakashrot.h, generated from bakashrot-capi
purebasic/ the prototypes and error codes, as OldSource/Client/'s
python/ bakashrot.py over the DLL, check_bakashrot.py (its wheel: 12)
.cargo/config.toml the C runtime linked statically on Windows
tests/ (13) end-to-end suites across processes
```
Dependencies only point downward: `proto`, `pki`, `config` and `storage`
don't open sockets and are tested on their own; `server` and `client` use
them; the DLL and the tools only use `client`.
## Building and checking
- `cargo build`, `cargo test` from `Source/` (rustup picks the pinned
toolchain).
- `powershell -ExecutionPolicy Bypass -File Source\check.ps1`: everything
CI checks (`../.github/workflows/source.yml`), warnings are errors.
- Output in `target/` (git-ignored). Generated keys and certificates never
go in git.
## Conventions
- LF line endings (`.gitattributes`), rustfmt's defaults.
- Every public item documented (`missing_docs`), no `unsafe` outside the C
API crate.
- A crate's root docs say what it does; designs that span crates go in
`docs/`, updated with the code.
- Use existing crates rather than reimplementing (MessagePack is `rmp-serde`).
- Protocol changes update `docs/protocol.md`; error codes are never
renumbered, packet ids never reused.
+355
View File
@@ -0,0 +1,355 @@
/*
* BakaShrot's client DLL: bakashrot.dll (Windows), libbakashrot.so (Linux).
* Generated by cbindgen from Source/crates/bakashrot-capi: don't edit.
* Source/docs/client.md has the conventions and the whole API.
*/
#ifndef BAKASHROT_H
#define BAKASHROT_H
#include <stdarg.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
/**
* Why the last call failed: a protocol error code (1-99 a server's
* refusal, the connection still open; 100 and up the client's own), 0 if
* it succeeded. Getters don't change it.
*/
int32_t BakaShrot_GetLastError(void);
/**
* Why the last call failed, in words: the server's reason for a refusal,
* the client's otherwise. Empty if it succeeded.
*/
ptrdiff_t BakaShrot_GetRefusalReasonA(char *buffer, ptrdiff_t size);
/**
* The same as `BakaShrot_GetRefusalReasonA`, in UTF-16.
*/
ptrdiff_t BakaShrot_GetRefusalReasonW(uint16_t *buffer, ptrdiff_t size);
/**
* Sets the CA's certificate, which the server's must be issued by: PEM
* text, or the path of a file holding it. Before connecting.
*/
ptrdiff_t BakaShrot_SetCaCertificateA(const char *certificate);
/**
* The same as `BakaShrot_SetCaCertificateA`, in UTF-16.
*/
ptrdiff_t BakaShrot_SetCaCertificateW(const uint16_t *certificate);
/**
* Sets this client's certificate, which says its node and its roles: PEM
* text, or the path of a file holding it. Before connecting.
*/
ptrdiff_t BakaShrot_SetCertificateA(const char *certificate);
/**
* The same as `BakaShrot_SetCertificateA`, in UTF-16.
*/
ptrdiff_t BakaShrot_SetCertificateW(const uint16_t *certificate);
/**
* Sets this client's private key, its certificate's: PEM text, or the path
* of a file holding it. Before connecting.
*/
ptrdiff_t BakaShrot_SetPrivateKeyA(const char *key);
/**
* The same as `BakaShrot_SetPrivateKeyA`, in UTF-16.
*/
ptrdiff_t BakaShrot_SetPrivateKeyW(const uint16_t *key);
/**
* Sets the CA's CRL, optional: servers it revokes are refused. PEM text,
* or the path of a file holding it; null or empty for none. Before
* connecting.
*/
ptrdiff_t BakaShrot_SetCrlA(const char *crl);
/**
* The same as `BakaShrot_SetCrlA`, in UTF-16.
*/
ptrdiff_t BakaShrot_SetCrlW(const uint16_t *crl);
/**
* Connects to the server at `host` (a name or an address) and `port`:
* TLS with the certificates set, then the server says who this client is
* (`BakaShrot_GetNode()`). Refused: the code says by whom (`AuthRejected`
* the server refused the certificate, `ServerNotVerified` this client
* refused the server's, `NotAllowed` none of its roles is the server's).
*/
ptrdiff_t BakaShrot_ConnectA(const char *host, int32_t port);
/**
* The same as `BakaShrot_ConnectA`, in UTF-16.
*/
ptrdiff_t BakaShrot_ConnectW(const uint16_t *host, int32_t port);
/**
* 1 while connected: notices when the server closed the connection
* (forgotten then: connect again).
*/
ptrdiff_t BakaShrot_IsConnected(void);
/**
* Closes the connection: 0 if there was none. The settings stay.
*/
ptrdiff_t BakaShrot_Disconnect(void);
/**
* The node this client is, as the server said when connecting: its
* certificate's name. Empty when not connected.
*/
ptrdiff_t BakaShrot_GetNodeA(char *buffer, ptrdiff_t size);
/**
* The same as `BakaShrot_GetNodeA`, in UTF-16.
*/
ptrdiff_t BakaShrot_GetNodeW(uint16_t *buffer, ptrdiff_t size);
/**
* Pushes a message (JSON or not) to `topic`, as this client's node: its
* id (1 and up), -1 on failure. A push whose answer was lost
* (`ConnectionLost`) may have been stored all the same.
*/
int64_t BakaShrot_PushMessageToA(const char *topic, const char *data);
/**
* The same as `BakaShrot_PushMessageToA`, in UTF-16.
*/
int64_t BakaShrot_PushMessageToW(const uint16_t *topic, const uint16_t *data);
/**
* Gets the latest message of `topic` and `node`, then read with the
* `BakaShrot_GetMessage*()` getters. `NotFound` if there's none yet.
*/
ptrdiff_t BakaShrot_GetLatestMessageOfA(const char *topic, const char *node);
/**
* The same as `BakaShrot_GetLatestMessageOfA`, in UTF-16.
*/
ptrdiff_t BakaShrot_GetLatestMessageOfW(const uint16_t *topic, const uint16_t *node);
/**
* Gets the messages of `topic` and `node` after id `after` (0 for the
* first ones), in order: `limit` at most (1-10000), fewer past about
* 1 MB. Returns how many came (none isn't a failure), -1 on failure. The
* first is selected; `BakaShrot_SelectMessage()` selects the others,
* `BakaShrot_HasMoreMessages()` says whether more follow the last one.
*/
int32_t BakaShrot_GetMessagesA(const char *topic, const char *node, int64_t after, int32_t limit);
/**
* The same as `BakaShrot_GetMessagesA`, in UTF-16.
*/
int32_t BakaShrot_GetMessagesW(const uint16_t *topic,
const uint16_t *node,
int64_t after,
int32_t limit);
/**
* How many messages the last `GetMessages` or `GetLatestMessageOf` got.
*/
int32_t BakaShrot_GetMessageCount(void);
/**
* Selects the message at `index` (0 to the count - 1) for the getters: 0
* if there's none there (`InvalidArgument`), the selection unchanged.
*/
ptrdiff_t BakaShrot_SelectMessage(int32_t index);
/**
* 1 if more messages follow the last one the last `GetMessages` got: ask
* again after its id.
*/
ptrdiff_t BakaShrot_HasMoreMessages(void);
/**
* The selected message's id, 0 if none.
*/
int64_t BakaShrot_GetMessageId(void);
/**
* When the selected message was pushed, by the server it was pushed to:
* milliseconds since 1970-01-01 UTC, 0 if none.
*/
int64_t BakaShrot_GetMessagePushedAt(void);
/**
* The selected message's attachment's size, 0 without one.
*/
int64_t BakaShrot_GetMessageAttachmentSize(void);
/**
* 1 if the selected message's attachment is all on this server (a
* replicated one may still be on its way).
*/
ptrdiff_t BakaShrot_IsMessageAttachmentReady(void);
/**
* The selected message's data, as pushed (JSON or not).
*/
ptrdiff_t BakaShrot_GetMessageDataA(char *buffer, ptrdiff_t size);
/**
* The same as `BakaShrot_GetMessageDataA`, in UTF-16.
*/
ptrdiff_t BakaShrot_GetMessageDataW(uint16_t *buffer, ptrdiff_t size);
/**
* The topic the last `GetMessages` or `GetLatestMessageOf` asked for.
*/
ptrdiff_t BakaShrot_GetMessageTopicA(char *buffer, ptrdiff_t size);
/**
* The same as `BakaShrot_GetMessageTopicA`, in UTF-16.
*/
ptrdiff_t BakaShrot_GetMessageTopicW(uint16_t *buffer, ptrdiff_t size);
/**
* The node the last `GetMessages` or `GetLatestMessageOf` asked for.
*/
ptrdiff_t BakaShrot_GetMessageNodeA(char *buffer, ptrdiff_t size);
/**
* The same as `BakaShrot_GetMessageNodeA`, in UTF-16.
*/
ptrdiff_t BakaShrot_GetMessageNodeW(uint16_t *buffer, ptrdiff_t size);
/**
* Lists the topics this client may push to or read (every one if it may
* query): how many, -1 on failure. Then `BakaShrot_GetNamesList()`.
*/
int32_t BakaShrot_ListTopics(void);
/**
* Lists every node with messages: how many, -1 on failure. Then
* `BakaShrot_GetNamesList()`.
*/
int32_t BakaShrot_ListNodes(void);
/**
* The last list, as JSON:
* `{"kind":"topic","truncated":false,"names":["logs",...]}`, `truncated`
* if some didn't fit.
*/
ptrdiff_t BakaShrot_GetNamesListA(char *buffer, ptrdiff_t size);
/**
* The same as `BakaShrot_GetNamesListA`, in UTF-16.
*/
ptrdiff_t BakaShrot_GetNamesListW(uint16_t *buffer, ptrdiff_t size);
/**
* Runs read-only SQL on the server (one SELECT or WITH), if this client
* may query. Then `BakaShrot_GetQueryResult()`.
*/
ptrdiff_t BakaShrot_QueryA(const char *sql);
/**
* The same as `BakaShrot_QueryA`, in UTF-16.
*/
ptrdiff_t BakaShrot_QueryW(const uint16_t *sql);
/**
* The last query's result, as JSON:
* `{"columns":[...],"rows":[[...],...]}`, every value a string or null.
*/
ptrdiff_t BakaShrot_GetQueryResultA(char *buffer, ptrdiff_t size);
/**
* The same as `BakaShrot_GetQueryResultA`, in UTF-16.
*/
ptrdiff_t BakaShrot_GetQueryResultW(uint16_t *buffer, ptrdiff_t size);
/**
* Pushes a message with the file at `FilePath` as its attachment (1 byte
* to 1 TiB, the server may take less: `TooBig`): uploaded with it, the
* message stored once all of it came. Its id, -1 on failure. The file is
* read twice (its SHA-256 first): one changed in between is refused
* (`DataMismatch`).
*/
int64_t BakaShrot_PushMessageWithFileA(const char *topic, const char *data, const char *file_path);
/**
* The same as `BakaShrot_PushMessageWithFileA`, in UTF-16.
*/
int64_t BakaShrot_PushMessageWithFileW(const uint16_t *topic,
const uint16_t *data,
const uint16_t *file_path);
/**
* Pushes a message with the `Size` bytes at `Data` as its attachment, as
* `BakaShrot_PushMessageWithFileA` does.
*/
int64_t BakaShrot_PushMessageWithDataA(const char *topic,
const char *data,
const void *attachment,
int64_t size);
/**
* The same as `BakaShrot_PushMessageWithDataA`, in UTF-16.
*/
int64_t BakaShrot_PushMessageWithDataW(const uint16_t *topic,
const uint16_t *data,
const void *attachment,
int64_t size);
/**
* Saves the attachment of `Topic`, `Node`'s message `MessageId` as the
* file at `FilePath` (replaced), read a part at a time and checked with
* its SHA-256: its size, -1 on failure (`NotFound` without one,
* `NotReady` if it isn't on this server yet, `AttachmentMismatch`). A
* failed one leaves no file.
*/
int64_t BakaShrot_SaveAttachmentA(const char *topic,
const char *node,
int64_t message_id,
const char *file_path);
/**
* The same as `BakaShrot_SaveAttachmentA`, in UTF-16.
*/
int64_t BakaShrot_SaveAttachmentW(const uint16_t *topic,
const uint16_t *node,
int64_t message_id,
const uint16_t *file_path);
/**
* Reads the attachment of `Topic`, `Node`'s message `MessageId` into
* memory, checked with its SHA-256 (`BakaShrot_SaveAttachmentA` for big
* ones): its size, -1 on failure. Then `BakaShrot_GetAttachmentData()`.
*/
int64_t BakaShrot_LoadAttachmentA(const char *topic, const char *node, int64_t message_id);
/**
* The same as `BakaShrot_LoadAttachmentA`, in UTF-16.
*/
int64_t BakaShrot_LoadAttachmentW(const uint16_t *topic, const uint16_t *node, int64_t message_id);
/**
* Copies what the last `BakaShrot_LoadAttachment()` read into `Buffer`, if
* `BufferSize` is enough: returns its size (0 if none), copies nothing if
* it doesn't fit (a null `Buffer` asks for the size).
*/
int64_t BakaShrot_GetAttachmentData(void *buffer, int64_t buffer_size);
/**
* Frees what `BakaShrot_LoadAttachment()` read: 1.
*/
ptrdiff_t BakaShrot_FreeAttachmentData(void);
#ifdef __cplusplus
} // extern "C"
#endif // __cplusplus
#endif /* BAKASHROT_H */
@@ -0,0 +1,322 @@
;{- Code Header
; ==- Basic Info -================================
; Name: BakaShrot_Client_Prototypes.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; BakaShrot client DLL - Prototypes
;
; Include this in an app to use bakashrot.dll (libbakashrot.so on Linux):
; XIncludeFile "BakaShrot_Client_Prototypes.pbi"
; If BakaShrot_LoadClient("bakashrot.dll")
; BakaShrot_SetCaCertificate("ca.crt") ; a file, or PEM text
; BakaShrot_SetCertificate("kitchen.crt")
; BakaShrot_SetPrivateKey("kitchen.key")
; If BakaShrot_Connect("10.0.0.2", 7000)
; BakaShrot_PushMessageTo("logs", ~"{\"temp\": 21}")
; ...
; EndIf
; BakaShrot_UnloadClient()
; EndIf
;
; Source/docs/client.md has what each function does (and
; Source/bindings/c/bakashrot.h, generated from the DLL). The string
; functions are mapped to the DLL's W (UTF-16) variants. After a failed
; call, BakaShrot_GetLastError() tells why: the codes and what to do about
; each are in BakaShrot_ErrorCodes.pbi, next to this file (included below),
; BakaShrot_ErrorName() names them; BakaShrot_GetRefusalReasonString() says
; why in words.
;
; Changed from the PureBasic DLL (protocol 6): certificates instead of keys
; and a node (BakaShrot_SetCaCertificate(), _SetCertificate(),
; _SetPrivateKey() now a PEM key, _SetCrl()); a push always names its topic
; (BakaShrot_PushMessage() is gone); no ids (_GetLatestMessage(TopicId,
; NodeId), _SetNodeId(), _GetMessageTopicId/NodeId(), _ResolveTopic/Node(),
; _GetResolvedName() are gone); _GetNamesList() is
; {"kind":"topic","names":[...],"truncated":false}. New: _GetNode().
; Attachments: the same six as before, by names.
; ============================================================================
XIncludeFile "BakaShrot_ErrorCodes.pbi"
PrototypeC.l BakaShrot_GetLastError_Prototype()
PrototypeC.i BakaShrot_GetRefusalReason_Prototype(*Buffer, BufferSize.i)
PrototypeC.i BakaShrot_SetCaCertificate_Prototype(Certificate.p-unicode)
PrototypeC.i BakaShrot_SetCertificate_Prototype(Certificate.p-unicode)
PrototypeC.i BakaShrot_SetPrivateKey_Prototype(PrivateKey.p-unicode)
PrototypeC.i BakaShrot_SetCrl_Prototype(Crl.p-unicode)
PrototypeC.i BakaShrot_Connect_Prototype(Host.p-unicode, Port.l)
PrototypeC.i BakaShrot_IsConnected_Prototype()
PrototypeC.i BakaShrot_Disconnect_Prototype()
PrototypeC.i BakaShrot_GetNode_Prototype(*Buffer, BufferSize.i)
PrototypeC.q BakaShrot_PushMessageTo_Prototype(Topic.p-unicode, JsonData.p-unicode)
PrototypeC.i BakaShrot_GetLatestMessageOf_Prototype(Topic.p-unicode, Node.p-unicode)
PrototypeC.l BakaShrot_GetMessages_Prototype(Topic.p-unicode, Node.p-unicode, AfterMessageId.q, Limit.l)
PrototypeC.l BakaShrot_GetMessageCount_Prototype()
PrototypeC.i BakaShrot_SelectMessage_Prototype(Index.l)
PrototypeC.i BakaShrot_HasMoreMessages_Prototype()
PrototypeC.q BakaShrot_GetMessageId_Prototype()
PrototypeC.q BakaShrot_GetMessagePushedAt_Prototype()
PrototypeC.q BakaShrot_GetMessageAttachmentSize_Prototype()
PrototypeC.i BakaShrot_IsMessageAttachmentReady_Prototype()
PrototypeC.i BakaShrot_GetMessageData_Prototype(*Buffer, BufferSize.i)
PrototypeC.i BakaShrot_GetMessageTopic_Prototype(*Buffer, BufferSize.i)
PrototypeC.i BakaShrot_GetMessageNode_Prototype(*Buffer, BufferSize.i)
PrototypeC.l BakaShrot_ListTopics_Prototype()
PrototypeC.l BakaShrot_ListNodes_Prototype()
PrototypeC.i BakaShrot_GetNamesList_Prototype(*Buffer, BufferSize.i)
PrototypeC.i BakaShrot_Query_Prototype(Sql.p-unicode)
PrototypeC.i BakaShrot_GetQueryResult_Prototype(*Buffer, BufferSize.i)
PrototypeC.q BakaShrot_PushMessageWithFile_Prototype(Topic.p-unicode, JsonData.p-unicode, FilePath.p-unicode)
PrototypeC.q BakaShrot_PushMessageWithData_Prototype(Topic.p-unicode, JsonData.p-unicode, *Data, Size.q)
PrototypeC.q BakaShrot_SaveAttachment_Prototype(Topic.p-unicode, Node.p-unicode, MessageId.q, FilePath.p-unicode)
PrototypeC.q BakaShrot_LoadAttachment_Prototype(Topic.p-unicode, Node.p-unicode, MessageId.q)
PrototypeC.q BakaShrot_GetAttachmentData_Prototype(*Buffer, BufferSize.q)
PrototypeC.i BakaShrot_FreeAttachmentData_Prototype()
Global BakaShrot_GetLastError.BakaShrot_GetLastError_Prototype
Global BakaShrot_GetRefusalReason.BakaShrot_GetRefusalReason_Prototype
Global BakaShrot_SetCaCertificate.BakaShrot_SetCaCertificate_Prototype
Global BakaShrot_SetCertificate.BakaShrot_SetCertificate_Prototype
Global BakaShrot_SetPrivateKey.BakaShrot_SetPrivateKey_Prototype
Global BakaShrot_SetCrl.BakaShrot_SetCrl_Prototype
Global BakaShrot_Connect.BakaShrot_Connect_Prototype
Global BakaShrot_IsConnected.BakaShrot_IsConnected_Prototype
Global BakaShrot_Disconnect.BakaShrot_Disconnect_Prototype
Global BakaShrot_GetNode.BakaShrot_GetNode_Prototype
Global BakaShrot_PushMessageTo.BakaShrot_PushMessageTo_Prototype
Global BakaShrot_GetLatestMessageOf.BakaShrot_GetLatestMessageOf_Prototype
Global BakaShrot_GetMessages.BakaShrot_GetMessages_Prototype
Global BakaShrot_GetMessageCount.BakaShrot_GetMessageCount_Prototype
Global BakaShrot_SelectMessage.BakaShrot_SelectMessage_Prototype
Global BakaShrot_HasMoreMessages.BakaShrot_HasMoreMessages_Prototype
Global BakaShrot_GetMessageId.BakaShrot_GetMessageId_Prototype
Global BakaShrot_GetMessagePushedAt.BakaShrot_GetMessagePushedAt_Prototype
Global BakaShrot_GetMessageAttachmentSize.BakaShrot_GetMessageAttachmentSize_Prototype
Global BakaShrot_IsMessageAttachmentReady.BakaShrot_IsMessageAttachmentReady_Prototype
Global BakaShrot_GetMessageData.BakaShrot_GetMessageData_Prototype
Global BakaShrot_GetMessageTopic.BakaShrot_GetMessageTopic_Prototype
Global BakaShrot_GetMessageNode.BakaShrot_GetMessageNode_Prototype
Global BakaShrot_ListTopics.BakaShrot_ListTopics_Prototype
Global BakaShrot_ListNodes.BakaShrot_ListNodes_Prototype
Global BakaShrot_GetNamesList.BakaShrot_GetNamesList_Prototype
Global BakaShrot_Query.BakaShrot_Query_Prototype
Global BakaShrot_GetQueryResult.BakaShrot_GetQueryResult_Prototype
Global BakaShrot_PushMessageWithFile.BakaShrot_PushMessageWithFile_Prototype
Global BakaShrot_PushMessageWithData.BakaShrot_PushMessageWithData_Prototype
Global BakaShrot_SaveAttachment.BakaShrot_SaveAttachment_Prototype
Global BakaShrot_LoadAttachment.BakaShrot_LoadAttachment_Prototype
Global BakaShrot_GetAttachmentData.BakaShrot_GetAttachmentData_Prototype
Global BakaShrot_FreeAttachmentData.BakaShrot_FreeAttachmentData_Prototype
Global BakaShrot_ClientLibrary.i = 0
; The first export BakaShrot_LoadClient() didn't find, "" if none.
Global BakaShrot_ClientMissing.s = ""
; Unloads the DLL loaded by BakaShrot_LoadClient().
Procedure BakaShrot_UnloadClient()
If BakaShrot_ClientLibrary
CloseLibrary(BakaShrot_ClientLibrary)
BakaShrot_ClientLibrary = 0
EndIf
EndProcedure
; An export of the DLL, noted in BakaShrot_ClientMissing if it has none.
Procedure.i BakaShrot_ClientFunction(Name.s)
Protected *Function = GetFunction(BakaShrot_ClientLibrary, Name)
If Not *Function And BakaShrot_ClientMissing = ""
BakaShrot_ClientMissing = Name
EndIf
ProcedureReturn *Function
EndProcedure
; Loads the DLL at DllPath and fills the function pointers above.
; Returns #False if the DLL can't be loaded or an export is missing (an
; older DLL: BakaShrot_ClientMissing says which).
Procedure.i BakaShrot_LoadClient(DllPath.s)
If BakaShrot_ClientLibrary
ProcedureReturn #False
EndIf
BakaShrot_ClientLibrary = OpenLibrary(#PB_Any, DllPath)
If Not BakaShrot_ClientLibrary
ProcedureReturn #False
EndIf
BakaShrot_ClientMissing = ""
; PureBasic strings are UTF-16, so the W variants are used.
BakaShrot_GetLastError = BakaShrot_ClientFunction("BakaShrot_GetLastError")
BakaShrot_GetRefusalReason = BakaShrot_ClientFunction("BakaShrot_GetRefusalReasonW")
BakaShrot_SetCaCertificate = BakaShrot_ClientFunction("BakaShrot_SetCaCertificateW")
BakaShrot_SetCertificate = BakaShrot_ClientFunction("BakaShrot_SetCertificateW")
BakaShrot_SetPrivateKey = BakaShrot_ClientFunction("BakaShrot_SetPrivateKeyW")
BakaShrot_SetCrl = BakaShrot_ClientFunction("BakaShrot_SetCrlW")
BakaShrot_Connect = BakaShrot_ClientFunction("BakaShrot_ConnectW")
BakaShrot_IsConnected = BakaShrot_ClientFunction("BakaShrot_IsConnected")
BakaShrot_Disconnect = BakaShrot_ClientFunction("BakaShrot_Disconnect")
BakaShrot_GetNode = BakaShrot_ClientFunction("BakaShrot_GetNodeW")
BakaShrot_PushMessageTo = BakaShrot_ClientFunction("BakaShrot_PushMessageToW")
BakaShrot_GetLatestMessageOf = BakaShrot_ClientFunction("BakaShrot_GetLatestMessageOfW")
BakaShrot_GetMessages = BakaShrot_ClientFunction("BakaShrot_GetMessagesW")
BakaShrot_GetMessageCount = BakaShrot_ClientFunction("BakaShrot_GetMessageCount")
BakaShrot_SelectMessage = BakaShrot_ClientFunction("BakaShrot_SelectMessage")
BakaShrot_HasMoreMessages = BakaShrot_ClientFunction("BakaShrot_HasMoreMessages")
BakaShrot_GetMessageId = BakaShrot_ClientFunction("BakaShrot_GetMessageId")
BakaShrot_GetMessagePushedAt = BakaShrot_ClientFunction("BakaShrot_GetMessagePushedAt")
BakaShrot_GetMessageAttachmentSize = BakaShrot_ClientFunction("BakaShrot_GetMessageAttachmentSize")
BakaShrot_IsMessageAttachmentReady = BakaShrot_ClientFunction("BakaShrot_IsMessageAttachmentReady")
BakaShrot_GetMessageData = BakaShrot_ClientFunction("BakaShrot_GetMessageDataW")
BakaShrot_GetMessageTopic = BakaShrot_ClientFunction("BakaShrot_GetMessageTopicW")
BakaShrot_GetMessageNode = BakaShrot_ClientFunction("BakaShrot_GetMessageNodeW")
BakaShrot_ListTopics = BakaShrot_ClientFunction("BakaShrot_ListTopics")
BakaShrot_ListNodes = BakaShrot_ClientFunction("BakaShrot_ListNodes")
BakaShrot_GetNamesList = BakaShrot_ClientFunction("BakaShrot_GetNamesListW")
BakaShrot_Query = BakaShrot_ClientFunction("BakaShrot_QueryW")
BakaShrot_GetQueryResult = BakaShrot_ClientFunction("BakaShrot_GetQueryResultW")
BakaShrot_PushMessageWithFile = BakaShrot_ClientFunction("BakaShrot_PushMessageWithFileW")
BakaShrot_PushMessageWithData = BakaShrot_ClientFunction("BakaShrot_PushMessageWithDataW")
BakaShrot_SaveAttachment = BakaShrot_ClientFunction("BakaShrot_SaveAttachmentW")
BakaShrot_LoadAttachment = BakaShrot_ClientFunction("BakaShrot_LoadAttachmentW")
BakaShrot_GetAttachmentData = BakaShrot_ClientFunction("BakaShrot_GetAttachmentData")
BakaShrot_FreeAttachmentData = BakaShrot_ClientFunction("BakaShrot_FreeAttachmentData")
If BakaShrot_ClientMissing <> ""
BakaShrot_UnloadClient()
ProcedureReturn #False
EndIf
ProcedureReturn #True
EndProcedure
; Calls a string getter of the DLL (Getter(*Buffer, BufferSize)) and
; returns the string: asks for the size, then copies.
PrototypeC.i BakaShrot_StringGetter_Prototype(*Buffer, BufferSize.i)
Procedure.s BakaShrot_GetString(Getter.BakaShrot_StringGetter_Prototype)
Protected *Buffer, BufferSize.i, Text.s
BufferSize = Getter(0, 0)
*Buffer = AllocateMemory(BufferSize)
If Not *Buffer
ProcedureReturn ""
EndIf
Getter(*Buffer, BufferSize)
Text = PeekS(*Buffer, -1, #PB_Unicode)
FreeMemory(*Buffer)
ProcedureReturn Text
EndProcedure
; The string getters, as strings.
Procedure.s BakaShrot_GetRefusalReasonString()
ProcedureReturn BakaShrot_GetString(BakaShrot_GetRefusalReason)
EndProcedure
Procedure.s BakaShrot_GetNodeString()
ProcedureReturn BakaShrot_GetString(BakaShrot_GetNode)
EndProcedure
Procedure.s BakaShrot_GetMessageDataString()
ProcedureReturn BakaShrot_GetString(BakaShrot_GetMessageData)
EndProcedure
Procedure.s BakaShrot_GetMessageTopicString()
ProcedureReturn BakaShrot_GetString(BakaShrot_GetMessageTopic)
EndProcedure
Procedure.s BakaShrot_GetMessageNodeString()
ProcedureReturn BakaShrot_GetString(BakaShrot_GetMessageNode)
EndProcedure
Procedure.s BakaShrot_GetNamesListString()
ProcedureReturn BakaShrot_GetString(BakaShrot_GetNamesList)
EndProcedure
Procedure.s BakaShrot_GetQueryResultString()
ProcedureReturn BakaShrot_GetString(BakaShrot_GetQueryResult)
EndProcedure
; Usage example. Only compiled when this file is run directly (F5 in the
; IDE), not when it's included by an app.
; ClientExample <DllPath> <CaFile> <CertificateFile> <KeyFile> <Host> <Port>
; Pushes a message to "logs", reads it back, pushes one with an
; attachment and reads that back, lists the topics.
CompilerIf #PB_Compiler_IsMainFile
Define Id.q, Size.q, *Attachment, *Copy
; Prints why the last call failed, then ends.
Procedure Failed(What.s)
PrintN(What + " failed: " + BakaShrot_ErrorName(BakaShrot_GetLastError()) + ", " + BakaShrot_GetRefusalReasonString())
BakaShrot_UnloadClient()
End 1
EndProcedure
OpenConsole()
If CountProgramParameters() < 6
PrintN("Usage: ClientExample <DllPath> <CaFile> <CertificateFile> <KeyFile> <Host> <Port>")
End 2
EndIf
If Not BakaShrot_LoadClient(ProgramParameter(0))
PrintN("Failed to load " + ProgramParameter(0) + " " + BakaShrot_ClientMissing)
End 1
EndIf
If Not BakaShrot_SetCaCertificate(ProgramParameter(1)) : Failed("Setting the CA's certificate") : EndIf
If Not BakaShrot_SetCertificate(ProgramParameter(2)) : Failed("Setting the certificate") : EndIf
If Not BakaShrot_SetPrivateKey(ProgramParameter(3)) : Failed("Setting the private key") : EndIf
If Not BakaShrot_Connect(ProgramParameter(4), Val(ProgramParameter(5))) : Failed("Connecting") : EndIf
PrintN("Connected as " + BakaShrot_GetNodeString())
Id = BakaShrot_PushMessageTo("logs", ~"{\"from\": \"PureBasic\", \"text\": \"hello\"}")
If Id < 1 : Failed("Pushing") : EndIf
PrintN("Pushed #" + Str(Id))
If Not BakaShrot_GetLatestMessageOf("logs", BakaShrot_GetNodeString()) : Failed("Reading") : EndIf
PrintN("Latest: #" + Str(BakaShrot_GetMessageId()) + " " + BakaShrot_GetMessageDataString())
*Attachment = AllocateMemory(3000)
FillMemory(*Attachment, 3000, 42, #PB_Byte)
Id = BakaShrot_PushMessageWithData("logs", ~"{\"photo\": 1}", *Attachment, 3000)
If Id < 1 : Failed("Pushing an attachment") : EndIf
Size = BakaShrot_LoadAttachment("logs", BakaShrot_GetNodeString(), Id)
If Size < 0 : Failed("Reading the attachment") : EndIf
*Copy = AllocateMemory(Size)
BakaShrot_GetAttachmentData(*Copy, Size)
BakaShrot_FreeAttachmentData()
If CompareMemory(*Attachment, *Copy, 3000)
PrintN("Pushed #" + Str(Id) + " with " + Str(Size) + " bytes, read back the same")
Else
PrintN("The attachment read back differs")
End 1
EndIf
FreeMemory(*Attachment) : FreeMemory(*Copy)
If BakaShrot_ListTopics() < 0 : Failed("Listing") : EndIf
PrintN("Topics: " + BakaShrot_GetNamesListString())
If BakaShrot_PushMessageTo("nothing", "{}") < 0
PrintN("A push to an unknown topic: " + BakaShrot_ErrorName(BakaShrot_GetLastError()) + ", " + BakaShrot_GetRefusalReasonString())
EndIf
BakaShrot_Disconnect()
PrintN("IsConnected after disconnecting: " + Str(BakaShrot_IsConnected()))
BakaShrot_UnloadClient()
End 0
CompilerEndIf
@@ -0,0 +1,144 @@
;{- Code Header
; ==- Basic Info -================================
; Name: BakaShrot_ErrorCodes.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; BakaShrot error codes
;
; What BakaShrot_GetLastError() returns after a failed call of the client DLL
; (bakashrot.dll), and the code a server sends with each refusal (protocol 7,
; Source/crates/bakashrot-proto/src/error.rs, the same numbers as protocol 6).
; The Python client has them in bakashrot.ErrorCode. Shipped next to
; BakaShrot_Client_Prototypes.pbi, which includes it.
;
; 0 no error (the last call succeeded)
; 1-99 refused by the server: the connection is still open, see
; BakaShrot_GetRefusalReason() for the details
; 100+ the client's own: the connection, the arguments, the files
;
; What to do about each:
; reconnect, then retry: NotConnected, ConnectFailed, ConnectionLost,
; ProtocolError (the connection is closed)
; retry later: NotReady (an attachment still on its way),
; ServerError (the server's storage failed)
; fix the certificates or
; the server's config: AuthRejected, ServerNotVerified, NotAllowed,
; UnknownName, VersionMismatch
; fix the call: InvalidArgument, InvalidRequest, TooBig,
; QueryFailed, FileError
; gone, or not yet there: NotFound
; sent again by itself: DataMismatch, AttachmentMismatch
;
; A push whose answer was lost (ConnectionLost) may still have been stored:
; pushing it again can store it twice, under the next id. Delivery is at
; least once; check the latest message first if a duplicate matters.
; ============================================================================
; --- Refused by the server (RequestRefused's code) ----------------------------
; Not allowed to this client: its roles' permissions (or, when connecting,
; none of its roles is the server's).
#BakaShrot_Refused_NotAllowed = 1
; A topic or node this server doesn't know.
#BakaShrot_Refused_UnknownName = 2
; No such message or attachment.
#BakaShrot_Refused_NotFound = 3
; The attachment isn't on this server yet (still being replicated).
#BakaShrot_Refused_NotReady = 4
; A message, attachment or query result over a limit, or an attachment
; bigger than this server keeps.
#BakaShrot_Refused_TooBig = 5
; Protocol 6's (a push without a topic): never sent any more.
#BakaShrot_Refused_NoDefaultTopic = 6
; A request that doesn't fit: an attachment's parts not matching its size,
; a part that doesn't exist...
#BakaShrot_Refused_InvalidRequest = 7
; An uploaded attachment that doesn't match its SHA-256: dropped.
#BakaShrot_Refused_DataMismatch = 8
; The SQL of a query failed (its error in the reason).
#BakaShrot_Refused_QueryFailed = 9
; The server couldn't store or read something: its database failed.
#BakaShrot_Refused_ServerError = 10
; The highest a refusal can have, anything above is the client's own.
#BakaShrot_Refused_Max = 99
; --- The client's own (BakaShrot_GetLastError()) --------------------------------
#BakaShrot_Error_None = 0
; Not connected: never, or the connection was closed or lost before.
#BakaShrot_Error_NotConnected = 100
; The server couldn't be reached at that host and port.
#BakaShrot_Error_ConnectFailed = 101
; The server refused this client's certificate: another CA's, revoked,
; expired.
#BakaShrot_Error_AuthRejected = 102
; This client refused the server's certificate: not the CA's, or revoked.
#BakaShrot_Error_ServerNotVerified = 103
; The connection broke during a request (it's closed now). A push may
; still have been stored.
#BakaShrot_Error_ConnectionLost = 104
; The server answered something unexpected or malformed: the connection is
; closed.
#BakaShrot_Error_ProtocolError = 105
; A bad argument: a topic or node that isn't a name, a null pointer, a
; message over the limit, a certificate missing before connecting.
#BakaShrot_Error_InvalidArgument = 106
; A file couldn't be opened, read or written.
#BakaShrot_Error_FileError = 107
; A downloaded attachment doesn't match its SHA-256.
#BakaShrot_Error_AttachmentMismatch = 108
; Already connected: disconnect first.
#BakaShrot_Error_AlreadyConnected = 109
; A failure inside the DLL.
#BakaShrot_Error_Internal = 110
; The server speaks another version of the protocol: update one or the
; other.
#BakaShrot_Error_VersionMismatch = 111
; The name of an error code, as the constants have it ("NotFound"), or
; "Error <code>" for an unknown one.
Procedure.s BakaShrot_ErrorName(Code.l)
Select Code
Case #BakaShrot_Error_None : ProcedureReturn "None"
Case #BakaShrot_Refused_NotAllowed : ProcedureReturn "NotAllowed"
Case #BakaShrot_Refused_UnknownName : ProcedureReturn "UnknownName"
Case #BakaShrot_Refused_NotFound : ProcedureReturn "NotFound"
Case #BakaShrot_Refused_NotReady : ProcedureReturn "NotReady"
Case #BakaShrot_Refused_TooBig : ProcedureReturn "TooBig"
Case #BakaShrot_Refused_NoDefaultTopic : ProcedureReturn "NoDefaultTopic"
Case #BakaShrot_Refused_InvalidRequest : ProcedureReturn "InvalidRequest"
Case #BakaShrot_Refused_DataMismatch : ProcedureReturn "DataMismatch"
Case #BakaShrot_Refused_QueryFailed : ProcedureReturn "QueryFailed"
Case #BakaShrot_Refused_ServerError : ProcedureReturn "ServerError"
Case #BakaShrot_Error_NotConnected : ProcedureReturn "NotConnected"
Case #BakaShrot_Error_ConnectFailed : ProcedureReturn "ConnectFailed"
Case #BakaShrot_Error_AuthRejected : ProcedureReturn "AuthRejected"
Case #BakaShrot_Error_ServerNotVerified : ProcedureReturn "ServerNotVerified"
Case #BakaShrot_Error_ConnectionLost : ProcedureReturn "ConnectionLost"
Case #BakaShrot_Error_ProtocolError : ProcedureReturn "ProtocolError"
Case #BakaShrot_Error_InvalidArgument : ProcedureReturn "InvalidArgument"
Case #BakaShrot_Error_FileError : ProcedureReturn "FileError"
Case #BakaShrot_Error_AttachmentMismatch : ProcedureReturn "AttachmentMismatch"
Case #BakaShrot_Error_AlreadyConnected : ProcedureReturn "AlreadyConnected"
Case #BakaShrot_Error_Internal : ProcedureReturn "Internal"
Case #BakaShrot_Error_VersionMismatch : ProcedureReturn "VersionMismatch"
EndSelect
ProcedureReturn "Error " + Str(Code)
EndProcedure
; #True for a code a server sends with a refusal (1-99).
Procedure.i BakaShrot_IsRefusalCode(Code.l)
ProcedureReturn Bool(Code >= 1 And Code <= #BakaShrot_Refused_Max)
EndProcedure
+577
View File
@@ -0,0 +1,577 @@
"""BakaShrot client for Python, over the client DLL (bakashrot.dll,
libbakashrot.so).
No dependencies beyond the standard library: the DLL is loaded with ctypes
and does the connecting and talking to the server. Messages come back as
stored, a str that may or may not be JSON: parsing them is up to the app
(Message.json() helps).
from bakashrot import Client
with Client.from_file("client.toml") as client:
message_id = client.push({"temperature": 21.5}, "sensors")
for message in client.get_messages("sensors", client.node, after=0):
print(message.id, message.data)
for message in client.follow("logs", "kitchen"): # until stopped
print(message.id, message.json())
Who the client is comes from its certificate, issued by the CA the server
trusts (bakashrot-cert): its name is its node, its roles say what it may
do. client.toml says where the server is and where the certificates are
(Source/docs/client.md):
server = "10.0.0.2:7000"
ca = "ca.crt"
certificate = "kitchen.crt"
key = "kitchen.key"
# crl = "ca.crl"
Errors are exceptions with a code (`error.code`, an ErrorCode, the same
numbers as the DLL's BakaShrot_GetLastError()):
RefusedError the server refused (codes 1-99), still connected
ConnectionLostError not connected, unreachable, the connection lost or
broken: connect() again (nothing reconnects by itself)
AuthError a certificate refused, either way, or none of its
roles allowed: fix the certificates, retrying won't help
BakaShrotError the rest: a bad argument, a file, the DLL itself
A push whose answer was lost (ConnectionLostError) may have been stored all
the same: pushed again, it's stored twice. Delivery is at least once.
The DLL holds a single connection per process: only one Client may be
connected at a time. Calls are serialized with a lock, so a Client can be
shared between threads, one request at a time.
The DLL is looked for, in order: the dll_path given, the BAKASHROT_DLL
environment variable, next to this file, then in the current directory.
"""
from __future__ import annotations
import ctypes
import enum
import json
import os
import sys
import threading
import time
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Any, Iterator, Optional, Union
__version__ = "0.0.1"
__all__ = [
"Client", "Message", "MessagesPage", "NamesList",
"BakaShrotError", "RefusedError", "ConnectionLostError", "AuthError", "ErrorCode",
"MAX_GET_MESSAGES", "MAX_MESSAGE_SIZE",
]
# The protocol's: Source/crates/bakashrot-proto/src/limits.rs.
MAX_GET_MESSAGES = 10000
MAX_MESSAGE_SIZE = 16 * 1024 * 1024 - 4096
DLL_NAME = "bakashrot.dll" if sys.platform == "win32" else "libbakashrot.so"
class ErrorCode(enum.IntEnum):
"""What failed: the protocol's codes (Source/crates/bakashrot-proto/src/error.rs).
1-99: refused by the server, 100+: the client's own."""
NONE = 0
# Refused by the server, the connection still open.
NOT_ALLOWED = 1 # its roles don't allow it (or none is the server's, when connecting)
UNKNOWN_NAME = 2 # a topic or node this server doesn't know
NOT_FOUND = 3 # no such message or attachment
NOT_READY = 4 # the attachment isn't on this server yet: retry later
TOO_BIG = 5 # over a limit, or more than this server keeps
NO_DEFAULT_TOPIC = 6 # protocol 6's, never sent any more
INVALID_REQUEST = 7 # a request that doesn't fit (parts out of order...)
DATA_MISMATCH = 8 # an upload that doesn't match its SHA-256
QUERY_FAILED = 9 # the SQL failed
SERVER_ERROR = 10 # the server's database failed: retry later
# The client's own.
NOT_CONNECTED = 100 # never connected, or closed or lost before
CONNECT_FAILED = 101 # nothing answers at that host and port
AUTH_REJECTED = 102 # the server refused this client's certificate
SERVER_NOT_VERIFIED = 103 # this client refused the server's certificate
CONNECTION_LOST = 104 # broke during a request (a push may still be stored)
PROTOCOL_ERROR = 105 # an unexpected answer, the connection is closed
INVALID_ARGUMENT = 106
FILE_ERROR = 107
ATTACHMENT_MISMATCH = 108 # a downloaded attachment that doesn't match its SHA-256
ALREADY_CONNECTED = 109
INTERNAL = 110 # a failure inside the DLL, or the DLL missing or too old
VERSION_MISMATCH = 111 # the server speaks another protocol version
@property
def is_refusal(self) -> bool:
return 1 <= self.value <= 99
def _error_code(value: int):
"""An ErrorCode, or the int itself if this module doesn't know it."""
try:
return ErrorCode(value)
except ValueError:
return value
class BakaShrotError(Exception):
"""Something failed: code (an ErrorCode) tells what, see ErrorCode."""
def __init__(self, message: str, code: int = ErrorCode.INTERNAL):
super().__init__(message)
self.code = _error_code(code)
class RefusedError(BakaShrotError):
"""The server refused the request, the connection is still open. code
says why (1-99, e.g. ErrorCode.NOT_FOUND), reason in the server's words."""
def __init__(self, reason: str, code: int):
super().__init__(reason or "Refused", code)
self.reason = reason
class ConnectionLostError(BakaShrotError):
"""Not connected, or the connection failed or was closed (code:
NOT_CONNECTED, CONNECT_FAILED, CONNECTION_LOST, PROTOCOL_ERROR):
connect() again to go on."""
class AuthError(BakaShrotError):
"""Connecting was refused for good: the server refused this client's
certificate (AUTH_REJECTED), this client the server's
(SERVER_NOT_VERIFIED), none of its roles is allowed (NOT_ALLOWED), or
another protocol version (VERSION_MISMATCH). Retrying won't help."""
@dataclass(frozen=True)
class Message:
"""A stored message. data is as stored: JSON or not (json() parses it).
pushed_at: when it was pushed, to whichever server it was pushed to, in
milliseconds since 1970-01-01 UTC (pushed is the same as a datetime).
attachment_size: its attachment's, 0 for none; attachment_ready:
whether all of it is on this server."""
id: int
topic: str
node: str
data: str
pushed_at: int = 0
attachment_size: int = 0
attachment_ready: bool = False
def json(self) -> Any:
"""The data parsed as JSON, raises ValueError if it isn't."""
return json.loads(self.data)
@property
def pushed(self) -> datetime:
"""When it was pushed, as an aware datetime in UTC."""
return datetime.fromtimestamp(self.pushed_at / 1000, tz=timezone.utc)
@dataclass(frozen=True)
class MessagesPage:
"""One answer to get_messages(): in message id order. more is True if
more follow the last one, ask again with after=last_id."""
messages: list = field(default_factory=list)
more: bool = False
@property
def last_id(self) -> Optional[int]:
return self.messages[-1].id if self.messages else None
def __iter__(self):
return iter(self.messages)
def __len__(self):
return len(self.messages)
@dataclass(frozen=True)
class NamesList:
kind: str # "topic" or "node"
names: list
truncated: bool # True if they didn't all fit in one answer
def _name(value: str) -> bytes:
if not isinstance(value, str):
raise TypeError(f"a topic or node is a name, not {value!r}")
return value.encode("utf-8")
def _find_dll(dll_path: Optional[str]) -> str:
candidates = []
if dll_path:
candidates.append(dll_path)
if os.environ.get("BAKASHROT_DLL"):
candidates.append(os.environ["BAKASHROT_DLL"])
candidates.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), DLL_NAME))
candidates.append(os.path.join(os.getcwd(), DLL_NAME))
for candidate in candidates:
if os.path.isfile(candidate):
return os.path.abspath(candidate)
raise BakaShrotError(f"{DLL_NAME} not found, looked at: " + ", ".join(candidates))
class _Dll:
"""The DLL's functions, with their types. Loaded once per process."""
_instance: Optional["_Dll"] = None
_instance_lock = threading.Lock()
@classmethod
def get(cls, dll_path: Optional[str]) -> "_Dll":
with cls._instance_lock:
if cls._instance is None:
cls._instance = cls(_find_dll(dll_path))
return cls._instance
def __init__(self, path: str):
try:
self.lib = ctypes.CDLL(path)
except OSError as error:
raise BakaShrotError(f"Failed to load {path}: {error}") from error
self.path = path
I, L, Q, P, S = ctypes.c_ssize_t, ctypes.c_int32, ctypes.c_int64, ctypes.c_char_p, ctypes.c_void_p
signatures = {
"BakaShrot_GetLastError": (L, []),
"BakaShrot_GetRefusalReasonA": (I, [S, I]),
"BakaShrot_SetCaCertificateA": (I, [P]),
"BakaShrot_SetCertificateA": (I, [P]),
"BakaShrot_SetPrivateKeyA": (I, [P]),
"BakaShrot_SetCrlA": (I, [P]),
"BakaShrot_ConnectA": (I, [P, L]),
"BakaShrot_IsConnected": (I, []),
"BakaShrot_Disconnect": (I, []),
"BakaShrot_GetNodeA": (I, [S, I]),
"BakaShrot_PushMessageToA": (Q, [P, P]),
"BakaShrot_GetLatestMessageOfA": (I, [P, P]),
"BakaShrot_GetMessagesA": (L, [P, P, Q, L]),
"BakaShrot_GetMessageCount": (L, []),
"BakaShrot_SelectMessage": (I, [L]),
"BakaShrot_HasMoreMessages": (I, []),
"BakaShrot_GetMessageId": (Q, []),
"BakaShrot_GetMessagePushedAt": (Q, []),
"BakaShrot_GetMessageAttachmentSize": (Q, []),
"BakaShrot_IsMessageAttachmentReady": (I, []),
"BakaShrot_GetMessageTopicA": (I, [S, I]),
"BakaShrot_GetMessageNodeA": (I, [S, I]),
"BakaShrot_GetMessageDataA": (I, [S, I]),
"BakaShrot_ListTopics": (L, []),
"BakaShrot_ListNodes": (L, []),
"BakaShrot_GetNamesListA": (I, [S, I]),
"BakaShrot_QueryA": (I, [P]),
"BakaShrot_GetQueryResultA": (I, [S, I]),
"BakaShrot_PushMessageWithFileA": (Q, [P, P, P]),
"BakaShrot_PushMessageWithDataA": (Q, [P, P, P, Q]),
"BakaShrot_SaveAttachmentA": (Q, [P, P, Q, P]),
"BakaShrot_LoadAttachmentA": (Q, [P, P, Q]),
"BakaShrot_GetAttachmentData": (Q, [S, Q]),
"BakaShrot_FreeAttachmentData": (I, []),
}
for name, (restype, argtypes) in signatures.items():
try:
function = getattr(self.lib, name)
except AttributeError as error:
raise BakaShrotError(f"{path} has no {name}, is it an older build?", ErrorCode.INTERNAL) from error
function.restype = restype
function.argtypes = argtypes
setattr(self, name[len("BakaShrot_"):], function)
def string(self, getter) -> str:
"""Calls a string getter: asks for the size, then copies (UTF-8)."""
size = getter(None, 0)
if size <= 1:
return ""
buffer = ctypes.create_string_buffer(size)
getter(buffer, size)
return buffer.raw[: size - 1].decode("utf-8")
def _split_server(server: str) -> tuple:
""""host:port" (an IPv6 address in brackets) as (host, port)."""
host, _, port = server.rpartition(":")
if not host or not port.isdigit():
raise BakaShrotError(f"server is host:port, not {server!r}", ErrorCode.INVALID_ARGUMENT)
return host.strip("[]"), int(port)
class Client:
"""A connection to a BakaShrot server, through the DLL.
server: "host:port". ca, certificate, key, crl (optional): PEM text, or
the paths of files holding it: the CA's certificate (the server's must
be issued by it), this client's certificate (its node, its roles) and
its private key, the CA's CRL (servers it revokes are refused).
"""
_connected_client: Optional["Client"] = None
def __init__(self, server: str, ca: str, certificate: str, key: str, crl: Optional[str] = None,
dll_path: Optional[str] = None):
self._dll = _Dll.get(dll_path)
self._lock = threading.RLock()
self.host, self.port = _split_server(server)
self.ca = os.fspath(ca)
self.certificate = os.fspath(certificate)
self.key = os.fspath(key)
self.crl = os.fspath(crl) if crl else None
self.node = ""
@classmethod
def from_file(cls, path: Union[str, os.PathLike], dll_path: Optional[str] = None) -> "Client":
"""From a client.toml (server, ca, certificate, key, crl), the tools'
too; paths in it are relative to its folder. Needs Python 3.11+
(tomllib)."""
import tomllib
try:
with open(path, "rb") as file:
settings = tomllib.load(file)
except OSError as error:
raise BakaShrotError(f"Failed to open '{path}': {error}", ErrorCode.FILE_ERROR) from error
except tomllib.TOMLDecodeError as error:
raise BakaShrotError(f"'{path}': {error}", ErrorCode.INVALID_ARGUMENT) from error
folder = os.path.dirname(os.path.abspath(path))
def get(key, required=True):
value = settings.get(key)
if value is None and required:
raise BakaShrotError(f"'{path}' has no {key}", ErrorCode.INVALID_ARGUMENT)
if not isinstance(value, (str, type(None))):
raise BakaShrotError(f"'{path}': {key} is a string", ErrorCode.INVALID_ARGUMENT)
return value
def file(key, required=True):
value = get(key, required)
return os.path.join(folder, value) if value else None
return cls(get("server"), file("ca"), file("certificate"), file("key"), file("crl", False), dll_path)
# --- Connection --------------------------------------------------------
def connect(self) -> "Client":
"""Connects. Raises ConnectionLostError when the server can't be
reached (CONNECT_FAILED), AuthError when a certificate is refused,
BakaShrotError on a bad setting (INVALID_ARGUMENT, FILE_ERROR) or
another Client holding the DLL's connection (ALREADY_CONNECTED)."""
with self._lock:
owner = Client._connected_client
if owner is not None and owner is not self and owner.connected:
raise BakaShrotError("The DLL holds one connection, another Client is connected", ErrorCode.ALREADY_CONNECTED)
if self.connected:
return self
dll = self._dll
for setter, value in ((dll.SetCaCertificateA, self.ca), (dll.SetCertificateA, self.certificate),
(dll.SetPrivateKeyA, self.key), (dll.SetCrlA, self.crl or "")):
if not setter(value.encode("utf-8")):
raise self._failed("Certificates")
if not dll.ConnectA(self.host.encode("utf-8"), self.port):
raise self._failed(f"Connect to {self.host}:{self.port}", connecting=True)
self.node = dll.string(dll.GetNodeA)
Client._connected_client = self
return self
def close(self) -> None:
with self._lock:
if Client._connected_client is self:
self._dll.Disconnect()
Client._connected_client = None
@property
def connected(self) -> bool:
return Client._connected_client is self and bool(self._dll.IsConnected())
def __enter__(self) -> "Client":
return self.connect()
def __exit__(self, *_) -> None:
self.close()
def _check_connected(self) -> None:
if not self.connected:
raise ConnectionLostError("Not connected", ErrorCode.NOT_CONNECTED)
def _failed(self, what: str, connecting: bool = False) -> BakaShrotError:
"""The error for a failed call, by the DLL's BakaShrot_GetLastError()."""
code = _error_code(self._dll.GetLastError())
reason = self._dll.string(self._dll.GetRefusalReasonA)
if connecting and code in (ErrorCode.AUTH_REJECTED, ErrorCode.SERVER_NOT_VERIFIED,
ErrorCode.NOT_ALLOWED, ErrorCode.VERSION_MISMATCH):
return AuthError(f"{what}: {reason}", code)
if isinstance(code, int) and 1 <= int(code) <= 99:
return RefusedError(reason, code)
if not self._dll.IsConnected() and Client._connected_client is self:
Client._connected_client = None
name = code.name if isinstance(code, ErrorCode) else str(code)
message = f"{what} ({name}): {reason or 'failed'}"
if code in (ErrorCode.NOT_CONNECTED, ErrorCode.CONNECT_FAILED, ErrorCode.CONNECTION_LOST, ErrorCode.PROTOCOL_ERROR):
return ConnectionLostError(message, code)
return BakaShrotError(message, code if code else ErrorCode.INTERNAL)
# --- Requests ----------------------------------------------------------
def push(self, data: Any, topic: str,
attachment: Union[None, bytes, bytearray, memoryview, str, os.PathLike] = None) -> int:
"""Pushes a message into topic, under the client's node. data is
stored as is if it's a str (JSON or not), anything else is turned
into JSON first. Returns its message id.
attachment: bytes, or the path of a file, uploaded with it (1 byte
and up, as much as the server's max_attachment_size takes): the
message is only stored once all of it came."""
if not isinstance(data, str):
data = json.dumps(data, separators=(",", ":"), ensure_ascii=False)
encoded = data.encode("utf-8")
if len(encoded) > MAX_MESSAGE_SIZE:
raise BakaShrotError(f"The message is too big: {len(encoded)} bytes, at most {MAX_MESSAGE_SIZE}", ErrorCode.INVALID_ARGUMENT)
with self._lock:
self._check_connected()
if attachment is None:
message_id = self._dll.PushMessageToA(_name(topic), encoded)
elif isinstance(attachment, (bytes, bytearray, memoryview)):
raw = bytes(attachment)
message_id = self._dll.PushMessageWithDataA(_name(topic), encoded, raw, len(raw))
else:
path = os.fspath(attachment).encode("utf-8")
message_id = self._dll.PushMessageWithFileA(_name(topic), encoded, path)
if message_id < 1:
raise self._failed("Push")
return message_id
def get_attachment(self, topic: str, node: str, message_id: int) -> bytes:
"""The attachment of a message, all of it in memory (save_attachment()
for big ones), checked with its SHA-256. RefusedError if it has none
(NOT_FOUND) or it isn't on this server yet (NOT_READY)."""
with self._lock:
self._check_connected()
size = self._dll.LoadAttachmentA(_name(topic), _name(node), int(message_id))
if size < 0:
raise self._failed("Attachment")
try:
buffer = ctypes.create_string_buffer(size)
self._dll.GetAttachmentData(buffer, size)
return buffer.raw[:size]
finally:
self._dll.FreeAttachmentData()
def save_attachment(self, topic: str, node: str, message_id: int, path: Union[str, os.PathLike]) -> int:
"""Saves the attachment of a message as path (replaced), a part at a
time, checked with its SHA-256. Returns its size. A failed one
leaves no file."""
with self._lock:
self._check_connected()
size = self._dll.SaveAttachmentA(_name(topic), _name(node), int(message_id),
os.fspath(path).encode("utf-8"))
if size < 0:
raise self._failed("Attachment")
return size
def _current(self) -> Message:
dll = self._dll
return Message(dll.GetMessageId(), dll.string(dll.GetMessageTopicA), dll.string(dll.GetMessageNodeA),
dll.string(dll.GetMessageDataA), dll.GetMessagePushedAt(), dll.GetMessageAttachmentSize(),
bool(dll.IsMessageAttachmentReady()))
def latest(self, topic: str, node: str) -> Optional[Message]:
"""The latest message of topic/node, None if there's none yet."""
with self._lock:
self._check_connected()
if not self._dll.GetLatestMessageOfA(_name(topic), _name(node)):
error = self._failed("Latest message")
if isinstance(error, RefusedError) and error.code == ErrorCode.NOT_FOUND:
return None
raise error
return self._current()
def get_messages(self, topic: str, node: str, after: int = 0, limit: int = 1000) -> MessagesPage:
"""The messages of topic/node after message id `after` (0: from the
first), in id order: at most limit (1-10000), fewer if they didn't
fit in about 1 MB (a bigger one comes alone). None if there are no
more, that's not an error."""
if not 1 <= limit <= MAX_GET_MESSAGES:
raise ValueError(f"limit is 1-{MAX_GET_MESSAGES}, not {limit}")
if after < 0:
raise ValueError(f"after is 0 or more, not {after}")
with self._lock:
self._check_connected()
dll = self._dll
count = dll.GetMessagesA(_name(topic), _name(node), after, limit)
if count < 0:
raise self._failed("Get messages")
messages = []
for index in range(count):
dll.SelectMessage(index)
messages.append(self._current())
return MessagesPage(messages, bool(dll.HasMoreMessages()))
def iter_messages(self, topic: str, node: str, after: int = 0, batch: int = 1000) -> Iterator[Message]:
"""Every message of topic/node after `after`, asking for batch at a
time, until there are no more."""
while True:
page = self.get_messages(topic, node, after, batch)
yield from page.messages
if page.messages:
after = page.last_id
if not page.more:
return
def follow(self, topic: str, node: str, after: Union[int, str] = "latest",
interval: float = 0.5, batch: int = 1000) -> Iterator[Message]:
"""Every message of topic/node after `after`, then new ones as they
come, checking every `interval` seconds once caught up. Forever:
stop iterating to stop. after="latest" starts with the next new one.
Raises ConnectionLostError if the connection fails: nothing
reconnects by itself, connect() again and follow from the last id."""
if after == "latest":
latest = self.latest(topic, node)
after = latest.id if latest else 0
elif not isinstance(after, int):
raise ValueError(f"after is a message id or 'latest', not {after!r}")
while True:
page = self.get_messages(topic, node, after, batch)
yield from page.messages
if page.messages:
after = page.last_id
if not page.more:
time.sleep(interval)
def list_topics(self) -> NamesList:
"""The topics the client may push to or read (every one if it may query)."""
return self._list(self._dll.ListTopics, "List topics")
def list_nodes(self) -> NamesList:
"""Every node with messages."""
return self._list(self._dll.ListNodes, "List nodes")
def _list(self, function, what: str) -> NamesList:
with self._lock:
self._check_connected()
if function() < 0:
raise self._failed(what)
parsed = json.loads(self._dll.string(self._dll.GetNamesListA))
return NamesList(parsed["kind"], parsed["names"], bool(parsed["truncated"]))
def query_raw(self, sql: str) -> str:
"""Runs one read-only SELECT on the server (a role with query =
true), returns its result as the server's JSON text:
{"columns": [...], "rows": [[...], ...]}, every value a str or null.
JSON functions on message_data need "is_json = 1" in the WHERE (or
CASE WHEN is_json THEN ... END) when some rows aren't JSON, or the
query is refused: RefusedError "malformed JSON"."""
with self._lock:
self._check_connected()
if not self._dll.QueryA(sql.encode("utf-8")):
raise self._failed("Query")
return self._dll.string(self._dll.GetQueryResultA)
def query(self, sql: str) -> list:
"""query_raw(), as a list of dicts, one per row, by column name."""
result = json.loads(self.query_raw(sql))
columns = result["columns"]
return [dict(zip(columns, row)) for row in result["rows"]]
+247
View File
@@ -0,0 +1,247 @@
"""Checks bakashrot.py and the DLL against a running server, run by
crates/bakashrot-capi/tests/python.rs (which starts the server and writes
the certificates and client.toml files).
Usage: python check_bakashrot.py <DllPath> <Folder>
Folder/kitchen.toml node kitchen: may push to logs and secret, read everything, query.
Folder/lounge.toml node lounge: may read logs only.
Folder/guest.toml node guest: none of its roles is the server's.
Expects an empty database. Prints PASS/FAIL per check, exits 1 if any failed.
"""
import hashlib
import os
import sys
import threading
import time
import bakashrot
from bakashrot import AuthError, BakaShrotError, Client, ConnectionLostError, ErrorCode, RefusedError
dll_path, folder = sys.argv[1:3]
fails = 0
def check(what, ok, detail=""):
global fails
if not ok:
fails += 1
detail = str(detail)
if len(detail) > 300:
detail = detail[:300] + f"... ({len(detail)} chars)"
print(f"{'PASS' if ok else 'FAIL'} {what}\n -> {detail}", flush=True)
def raises(function, error_type, contains="", code=None):
try:
function()
except error_type as error:
got = getattr(error, "code", None)
return contains in str(error) and (code is None or got == code), f"{type(error).__name__} [{got!r}]: {error}"
except Exception as error: # noqa: BLE001 - reported as a failure
return False, f"{type(error).__name__}: {error}"
return False, "no exception"
kitchen = Client.from_file(os.path.join(folder, "kitchen.toml"), dll_path)
lounge = Client.from_file(os.path.join(folder, "lounge.toml"), dll_path)
with kitchen:
check("Connects from kitchen.toml, the node from its certificate", kitchen.connected and kitchen.node == "kitchen",
f"{kitchen.node!r}, {kitchen._dll.path}")
# --- Nothing yet ---------------------------------------------------------
check("latest() with no messages: None", kitchen.latest("logs", "kitchen") is None)
page = kitchen.get_messages("logs", "kitchen")
check("get_messages() with no messages: empty, no more", len(page) == 0 and not page.more and page.last_id is None, page)
# --- Pushes --------------------------------------------------------------
started = time.perf_counter()
ids = [kitchen.push({"i": i}, "logs") for i in range(1, 251)]
elapsed = time.perf_counter() - started
check("250 pushes on one connection, ids 1-250", ids == list(range(1, 251)),
f"{elapsed * 1000:.0f} ms, {250 / elapsed:.0f} msg/s")
latest = kitchen.latest("logs", "kitchen")
check("latest(): #250", latest is not None and latest.id == 250 and latest.json() == {"i": 250}, latest)
now_ms = int(time.time() * 1000)
check("latest().pushed_at: just now, UTC ms", latest is not None and now_ms - 60000 < latest.pushed_at <= now_ms + 1000,
f"{latest.pushed_at if latest else None} vs {now_ms}")
check("latest().pushed: the same, an aware datetime in UTC",
latest is not None and latest.pushed.tzinfo is not None and latest.pushed.utcoffset().total_seconds() == 0
and int(latest.pushed.timestamp() * 1000) == latest.pushed_at, latest.pushed if latest else None)
# --- Pages ---------------------------------------------------------------
page = kitchen.get_messages("logs", "kitchen", after=0, limit=100)
check("First page: 1-100, more", [m.id for m in page] == list(range(1, 101)) and page.more and page.last_id == 100,
f"{len(page)} messages, more={page.more}")
first = page.messages[0]
check("A message's fields", (first.topic, first.node, first.data, first.json(), first.attachment_size)
== ("logs", "kitchen", '{"i":1}', {"i": 1}, 0), first)
stamps = [m.pushed_at for m in page]
check("Each message of a page has its pushed_at, in push order", all(stamps) and stamps == sorted(stamps),
f"{stamps[0]} .. {stamps[-1]}")
page = kitchen.get_messages("logs", "kitchen", after=200, limit=100)
check("Last page: 201-250, no more", [m.id for m in page] == list(range(201, 251)) and not page.more,
f"{len(page)} messages, more={page.more}")
page = kitchen.get_messages("logs", "kitchen", after=150, limit=100)
check("Exactly up to the last one: 151-250, no more", [m.id for m in page] == list(range(151, 251)) and not page.more,
f"{len(page)} messages, more={page.more}")
page = kitchen.get_messages("LOGS", "Kitchen", after=250)
check("After the last one, names in another case: empty, no more", len(page) == 0 and not page.more, page)
every = list(kitchen.iter_messages("logs", "kitchen", batch=37))
check("iter_messages(batch=37): all 250 in order", [m.id for m in every] == list(range(1, 251)), f"{len(every)} messages")
# --- Data ----------------------------------------------------------------
text_id = kitchen.push("plain text, not JSON", "logs")
unicode_id = kitchen.push("héllo wörld, 🌍, 日本語", "logs")
empty_id = kitchen.push("", "logs")
page = kitchen.get_messages("logs", "kitchen", after=250)
data = [m.data for m in page]
check("Non-JSON, non-ASCII and empty data read back as pushed",
data == ["plain text, not JSON", "héllo wörld, 🌍, 日本語", ""] and [m.id for m in page] == [text_id, unicode_id, empty_id],
data)
ok, detail = raises(lambda: page.messages[0].json(), ValueError)
check("json() on non-JSON data raises ValueError", ok, detail)
rows = kitchen.query("SELECT is_json, COUNT(*) AS n FROM data GROUP BY is_json ORDER BY is_json")
check("query(): is_json flags 3 non-JSON, 250 JSON", rows == [{"is_json": "0", "n": "3"}, {"is_json": "1", "n": "250"}], rows)
ok, detail = raises(lambda: kitchen.query("SELECT nope FROM data"), RefusedError, "nope", ErrorCode.QUERY_FAILED)
check("A query that fails: RefusedError, QUERY_FAILED", ok, detail)
# --- Answers split at ~1 MB ----------------------------------------------
big = "x" * (700 * 1024)
big_ids = [kitchen.push(big, "logs") for _ in range(3)]
page = kitchen.get_messages("logs", "kitchen", after=empty_id, limit=10)
check("3 x 700 KB: one per answer, more", [m.id for m in page] == big_ids[:1] and page.more and page.messages[0].data == big,
f"{len(page)} messages, more={page.more}")
every = list(kitchen.iter_messages("logs", "kitchen", after=empty_id))
check("iter_messages() over them: all 3, whole", [m.id for m in every] == big_ids and all(m.data == big for m in every),
[len(m.data) for m in every])
# --- Refusals ------------------------------------------------------------
ok, detail = raises(lambda: kitchen.get_messages("logs", "nobody"), RefusedError, "unknown node 'nobody'", ErrorCode.UNKNOWN_NAME)
check("Unknown node: RefusedError, UNKNOWN_NAME", ok, detail)
check("Still connected after a refusal", kitchen.connected and kitchen.latest("logs", "kitchen").id == big_ids[-1])
ok, detail = raises(lambda: kitchen.get_messages("logs", "kitchen", limit=0), ValueError)
check("limit 0: ValueError, before asking", ok, detail)
ok, detail = raises(lambda: kitchen.get_messages("logs", "kitchen", after=-1), ValueError)
check("after -1: ValueError", ok, detail)
ok, detail = raises(lambda: kitchen.push("x", "nothing"), RefusedError, "unknown topic", ErrorCode.UNKNOWN_NAME)
check("Push to an unknown topic: RefusedError, UNKNOWN_NAME", ok, detail)
ok, detail = raises(lambda: kitchen.push("x", "a b"), BakaShrotError, "isn't a topic name", ErrorCode.INVALID_ARGUMENT)
check("A topic that isn't a name: refused before sending", ok, detail)
ok, detail = raises(lambda: kitchen.push("x" * (bakashrot.MAX_MESSAGE_SIZE + 1), "logs"), BakaShrotError, "too big",
ErrorCode.INVALID_ARGUMENT)
check("A message over the limit: refused before sending", ok, detail)
secret_id = kitchen.push({"s": 1}, "secret")
check("Push to another allowed topic", secret_id == 1, secret_id)
ok, detail = raises(lambda: lounge.connect(), BakaShrotError, "one connection", ErrorCode.ALREADY_CONNECTED)
check("A second Client can't connect while one is", ok and not lounge.connected, detail)
topics = kitchen.list_topics()
check("list_topics()", topics.kind == "topic" and topics.names == ["logs", "secret"] and not topics.truncated, topics)
nodes = kitchen.list_nodes()
check("list_nodes()", nodes.kind == "node" and nodes.names == ["kitchen"], nodes)
# --- follow() ------------------------------------------------------------
followed = []
errors = []
def follower():
try:
for message in kitchen.follow("logs", "kitchen", after="latest", interval=0.05):
followed.append(message)
if len(followed) == 5:
return
except Exception as error: # noqa: BLE001 - reported below
errors.append(error)
thread = threading.Thread(target=follower, daemon=True)
thread.start()
time.sleep(0.5)
new_ids = [kitchen.push({"f": i}, "logs") for i in range(5)]
thread.join(10)
check("follow(after='latest') from another thread: only the 5 new ones",
not thread.is_alive() and not errors and [m.id for m in followed] == new_ids,
f"{[m.id for m in followed]} vs {new_ids}, errors {errors}")
# --- Attachments (in secret, the other checks count logs) ----------------
blob = os.urandom(3 * 1024 * 1024 + 7)
started = time.perf_counter()
blob_id = kitchen.push({"kind": "blob"}, "secret", attachment=blob)
up = time.perf_counter() - started
message = kitchen.latest("secret", "kitchen")
check("push(attachment=bytes): the message has it, ready",
message is not None and message.id == blob_id and message.attachment_size == len(blob) and message.attachment_ready,
message)
started = time.perf_counter()
data = kitchen.get_attachment("secret", "kitchen", blob_id)
down = time.perf_counter() - started
check("get_attachment(): the same bytes", data == blob, f"{len(data)} bytes, {up * 1000:.0f} ms up, {down * 1000:.0f} ms down")
source = os.path.join(folder, "source.bin")
with open(source, "wb") as file:
file.write(os.urandom(1500 * 1024))
file_id = kitchen.push("from a file", "secret", attachment=source)
copy = os.path.join(folder, "copy.bin")
size = kitchen.save_attachment("secret", "kitchen", file_id, copy)
with open(source, "rb") as a, open(copy, "rb") as b:
same = hashlib.sha256(a.read()).digest() == hashlib.sha256(b.read()).digest()
check("push(attachment=path), save_attachment(): the same file", size == os.path.getsize(source) and same, size)
plain_id = kitchen.push("no attachment", "secret")
page = kitchen.get_messages("secret", "kitchen", after=blob_id - 1)
sizes = [(m.id, m.attachment_size, m.attachment_ready) for m in page]
check("get_messages(): each message's attachment",
sizes == [(blob_id, len(blob), True), (file_id, os.path.getsize(source), True), (plain_id, 0, False)], sizes)
ok, detail = raises(lambda: kitchen.get_attachment("secret", "kitchen", plain_id), RefusedError, "no attachment", ErrorCode.NOT_FOUND)
check("get_attachment() of a message without: RefusedError, NOT_FOUND", ok, detail)
none = os.path.join(folder, "none.bin")
ok, detail = raises(lambda: kitchen.save_attachment("secret", "kitchen", plain_id, none), RefusedError, code=ErrorCode.NOT_FOUND)
check("save_attachment() refused: no file left", ok and not os.path.exists(none), detail)
ok, detail = raises(lambda: kitchen.push("x", "secret", attachment=b""), BakaShrotError, "0 bytes", ErrorCode.INVALID_ARGUMENT)
check("An empty attachment: refused before sending", ok, detail)
ok, detail = raises(lambda: kitchen.push("x", "secret", attachment=os.path.join(folder, "missing.bin")), BakaShrotError,
"missing.bin", ErrorCode.FILE_ERROR)
check("A missing file: refused before sending", ok, detail)
check("Still connected", kitchen.connected)
check("close(): disconnected", not kitchen.connected)
ok, detail = raises(lambda: kitchen.push("x", "logs"), ConnectionLostError, code=ErrorCode.NOT_CONNECTED)
check("A request once closed: ConnectionLostError, NOT_CONNECTED", ok, detail)
# --- Connecting: unreachable, refused, PEM text ----------------------------------
with open(kitchen.ca) as ca, open(kitchen.certificate) as certificate, open(kitchen.key) as key:
pem = (ca.read(), certificate.read(), key.read())
nowhere = Client("127.0.0.1:1", *pem, dll_path=dll_path)
ok, detail = raises(nowhere.connect, ConnectionLostError, code=ErrorCode.CONNECT_FAILED)
check("Nothing listening: ConnectionLostError, CONNECT_FAILED", ok, detail)
guest = Client.from_file(os.path.join(folder, "guest.toml"), dll_path)
ok, detail = raises(guest.connect, AuthError, "guest", ErrorCode.NOT_ALLOWED)
check("None of its roles allowed: AuthError, NOT_ALLOWED", ok, detail)
missing = Client(f"{kitchen.host}:{kitchen.port}", os.path.join(folder, "missing.crt"), *pem[1:], dll_path=dll_path)
ok, detail = raises(missing.connect, BakaShrotError, "missing.crt", ErrorCode.FILE_ERROR)
check("A certificate file that isn't there: FILE_ERROR", ok, detail)
with Client(f"{kitchen.host}:{kitchen.port}", *pem, dll_path=dll_path) as again:
check("The same identity from PEM text: connected", again.connected and again.node == "kitchen", again.node)
with lounge:
page = lounge.get_messages("logs", "kitchen", after=245, limit=3)
check("Another identity once the first closed: reads logs", [m.id for m in page] == [246, 247, 248] and page.more,
f"{[m.id for m in page]}, more={page.more}")
ok, detail = raises(lambda: lounge.get_messages("secret", "kitchen"), RefusedError, "may not read 'secret'", ErrorCode.NOT_ALLOWED)
check("A topic not in its read_topics: RefusedError, NOT_ALLOWED", ok, detail)
ok, detail = raises(lambda: lounge.query("SELECT 1"), RefusedError, "may not run queries", ErrorCode.NOT_ALLOWED)
check("Not allowed to query: RefusedError, NOT_ALLOWED", ok, detail)
check("list_topics(): only what it may read", lounge.list_topics().names == ["logs"])
ok, detail = raises(lambda: lounge.get_attachment("secret", "kitchen", blob_id), RefusedError, code=ErrorCode.NOT_ALLOWED)
check("An attachment in a topic it may not read: RefusedError, NOT_ALLOWED", ok, detail)
print()
print("All checks passed" if fails == 0 else f"{fails} check(s) failed")
sys.exit(1 if fails else 0)
+29
View File
@@ -0,0 +1,29 @@
# Runs what CI runs (../.github/workflows/source.yml), in this order:
# formatting, clippy (warnings are errors), the tests, the docs.
# Exit code 0 when everything passed.
# Usage: powershell -ExecutionPolicy Bypass -File Source\check.ps1
$ErrorActionPreference = "Stop"
# rustup's folder isn't always on the PATH (it isn't in every shell here).
if (-not (Get-Command cargo -ErrorAction SilentlyContinue)) {
$env:PATH = (Join-Path $env:USERPROFILE ".cargo\bin") + [IO.Path]::PathSeparator + $env:PATH
}
function Step([string]$What, [scriptblock]$Run) {
"== $What"
& $Run
if ($LASTEXITCODE -ne 0) { "FAILED: $What"; exit 1 }
}
Push-Location $PSScriptRoot
try {
Step "cargo fmt" { cargo fmt --all -- --check }
Step "cargo clippy" { cargo clippy --workspace --all-targets --all-features -- -D warnings }
Step "cargo test" { cargo test --workspace --all-features }
$env:RUSTDOCFLAGS = "-D warnings"
Step "cargo doc" { cargo doc --workspace --no-deps --all-features }
} finally {
Pop-Location
}
"All checks passed"
exit 0
+30
View File
@@ -0,0 +1,30 @@
[package]
name = "bakashrot-capi"
description = "BakaShrot's C DLL: the BakaShrot_* exports over bakashrot-client, one connection per process."
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
authors.workspace = true
repository.workspace = true
publish.workspace = true
# bakashrot.dll / libbakashrot.so; the rlib for the tests.
[lib]
name = "bakashrot"
crate-type = ["cdylib", "rlib"]
[dependencies]
bakashrot-client = { path = "../bakashrot-client" }
bakashrot-proto = { path = "../bakashrot-proto" }
serde_json = "1.0.154"
[dev-dependencies]
bakashrot-config = { path = "../bakashrot-config" }
bakashrot-pki = { path = "../bakashrot-pki" }
bakashrot-server = { path = "../bakashrot-server" }
cbindgen = { version = "0.29.4", default-features = false }
tokio = { version = "1.54.1", features = ["rt-multi-thread", "net"] }
[lints]
workspace = true
@@ -0,0 +1,13 @@
# bindings/c/bakashrot.h, generated from src/lib.rs by tests/header.rs
# (which rewrites it when the exports change: check it in then).
language = "C"
header = """/*
* BakaShrot's client DLL: bakashrot.dll (Windows), libbakashrot.so (Linux).
* Generated by cbindgen from Source/crates/bakashrot-capi: don't edit.
* Source/docs/client.md has the conventions and the whole API.
*/"""
include_guard = "BAKASHROT_H"
cpp_compat = true
documentation = true
line_endings = "LF"
usize_is_size_t = true
+928
View File
@@ -0,0 +1,928 @@
//! BakaShrot's C DLL (`bakashrot.dll`, `libbakashrot.so`): the old
//! `BakaShrot_*` exports over [`bakashrot_client`], for C, PureBasic,
//! Python (ctypes) and anything that loads a DLL. `Source/docs/client.md`
//! has the whole API; `bindings/c/bakashrot.h` is generated from this file.
//!
//! The conventions, the old DLL's:
//!
//! - **One connection per process:** set the certificates, connect, send
//! requests, one at a time (calls from several threads wait for each
//! other).
//! - **`A` and `W` exports:** strings in and out as UTF-8 (`char*`) or
//! UTF-16 (`uint16_t*`, `wchar_t*` on Windows), null-terminated.
//! - **Strings out** are copied into the caller's buffer of `BufferSize`
//! bytes: the getter returns the bytes needed, terminator included, and
//! copies nothing if they don't fit (a null buffer asks for the size).
//! - **Failures:** 0 (or -1 where a count or an id is returned), then
//! `BakaShrot_GetLastError()` gives the code (1-99 a server's refusal, the
//! connection still open; 100 and up the client's own) and
//! `BakaShrot_GetRefusalReason()` why, in words. After `ConnectionLost`
//! or `ProtocolError` the connection is closed: connect again.
//! - **Safety:** pointers are null or valid for what's said, strings
//! terminated, buffers writable for their size. A panic inside is caught
//! and reported as `Internal`; nothing allocated here is freed by the
//! caller, or the other way.
#![allow(unsafe_code, non_snake_case, clippy::missing_safety_doc)]
mod text;
use bakashrot_client::{Client, Error, Settings};
use bakashrot_proto::ErrorCode;
use bakashrot_proto::packets::{MessageEntry, NameKind};
use std::ffi::{c_char, c_void};
use std::fs::File;
use std::io::Cursor;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::path::Path;
use std::sync::{Mutex, MutexGuard, PoisonError};
use text::{Text, Utf8, Utf16};
type Result<T> = std::result::Result<T, Error>;
/// Everything the DLL holds: its one connection, its settings, the last
/// answers.
static STATE: Mutex<State> = Mutex::new(State::new());
struct State {
ca: Option<String>,
certificate: Option<String>,
key: Option<String>,
crl: Option<String>,
client: Option<Client>,
/// The last call's error code, 0 if it succeeded.
last_error: u32,
/// Why it failed.
reason: String,
/// The last `GetMessages` or `GetLatestMessageOf`.
topic: String,
node: String,
messages: Vec<MessageEntry>,
selected: usize,
more: bool,
/// The last `ListTopics` / `ListNodes`, as JSON.
names: String,
/// The last `Query`'s result.
query: String,
/// The last `LoadAttachment`'s attachment.
attachment: Vec<u8>,
}
impl State {
const fn new() -> State {
State {
ca: None,
certificate: None,
key: None,
crl: None,
client: None,
last_error: 0,
reason: String::new(),
topic: String::new(),
node: String::new(),
messages: Vec::new(),
selected: 0,
more: false,
names: String::new(),
query: String::new(),
attachment: Vec::new(),
}
}
fn fail(&mut self, error: Error) {
self.last_error = error.code();
self.reason = error.message().to_owned();
let closed = [ErrorCode::ConnectionLost, ErrorCode::ProtocolError]
.iter()
.any(|code| code.code() == error.code());
if closed {
self.client = None;
}
}
fn client(&mut self) -> Result<&mut Client> {
self.client.as_mut().ok_or_else(|| {
Error::new(
ErrorCode::NotConnected,
"not connected: BakaShrot_Connect() first",
)
})
}
/// The selected message of the last answer.
fn message(&self) -> Option<&MessageEntry> {
self.messages.get(self.selected)
}
/// Forgets the last answer's messages.
fn clear_messages(&mut self, topic: &str, node: &str) {
self.topic = topic.to_owned();
self.node = node.to_owned();
self.messages.clear();
self.selected = 0;
self.more = false;
}
}
fn state() -> MutexGuard<'static, State> {
STATE.lock().unwrap_or_else(PoisonError::into_inner)
}
/// Runs a call that can fail: the last error reset, then set if it fails
/// (or panics), `failed` returned then.
fn call<T>(failed: T, run: impl FnOnce(&mut State) -> Result<T>) -> T {
let outcome = catch_unwind(AssertUnwindSafe(|| {
let mut state = state();
state.last_error = 0;
state.reason.clear();
let outcome = run(&mut state);
outcome.map_err(|error| state.fail(error))
}));
match outcome {
Ok(Ok(value)) => value,
Ok(Err(())) => failed,
Err(_) => {
state().fail(Error::new(ErrorCode::Internal, "the DLL panicked"));
failed
}
}
}
/// Runs a getter: the last error stays as it is.
fn get<T>(default: T, read: impl FnOnce(&State) -> T) -> T {
catch_unwind(AssertUnwindSafe(|| read(&state()))).unwrap_or(default)
}
/// Copies a string of the state into the caller's buffer.
unsafe fn get_text<T: Text>(buffer: *mut T::Unit, size: isize, text: fn(&State) -> &str) -> isize {
get(0, |state| unsafe {
text::copy::<T>(text(state), buffer, size)
})
}
fn invalid(why: impl Into<String>) -> Error {
Error::new(ErrorCode::InvalidArgument, why)
}
fn required(value: Option<String>, what: &str) -> Result<String> {
value.ok_or_else(|| invalid(format!("no {what} (a null pointer)")))
}
fn bool_result(ok: bool) -> isize {
isize::from(ok)
}
// --- Errors ------------------------------------------------------------------
/// Why the last call failed: a protocol error code (1-99 a server's
/// refusal, the connection still open; 100 and up the client's own), 0 if
/// it succeeded. Getters don't change it.
#[unsafe(no_mangle)]
pub extern "C" fn BakaShrot_GetLastError() -> i32 {
get(ErrorCode::Internal.code() as i32, |state| {
state.last_error as i32
})
}
/// Why the last call failed, in words: the server's reason for a refusal,
/// the client's otherwise. Empty if it succeeded.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_GetRefusalReasonA(buffer: *mut c_char, size: isize) -> isize {
unsafe { get_text::<Utf8>(buffer.cast(), size, |state| &state.reason) }
}
/// The same as `BakaShrot_GetRefusalReasonA`, in UTF-16.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_GetRefusalReasonW(buffer: *mut u16, size: isize) -> isize {
unsafe { get_text::<Utf16>(buffer, size, |state| &state.reason) }
}
// --- Settings ----------------------------------------------------------------
/// A setting's PEM: the text itself if it starts with `-----BEGIN`, a
/// file's path otherwise. `None` (null or empty) only if `optional`.
fn pem_or_file(value: Option<String>, what: &str, optional: bool) -> Result<Option<String>> {
let Some(value) = value.filter(|value| !value.trim().is_empty()) else {
return match optional {
true => Ok(None),
false => Err(invalid(format!("no {what}"))),
};
};
if value.trim_start().starts_with("-----BEGIN") {
return Ok(Some(value));
}
std::fs::read_to_string(&value)
.map(Some)
.map_err(|error| Error::new(ErrorCode::FileError, format!("{what} '{value}': {error}")))
}
/// Sets one of the certificates' settings, before connecting.
unsafe fn set<T: Text>(
value: *const T::Unit,
what: &str,
optional: bool,
slot: fn(&mut State) -> &mut Option<String>,
) -> isize {
call(0, |state| {
if state.client.is_some() {
return Err(Error::new(
ErrorCode::AlreadyConnected,
"already connected: disconnect first",
));
}
let value = unsafe { text::read::<T>(value, what)? };
*slot(state) = pem_or_file(value, what, optional)?;
Ok(1)
})
}
/// Sets the CA's certificate, which the server's must be issued by: PEM
/// text, or the path of a file holding it. Before connecting.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_SetCaCertificateA(certificate: *const c_char) -> isize {
unsafe {
set::<Utf8>(certificate.cast(), "CA certificate", false, |state| {
&mut state.ca
})
}
}
/// The same as `BakaShrot_SetCaCertificateA`, in UTF-16.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_SetCaCertificateW(certificate: *const u16) -> isize {
unsafe { set::<Utf16>(certificate, "CA certificate", false, |state| &mut state.ca) }
}
/// Sets this client's certificate, which says its node and its roles: PEM
/// text, or the path of a file holding it. Before connecting.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_SetCertificateA(certificate: *const c_char) -> isize {
unsafe {
set::<Utf8>(certificate.cast(), "certificate", false, |state| {
&mut state.certificate
})
}
}
/// The same as `BakaShrot_SetCertificateA`, in UTF-16.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_SetCertificateW(certificate: *const u16) -> isize {
unsafe {
set::<Utf16>(certificate, "certificate", false, |state| {
&mut state.certificate
})
}
}
/// Sets this client's private key, its certificate's: PEM text, or the path
/// of a file holding it. Before connecting.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_SetPrivateKeyA(key: *const c_char) -> isize {
unsafe { set::<Utf8>(key.cast(), "private key", false, |state| &mut state.key) }
}
/// The same as `BakaShrot_SetPrivateKeyA`, in UTF-16.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_SetPrivateKeyW(key: *const u16) -> isize {
unsafe { set::<Utf16>(key, "private key", false, |state| &mut state.key) }
}
/// Sets the CA's CRL, optional: servers it revokes are refused. PEM text,
/// or the path of a file holding it; null or empty for none. Before
/// connecting.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_SetCrlA(crl: *const c_char) -> isize {
unsafe { set::<Utf8>(crl.cast(), "CRL", true, |state| &mut state.crl) }
}
/// The same as `BakaShrot_SetCrlA`, in UTF-16.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_SetCrlW(crl: *const u16) -> isize {
unsafe { set::<Utf16>(crl, "CRL", true, |state| &mut state.crl) }
}
// --- The connection ----------------------------------------------------------
unsafe fn connect<T: Text>(host: *const T::Unit, port: i32) -> isize {
call(0, |state| {
if state.client.is_some() {
return Err(Error::new(
ErrorCode::AlreadyConnected,
"already connected: disconnect first",
));
}
let host = required(unsafe { text::read::<T>(host, "host")? }, "host")?;
let port = u16::try_from(port)
.ok()
.filter(|port| *port != 0)
.ok_or_else(|| invalid(format!("port {port}: 1 to 65535")))?;
let missing = |what: &str, setter: &str| invalid(format!("no {what}: {setter}() first"));
let settings = Settings {
ca: state
.ca
.as_deref()
.ok_or_else(|| missing("CA certificate", "BakaShrot_SetCaCertificate"))?,
certificate: state
.certificate
.as_deref()
.ok_or_else(|| missing("certificate", "BakaShrot_SetCertificate"))?,
key: state
.key
.as_deref()
.ok_or_else(|| missing("private key", "BakaShrot_SetPrivateKey"))?,
crl: state.crl.as_deref(),
};
// An IPv6 address goes in brackets before its port.
let address = match host.contains(':') && !host.starts_with('[') {
true => format!("[{host}]:{port}"),
false => format!("{host}:{port}"),
};
let client = Client::connect(&address, &settings)?;
state.client = Some(client);
Ok(1)
})
}
/// Connects to the server at `host` (a name or an address) and `port`:
/// TLS with the certificates set, then the server says who this client is
/// (`BakaShrot_GetNode()`). Refused: the code says by whom (`AuthRejected`
/// the server refused the certificate, `ServerNotVerified` this client
/// refused the server's, `NotAllowed` none of its roles is the server's).
#[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_ConnectA(host: *const c_char, port: i32) -> isize {
unsafe { connect::<Utf8>(host.cast(), port) }
}
/// The same as `BakaShrot_ConnectA`, in UTF-16.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_ConnectW(host: *const u16, port: i32) -> isize {
unsafe { connect::<Utf16>(host, port) }
}
/// 1 while connected: notices when the server closed the connection
/// (forgotten then: connect again).
#[unsafe(no_mangle)]
pub extern "C" fn BakaShrot_IsConnected() -> isize {
let open = catch_unwind(AssertUnwindSafe(|| {
let mut state = state();
let open = state.client.as_ref().is_some_and(Client::is_open);
if !open {
state.client = None;
}
open
}));
bool_result(open.unwrap_or(false))
}
/// Closes the connection: 0 if there was none. The settings stay.
#[unsafe(no_mangle)]
pub extern "C" fn BakaShrot_Disconnect() -> isize {
let closed = catch_unwind(AssertUnwindSafe(|| state().client.take().is_some()));
bool_result(closed.unwrap_or(false))
}
/// The node this client is, as the server said when connecting: its
/// certificate's name. Empty when not connected.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_GetNodeA(buffer: *mut c_char, size: isize) -> isize {
unsafe {
get_text::<Utf8>(buffer.cast(), size, |state| {
state.client.as_ref().map_or("", Client::node)
})
}
}
/// The same as `BakaShrot_GetNodeA`, in UTF-16.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_GetNodeW(buffer: *mut u16, size: isize) -> isize {
unsafe {
get_text::<Utf16>(buffer, size, |state| {
state.client.as_ref().map_or("", Client::node)
})
}
}
// --- Pushing -----------------------------------------------------------------
/// A push's topic and message, as arguments: a null message is an empty
/// one (PureBasic passes "" as null).
unsafe fn topic_and_data<T: Text>(
topic: *const T::Unit,
data: *const T::Unit,
) -> Result<(String, String)> {
let topic = required(unsafe { text::read::<T>(topic, "topic")? }, "topic")?;
let data = unsafe { text::read::<T>(data, "the message")? }.unwrap_or_default();
Ok((topic, data))
}
unsafe fn push_to<T: Text>(topic: *const T::Unit, data: *const T::Unit) -> i64 {
call(-1, |state| {
let (topic, data) = unsafe { topic_and_data::<T>(topic, data)? };
let id = state.client()?.push(&topic, &data)?;
Ok(id as i64)
})
}
/// Pushes a message (JSON or not) to `topic`, as this client's node: its
/// id (1 and up), -1 on failure. A push whose answer was lost
/// (`ConnectionLost`) may have been stored all the same.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_PushMessageToA(
topic: *const c_char,
data: *const c_char,
) -> i64 {
unsafe { push_to::<Utf8>(topic.cast(), data.cast()) }
}
/// The same as `BakaShrot_PushMessageToA`, in UTF-16.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_PushMessageToW(topic: *const u16, data: *const u16) -> i64 {
unsafe { push_to::<Utf16>(topic, data) }
}
// --- Reading -----------------------------------------------------------------
/// A topic and node, as arguments.
unsafe fn topic_and_node<T: Text>(
topic: *const T::Unit,
node: *const T::Unit,
) -> Result<(String, String)> {
let topic = required(unsafe { text::read::<T>(topic, "topic")? }, "topic")?;
let node = required(unsafe { text::read::<T>(node, "node")? }, "node")?;
Ok((topic, node))
}
unsafe fn latest_of<T: Text>(topic: *const T::Unit, node: *const T::Unit) -> isize {
call(0, |state| {
let (topic, node) = unsafe { topic_and_node::<T>(topic, node)? };
state.clear_messages(&topic, &node);
let answer = state.client()?.get_messages(&topic, &node, None, 1)?;
if answer.messages.is_empty() {
return Err(Error::new(
ErrorCode::NotFound,
format!("no message in {topic}/{node} yet"),
));
}
state.messages = answer.messages;
Ok(1)
})
}
/// Gets the latest message of `topic` and `node`, then read with the
/// `BakaShrot_GetMessage*()` getters. `NotFound` if there's none yet.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_GetLatestMessageOfA(
topic: *const c_char,
node: *const c_char,
) -> isize {
unsafe { latest_of::<Utf8>(topic.cast(), node.cast()) }
}
/// The same as `BakaShrot_GetLatestMessageOfA`, in UTF-16.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_GetLatestMessageOfW(
topic: *const u16,
node: *const u16,
) -> isize {
unsafe { latest_of::<Utf16>(topic, node) }
}
unsafe fn messages<T: Text>(
topic: *const T::Unit,
node: *const T::Unit,
after: i64,
limit: i32,
) -> i32 {
call(-1, |state| {
let (topic, node) = unsafe { topic_and_node::<T>(topic, node)? };
state.clear_messages(&topic, &node);
let after =
u64::try_from(after).map_err(|_| invalid(format!("after {after}: 0 or more")))?;
let limit = u32::try_from(limit).map_err(|_| invalid(format!("a limit of {limit}")))?;
let answer = state
.client()?
.get_messages(&topic, &node, Some(after), limit)?;
state.more = answer.more;
state.messages = answer.messages;
Ok(state.messages.len() as i32)
})
}
/// Gets the messages of `topic` and `node` after id `after` (0 for the
/// first ones), in order: `limit` at most (1-10000), fewer past about
/// 1 MB. Returns how many came (none isn't a failure), -1 on failure. The
/// first is selected; `BakaShrot_SelectMessage()` selects the others,
/// `BakaShrot_HasMoreMessages()` says whether more follow the last one.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_GetMessagesA(
topic: *const c_char,
node: *const c_char,
after: i64,
limit: i32,
) -> i32 {
unsafe { messages::<Utf8>(topic.cast(), node.cast(), after, limit) }
}
/// The same as `BakaShrot_GetMessagesA`, in UTF-16.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_GetMessagesW(
topic: *const u16,
node: *const u16,
after: i64,
limit: i32,
) -> i32 {
unsafe { messages::<Utf16>(topic, node, after, limit) }
}
/// How many messages the last `GetMessages` or `GetLatestMessageOf` got.
#[unsafe(no_mangle)]
pub extern "C" fn BakaShrot_GetMessageCount() -> i32 {
get(0, |state| state.messages.len() as i32)
}
/// Selects the message at `index` (0 to the count - 1) for the getters: 0
/// if there's none there (`InvalidArgument`), the selection unchanged.
#[unsafe(no_mangle)]
pub extern "C" fn BakaShrot_SelectMessage(index: i32) -> isize {
call(0, |state| {
let index = usize::try_from(index)
.ok()
.filter(|index| *index < state.messages.len())
.ok_or_else(|| invalid(format!("no message at {index}")))?;
state.selected = index;
Ok(1)
})
}
/// 1 if more messages follow the last one the last `GetMessages` got: ask
/// again after its id.
#[unsafe(no_mangle)]
pub extern "C" fn BakaShrot_HasMoreMessages() -> isize {
get(0, |state| bool_result(state.more))
}
/// The selected message's id, 0 if none.
#[unsafe(no_mangle)]
pub extern "C" fn BakaShrot_GetMessageId() -> i64 {
get(0, |state| {
state.message().map_or(0, |message| message.id as i64)
})
}
/// When the selected message was pushed, by the server it was pushed to:
/// milliseconds since 1970-01-01 UTC, 0 if none.
#[unsafe(no_mangle)]
pub extern "C" fn BakaShrot_GetMessagePushedAt() -> i64 {
get(0, |state| {
state
.message()
.map_or(0, |message| message.pushed_at as i64)
})
}
/// The selected message's attachment's size, 0 without one.
#[unsafe(no_mangle)]
pub extern "C" fn BakaShrot_GetMessageAttachmentSize() -> i64 {
get(0, |state| {
state
.message()
.and_then(|message| message.attachment.as_ref())
.map_or(0, |attachment| attachment.size as i64)
})
}
/// 1 if the selected message's attachment is all on this server (a
/// replicated one may still be on its way).
#[unsafe(no_mangle)]
pub extern "C" fn BakaShrot_IsMessageAttachmentReady() -> isize {
get(0, |state| {
let attachment = state
.message()
.and_then(|message| message.attachment.as_ref());
bool_result(attachment.is_some_and(|attachment| attachment.ready))
})
}
/// The selected message's data, as pushed (JSON or not).
#[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_GetMessageDataA(buffer: *mut c_char, size: isize) -> isize {
unsafe {
get_text::<Utf8>(buffer.cast(), size, |state| {
state.message().map_or("", |message| &message.data)
})
}
}
/// The same as `BakaShrot_GetMessageDataA`, in UTF-16.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_GetMessageDataW(buffer: *mut u16, size: isize) -> isize {
unsafe {
get_text::<Utf16>(buffer, size, |state| {
state.message().map_or("", |message| &message.data)
})
}
}
/// The topic the last `GetMessages` or `GetLatestMessageOf` asked for.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_GetMessageTopicA(buffer: *mut c_char, size: isize) -> isize {
unsafe { get_text::<Utf8>(buffer.cast(), size, |state| &state.topic) }
}
/// The same as `BakaShrot_GetMessageTopicA`, in UTF-16.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_GetMessageTopicW(buffer: *mut u16, size: isize) -> isize {
unsafe { get_text::<Utf16>(buffer, size, |state| &state.topic) }
}
/// The node the last `GetMessages` or `GetLatestMessageOf` asked for.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_GetMessageNodeA(buffer: *mut c_char, size: isize) -> isize {
unsafe { get_text::<Utf8>(buffer.cast(), size, |state| &state.node) }
}
/// The same as `BakaShrot_GetMessageNodeA`, in UTF-16.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_GetMessageNodeW(buffer: *mut u16, size: isize) -> isize {
unsafe { get_text::<Utf16>(buffer, size, |state| &state.node) }
}
// --- Names -------------------------------------------------------------------
fn list(kind: NameKind) -> i32 {
call(-1, |state| {
state.names.clear();
let list = state.client()?.list_names(kind)?;
let kind = match kind {
NameKind::Topic => "topic",
NameKind::Node => "node",
};
let count = list.names.len() as i32;
state.names = serde_json::json!({
"kind": kind,
"truncated": list.truncated,
"names": list.names,
})
.to_string();
Ok(count)
})
}
/// Lists the topics this client may push to or read (every one if it may
/// query): how many, -1 on failure. Then `BakaShrot_GetNamesList()`.
#[unsafe(no_mangle)]
pub extern "C" fn BakaShrot_ListTopics() -> i32 {
list(NameKind::Topic)
}
/// Lists every node with messages: how many, -1 on failure. Then
/// `BakaShrot_GetNamesList()`.
#[unsafe(no_mangle)]
pub extern "C" fn BakaShrot_ListNodes() -> i32 {
list(NameKind::Node)
}
/// The last list, as JSON:
/// `{"kind":"topic","truncated":false,"names":["logs",...]}`, `truncated`
/// if some didn't fit.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_GetNamesListA(buffer: *mut c_char, size: isize) -> isize {
unsafe { get_text::<Utf8>(buffer.cast(), size, |state| &state.names) }
}
/// The same as `BakaShrot_GetNamesListA`, in UTF-16.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_GetNamesListW(buffer: *mut u16, size: isize) -> isize {
unsafe { get_text::<Utf16>(buffer, size, |state| &state.names) }
}
// --- Queries -----------------------------------------------------------------
unsafe fn query<T: Text>(sql: *const T::Unit) -> isize {
call(0, |state| {
state.query.clear();
let sql = required(unsafe { text::read::<T>(sql, "query")? }, "query")?;
state.query = state.client()?.query(&sql)?;
Ok(1)
})
}
/// Runs read-only SQL on the server (one SELECT or WITH), if this client
/// may query. Then `BakaShrot_GetQueryResult()`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_QueryA(sql: *const c_char) -> isize {
unsafe { query::<Utf8>(sql.cast()) }
}
/// The same as `BakaShrot_QueryA`, in UTF-16.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_QueryW(sql: *const u16) -> isize {
unsafe { query::<Utf16>(sql) }
}
/// The last query's result, as JSON:
/// `{"columns":[...],"rows":[[...],...]}`, every value a string or null.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_GetQueryResultA(buffer: *mut c_char, size: isize) -> isize {
unsafe { get_text::<Utf8>(buffer.cast(), size, |state| &state.query) }
}
/// The same as `BakaShrot_GetQueryResultA`, in UTF-16.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_GetQueryResultW(buffer: *mut u16, size: isize) -> isize {
unsafe { get_text::<Utf16>(buffer, size, |state| &state.query) }
}
// --- Attachments -------------------------------------------------------------
/// A message id, as arguments.
fn message_id(id: i64) -> Result<u64> {
u64::try_from(id).map_err(|_| invalid(format!("message {id}")))
}
unsafe fn push_with_file<T: Text>(
topic: *const T::Unit,
data: *const T::Unit,
path: *const T::Unit,
) -> i64 {
call(-1, |state| {
let (topic, data) = unsafe { topic_and_data::<T>(topic, data)? };
let path = required(unsafe { text::read::<T>(path, "the file")? }, "file")?;
let mut file = File::open(&path)
.map_err(|error| Error::new(ErrorCode::FileError, format!("{path}: {error}")))?;
let id = state
.client()?
.push_with_attachment(&topic, &data, &mut file)?;
Ok(id as i64)
})
}
/// Pushes a message with the file at `FilePath` as its attachment (1 byte
/// to 1 TiB, the server may take less: `TooBig`): uploaded with it, the
/// message stored once all of it came. Its id, -1 on failure. The file is
/// read twice (its SHA-256 first): one changed in between is refused
/// (`DataMismatch`).
#[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_PushMessageWithFileA(
topic: *const c_char,
data: *const c_char,
file_path: *const c_char,
) -> i64 {
unsafe { push_with_file::<Utf8>(topic.cast(), data.cast(), file_path.cast()) }
}
/// The same as `BakaShrot_PushMessageWithFileA`, in UTF-16.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_PushMessageWithFileW(
topic: *const u16,
data: *const u16,
file_path: *const u16,
) -> i64 {
unsafe { push_with_file::<Utf16>(topic, data, file_path) }
}
unsafe fn push_with_data<T: Text>(
topic: *const T::Unit,
data: *const T::Unit,
attachment: *const c_void,
size: i64,
) -> i64 {
call(-1, |state| {
let (topic, data) = unsafe { topic_and_data::<T>(topic, data)? };
if attachment.is_null() {
return Err(invalid("no attachment (a null pointer)"));
}
let size = usize::try_from(size)
.ok()
.filter(|size| *size > 0)
.ok_or_else(|| invalid(format!("an attachment of {size} bytes")))?;
let bytes = unsafe { std::slice::from_raw_parts(attachment.cast::<u8>(), size) };
let id = state
.client()?
.push_with_attachment(&topic, &data, &mut Cursor::new(bytes))?;
Ok(id as i64)
})
}
/// Pushes a message with the `Size` bytes at `Data` as its attachment, as
/// `BakaShrot_PushMessageWithFileA` does.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_PushMessageWithDataA(
topic: *const c_char,
data: *const c_char,
attachment: *const c_void,
size: i64,
) -> i64 {
unsafe { push_with_data::<Utf8>(topic.cast(), data.cast(), attachment, size) }
}
/// The same as `BakaShrot_PushMessageWithDataA`, in UTF-16.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_PushMessageWithDataW(
topic: *const u16,
data: *const u16,
attachment: *const c_void,
size: i64,
) -> i64 {
unsafe { push_with_data::<Utf16>(topic, data, attachment, size) }
}
unsafe fn save<T: Text>(
topic: *const T::Unit,
node: *const T::Unit,
id: i64,
path: *const T::Unit,
) -> i64 {
call(-1, |state| {
let (topic, node) = unsafe { topic_and_node::<T>(topic, node)? };
let path = required(unsafe { text::read::<T>(path, "the file")? }, "file")?;
let size =
state
.client()?
.save_attachment(&topic, &node, message_id(id)?, Path::new(&path))?;
Ok(size as i64)
})
}
/// Saves the attachment of `Topic`, `Node`'s message `MessageId` as the
/// file at `FilePath` (replaced), read a part at a time and checked with
/// its SHA-256: its size, -1 on failure (`NotFound` without one,
/// `NotReady` if it isn't on this server yet, `AttachmentMismatch`). A
/// failed one leaves no file.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_SaveAttachmentA(
topic: *const c_char,
node: *const c_char,
message_id: i64,
file_path: *const c_char,
) -> i64 {
unsafe { save::<Utf8>(topic.cast(), node.cast(), message_id, file_path.cast()) }
}
/// The same as `BakaShrot_SaveAttachmentA`, in UTF-16.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_SaveAttachmentW(
topic: *const u16,
node: *const u16,
message_id: i64,
file_path: *const u16,
) -> i64 {
unsafe { save::<Utf16>(topic, node, message_id, file_path) }
}
unsafe fn load<T: Text>(topic: *const T::Unit, node: *const T::Unit, id: i64) -> i64 {
call(-1, |state| {
state.attachment = Vec::new();
let (topic, node) = unsafe { topic_and_node::<T>(topic, node)? };
let mut attachment = Vec::new();
let size =
state
.client()?
.get_attachment(&topic, &node, message_id(id)?, &mut attachment)?;
state.attachment = attachment;
Ok(size as i64)
})
}
/// Reads the attachment of `Topic`, `Node`'s message `MessageId` into
/// memory, checked with its SHA-256 (`BakaShrot_SaveAttachmentA` for big
/// ones): its size, -1 on failure. Then `BakaShrot_GetAttachmentData()`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_LoadAttachmentA(
topic: *const c_char,
node: *const c_char,
message_id: i64,
) -> i64 {
unsafe { load::<Utf8>(topic.cast(), node.cast(), message_id) }
}
/// The same as `BakaShrot_LoadAttachmentA`, in UTF-16.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_LoadAttachmentW(
topic: *const u16,
node: *const u16,
message_id: i64,
) -> i64 {
unsafe { load::<Utf16>(topic, node, message_id) }
}
/// Copies what the last `BakaShrot_LoadAttachment()` read into `Buffer`, if
/// `BufferSize` is enough: returns its size (0 if none), copies nothing if
/// it doesn't fit (a null `Buffer` asks for the size).
#[unsafe(no_mangle)]
pub unsafe extern "C" fn BakaShrot_GetAttachmentData(buffer: *mut c_void, buffer_size: i64) -> i64 {
get(0, |state| {
let data = &state.attachment;
if !buffer.is_null() && usize::try_from(buffer_size).is_ok_and(|size| size >= data.len()) {
unsafe { std::ptr::copy_nonoverlapping(data.as_ptr(), buffer.cast(), data.len()) };
}
data.len() as i64
})
}
/// Frees what `BakaShrot_LoadAttachment()` read: 1.
#[unsafe(no_mangle)]
pub extern "C" fn BakaShrot_FreeAttachmentData() -> isize {
let freed = catch_unwind(AssertUnwindSafe(|| state().attachment = Vec::new()));
bool_result(freed.is_ok())
}
+95
View File
@@ -0,0 +1,95 @@
//! Strings across the C boundary: arguments read as UTF-8 (`A` exports) or
//! UTF-16 (`W` exports), answers copied into the caller's buffers.
use bakashrot_client::Error;
use bakashrot_proto::ErrorCode;
/// An encoding of the exports' strings.
pub(crate) trait Text {
/// One code unit: `u8` or `u16`.
type Unit: Copy + Default + PartialEq;
/// Its name, for errors.
const NAME: &'static str;
fn decode(units: &[Self::Unit]) -> Option<String>;
fn encode(text: &str) -> Vec<Self::Unit>;
}
/// UTF-8, `char*`: the `A` exports.
pub(crate) struct Utf8;
impl Text for Utf8 {
type Unit = u8;
const NAME: &'static str = "UTF-8";
fn decode(units: &[u8]) -> Option<String> {
String::from_utf8(units.to_vec()).ok()
}
fn encode(text: &str) -> Vec<u8> {
text.as_bytes().to_vec()
}
}
/// UTF-16, `uint16_t*` (`wchar_t*` on Windows): the `W` exports.
pub(crate) struct Utf16;
impl Text for Utf16 {
type Unit = u16;
const NAME: &'static str = "UTF-16";
fn decode(units: &[u16]) -> Option<String> {
String::from_utf16(units).ok()
}
fn encode(text: &str) -> Vec<u16> {
text.encode_utf16().collect()
}
}
/// A null-terminated string argument; `None` for a null pointer (what
/// PureBasic passes for an empty string).
///
/// # Safety
///
/// `pointer` is null, or points to a string ending with a zero unit.
pub(crate) unsafe fn read<T: Text>(
pointer: *const T::Unit,
what: &str,
) -> Result<Option<String>, Error> {
if pointer.is_null() {
return Ok(None);
}
let mut units = Vec::new();
loop {
// Unaligned: callers' buffers may be byte arrays.
let unit = unsafe { pointer.add(units.len()).read_unaligned() };
if unit == T::Unit::default() {
break;
}
units.push(unit);
}
T::decode(&units).map(Some).ok_or_else(|| {
Error::new(
ErrorCode::InvalidArgument,
format!("{what}: not valid {}", T::NAME),
)
})
}
/// Copies `text`, terminated, into `buffer` of `size` bytes if it fits
/// (nothing otherwise, or with a null `buffer`): the bytes it needs.
///
/// # Safety
///
/// `buffer` is null, or writable for `size` bytes.
pub(crate) unsafe fn copy<T: Text>(text: &str, buffer: *mut T::Unit, size: isize) -> isize {
let mut units = T::encode(text);
units.push(T::Unit::default());
let needed = std::mem::size_of_val(units.as_slice());
if !buffer.is_null() && size >= needed as isize {
unsafe {
std::ptr::copy_nonoverlapping(units.as_ptr().cast::<u8>(), buffer.cast::<u8>(), needed);
}
}
needed as isize
}
@@ -0,0 +1,95 @@
//! A server on a free port, in a folder of its own with its CA and the
//! clients' certificates.
use bakashrot_config::Config;
use bakashrot_pki::{Ca, Identity, Usage};
use bakashrot_server::Server;
use std::path::PathBuf;
const CONFIG: &str = r#"
[server]
listen = "127.0.0.1:0"
ca = "ca.crt"
certificate = "server.crt"
key = "server.key"
topics = ["logs", "secret"]
[roles.home]
push_topics = ["logs", "secret"]
read_topics = ["*"]
query = true
[roles.lounge]
read_topics = ["logs"]
"#;
pub struct Running {
pub folder: PathBuf,
pub port: u16,
ca: Ca,
// Kept for the server's tasks to run.
_runtime: tokio::runtime::Runtime,
}
impl Running {
pub fn start(name: &str) -> Running {
let folder = PathBuf::from(env!("CARGO_TARGET_TMPDIR"))
.join(format!("capi-{}-{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&folder);
std::fs::create_dir_all(&folder).unwrap();
let issued = Ca::create("Test CA", 10).unwrap();
let ca = Ca::load(&issued.certificate, &issued.key).unwrap();
let server = ca
.issue(
&Identity::new("server-1", &["peer"]).unwrap(),
Usage::Server,
10,
)
.unwrap();
std::fs::write(folder.join("ca.crt"), &issued.certificate).unwrap();
std::fs::write(folder.join("server.crt"), &server.certificate).unwrap();
std::fs::write(folder.join("server.key"), &server.key).unwrap();
// `SYNC=normal` to measure without a disk flush per push.
let sync = std::env::var("SYNC").unwrap_or_else(|_| "full".into());
let config = CONFIG.replace(
"[roles.home]",
&format!(
"synchronous = \"{sync}\"
[roles.home]"
),
);
std::fs::write(folder.join("server.toml"), config).unwrap();
let config = Config::load(&folder.join("server.toml")).unwrap();
let server = Server::start(config).unwrap();
let runtime = tokio::runtime::Runtime::new().unwrap();
let listener = runtime
.block_on(tokio::net::TcpListener::bind("127.0.0.1:0"))
.unwrap();
let port = listener.local_addr().unwrap().port();
runtime.spawn(async move { server.serve(listener).await });
Running {
folder,
port,
ca,
_runtime: runtime,
}
}
/// Issues a client's certificate, written as `<name>.crt` and
/// `<name>.key`, with a `<name>.toml` to connect with.
pub fn issue(&self, name: &str, roles: &[&str]) {
let issued = self
.ca
.issue(&Identity::new(name, roles).unwrap(), Usage::Client, 10)
.unwrap();
std::fs::write(self.folder.join(format!("{name}.crt")), &issued.certificate).unwrap();
std::fs::write(self.folder.join(format!("{name}.key")), &issued.key).unwrap();
let toml = format!(
"server = \"127.0.0.1:{}\"\nca = \"ca.crt\"\ncertificate = \"{name}.crt\"\nkey = \"{name}.key\"\n",
self.port
);
std::fs::write(self.folder.join(format!("{name}.toml")), toml).unwrap();
}
}
@@ -0,0 +1,341 @@
//! The exports called as C would, against a server: the `W` ones (what
//! PureBasic uses; Python's check covers the `A` ones), the buffers, the
//! errors. One test: the DLL holds one connection per process.
#![allow(unsafe_code)]
mod common;
use bakashrot::*;
use bakashrot_proto::ErrorCode;
use std::ffi::{CString, c_char};
fn w(text: &str) -> Vec<u16> {
text.encode_utf16().chain([0]).collect()
}
fn a(text: &str) -> CString {
CString::new(text).unwrap()
}
/// A `W` getter's string: asks for the size, then copies.
fn get_w(getter: unsafe extern "C" fn(*mut u16, isize) -> isize) -> String {
let size = unsafe { getter(std::ptr::null_mut(), 0) };
let mut buffer = vec![0u16; size as usize / 2];
unsafe { getter(buffer.as_mut_ptr(), size) };
String::from_utf16(&buffer[..buffer.len() - 1]).unwrap()
}
fn get_a(getter: unsafe extern "C" fn(*mut c_char, isize) -> isize) -> String {
let size = unsafe { getter(std::ptr::null_mut(), 0) };
let mut buffer = vec![0u8; size as usize];
unsafe { getter(buffer.as_mut_ptr().cast(), size) };
String::from_utf8(buffer[..buffer.len() - 1].to_vec()).unwrap()
}
/// The last error's code and reason.
fn error() -> (u32, String) {
(
BakaShrot_GetLastError() as u32,
get_w(BakaShrot_GetRefusalReasonW),
)
}
fn code(code: ErrorCode) -> u32 {
code.code()
}
#[test]
fn exports() {
let running = common::Running::start("exports");
running.issue("kitchen", &["home"]);
running.issue("lounge", &["lounge"]);
let file = |name: &str| running.folder.join(name).display().to_string();
let pem = |name: &str| std::fs::read_to_string(running.folder.join(name)).unwrap();
let localhost = w("127.0.0.1");
let port = i32::from(running.port);
unsafe {
// Nothing set, not connected.
assert_eq!(
BakaShrot_PushMessageToW(w("logs").as_ptr(), w("{}").as_ptr()),
-1
);
assert_eq!(error().0, code(ErrorCode::NotConnected));
assert_eq!(BakaShrot_ConnectW(localhost.as_ptr(), port), 0);
let (failed, why) = error();
assert_eq!(failed, code(ErrorCode::InvalidArgument));
assert!(why.contains("BakaShrot_SetCaCertificate"), "{why}");
// Files or PEM text; a missing file, an empty setting.
assert_eq!(
BakaShrot_SetCaCertificateW(w(&file("missing.crt")).as_ptr()),
0
);
assert_eq!(error().0, code(ErrorCode::FileError));
assert_eq!(BakaShrot_SetCertificateW(std::ptr::null()), 0);
assert_eq!(error().0, code(ErrorCode::InvalidArgument));
assert_eq!(BakaShrot_SetCaCertificateW(w(&file("ca.crt")).as_ptr()), 1);
assert_eq!(BakaShrot_GetLastError(), 0);
assert_eq!(
BakaShrot_SetCertificateW(w(&pem("kitchen.crt")).as_ptr()),
1
);
assert_eq!(
BakaShrot_SetPrivateKeyA(a(&file("kitchen.key")).as_ptr()),
1
);
assert_eq!(BakaShrot_SetCrlW(std::ptr::null()), 1);
assert_eq!(BakaShrot_ConnectW(localhost.as_ptr(), 0), 0);
assert_eq!(error().0, code(ErrorCode::InvalidArgument));
assert_eq!(
BakaShrot_ConnectW(localhost.as_ptr(), port),
1,
"{:?}",
error()
);
assert_eq!(BakaShrot_IsConnected(), 1);
assert_eq!(get_w(BakaShrot_GetNodeW), "kitchen");
assert_eq!(BakaShrot_ConnectW(localhost.as_ptr(), port), 0);
assert_eq!(error().0, code(ErrorCode::AlreadyConnected));
assert_eq!(BakaShrot_SetCaCertificateW(w(&file("ca.crt")).as_ptr()), 0);
assert_eq!(error().0, code(ErrorCode::AlreadyConnected));
// Pushes: UTF-16, a null message is an empty one.
assert_eq!(
BakaShrot_PushMessageToW(w("logs").as_ptr(), w(r#"{"i":1}"#).as_ptr()),
1
);
assert_eq!(
BakaShrot_PushMessageToW(w("logs").as_ptr(), w("héllo 🌍").as_ptr()),
2
);
assert_eq!(
BakaShrot_PushMessageToW(w("logs").as_ptr(), std::ptr::null()),
3
);
assert_eq!(
BakaShrot_PushMessageToW(std::ptr::null(), w("{}").as_ptr()),
-1
);
assert_eq!(error().0, code(ErrorCode::InvalidArgument));
assert_eq!(
BakaShrot_PushMessageToW(w("nothing").as_ptr(), w("{}").as_ptr()),
-1
);
let (failed, why) = error();
assert_eq!(failed, code(ErrorCode::UnknownName));
assert!(why.contains("unknown topic"), "{why}");
// The latest; none yet in another topic.
assert_eq!(
BakaShrot_GetLatestMessageOfW(w("logs").as_ptr(), w("kitchen").as_ptr()),
1
);
assert_eq!(
(BakaShrot_GetMessageCount(), BakaShrot_GetMessageId()),
(1, 3)
);
assert_eq!(get_w(BakaShrot_GetMessageDataW), "");
assert!(BakaShrot_GetMessagePushedAt() > 1_700_000_000_000);
assert_eq!(BakaShrot_GetMessageAttachmentSize(), 0);
assert_eq!(BakaShrot_IsMessageAttachmentReady(), 0);
assert_eq!(
BakaShrot_GetLatestMessageOfW(w("secret").as_ptr(), w("kitchen").as_ptr()),
0
);
assert_eq!(error().0, code(ErrorCode::NotFound));
assert_eq!(BakaShrot_GetMessageCount(), 0);
// A run of messages, selected one by one.
assert_eq!(
BakaShrot_GetMessagesW(w("logs").as_ptr(), w("kitchen").as_ptr(), 0, 2),
2
);
assert_eq!(BakaShrot_HasMoreMessages(), 1);
assert_eq!(get_w(BakaShrot_GetMessageTopicW), "logs");
assert_eq!(get_w(BakaShrot_GetMessageNodeW), "kitchen");
assert_eq!(BakaShrot_GetMessageId(), 1);
assert_eq!(BakaShrot_SelectMessage(1), 1);
assert_eq!(get_w(BakaShrot_GetMessageDataW), "héllo 🌍");
assert_eq!(get_a(BakaShrot_GetMessageDataA), "héllo 🌍");
assert_eq!(BakaShrot_SelectMessage(2), 0);
assert_eq!(error().0, code(ErrorCode::InvalidArgument));
assert_eq!(BakaShrot_GetMessageId(), 2, "the selection stays");
assert_eq!(
BakaShrot_GetMessagesW(w("logs").as_ptr(), w("kitchen").as_ptr(), 3, 10),
0
);
assert_eq!(BakaShrot_HasMoreMessages(), 0);
assert_eq!(BakaShrot_GetMessageId(), 0);
for (after, limit) in [(-1, 10), (0, 0), (0, 10_001)] {
assert_eq!(
BakaShrot_GetMessagesW(w("logs").as_ptr(), w("kitchen").as_ptr(), after, limit),
-1
);
assert_eq!(error().0, code(ErrorCode::InvalidArgument));
}
assert_eq!(
BakaShrot_GetMessagesW(w("logs").as_ptr(), w("nobody").as_ptr(), 0, 10),
-1
);
assert_eq!(error().0, code(ErrorCode::UnknownName));
assert_eq!(BakaShrot_IsConnected(), 1, "a refusal keeps the connection");
// The buffers: the size needed, nothing copied if it doesn't fit.
BakaShrot_GetMessagesW(w("logs").as_ptr(), w("kitchen").as_ptr(), 0, 1);
assert_eq!(BakaShrot_GetMessageDataW(std::ptr::null_mut(), 0), 16);
assert_eq!(BakaShrot_GetMessageDataA(std::ptr::null_mut(), 0), 8);
let mut small = [7u16; 7];
assert_eq!(BakaShrot_GetMessageDataW(small.as_mut_ptr(), 14), 16);
assert_eq!(small, [7; 7]);
// Unaligned: a byte buffer.
let mut bytes = [0u8; 17];
assert_eq!(
BakaShrot_GetMessageDataW(bytes[1..].as_mut_ptr().cast(), 16),
16
);
assert_eq!(bytes[1..3], [b'{', 0]);
// Names, queries.
assert_eq!(BakaShrot_ListTopics(), 2);
assert_eq!(
get_w(BakaShrot_GetNamesListW),
r#"{"kind":"topic","names":["logs","secret"],"truncated":false}"#
);
assert_eq!(BakaShrot_ListNodes(), 1);
assert_eq!(
BakaShrot_QueryW(w("SELECT COUNT(*) AS n FROM data").as_ptr()),
1
);
assert_eq!(
get_w(BakaShrot_GetQueryResultW),
r#"{"columns":["n"],"rows":[["3"]]}"#
);
assert_eq!(BakaShrot_QueryW(w("SELECT nope").as_ptr()), 0);
assert_eq!(error().0, code(ErrorCode::QueryFailed));
assert_eq!(get_w(BakaShrot_GetQueryResultW), "");
// Attachments: from a file or memory, saved or loaded back.
let (logs, kitchen) = (w("logs"), w("kitchen"));
let photo: Vec<u8> = (0..1_500_000u32).map(|i| (i % 251) as u8).collect();
std::fs::write(running.folder.join("photo.bin"), &photo).unwrap();
let photo_file = w(&file("photo.bin"));
let pushed = BakaShrot_PushMessageWithFileW(
logs.as_ptr(),
w(r#"{"photo":1}"#).as_ptr(),
photo_file.as_ptr(),
);
assert_eq!(pushed, 4, "{:?}", error());
let tiny = b"tiny";
let pushed = BakaShrot_PushMessageWithDataW(
logs.as_ptr(),
std::ptr::null(),
tiny.as_ptr().cast(),
4,
);
assert_eq!(pushed, 5, "{:?}", error());
assert_eq!(
BakaShrot_GetLatestMessageOfW(logs.as_ptr(), kitchen.as_ptr()),
1
);
assert_eq!(
(
BakaShrot_GetMessageId(),
BakaShrot_GetMessageAttachmentSize(),
BakaShrot_IsMessageAttachmentReady()
),
(5, 4, 1)
);
let saved = w(&file("saved.bin"));
assert_eq!(
BakaShrot_SaveAttachmentW(logs.as_ptr(), kitchen.as_ptr(), 4, saved.as_ptr()),
1_500_000
);
assert_eq!(
std::fs::read(running.folder.join("saved.bin")).unwrap(),
photo
);
assert_eq!(
BakaShrot_LoadAttachmentW(logs.as_ptr(), kitchen.as_ptr(), 5),
4
);
assert_eq!(BakaShrot_GetAttachmentData(std::ptr::null_mut(), 0), 4);
let mut small = [9u8; 3];
assert_eq!(BakaShrot_GetAttachmentData(small.as_mut_ptr().cast(), 3), 4);
assert_eq!(small, [9; 3], "nothing copied if it doesn't fit");
let mut data = [0u8; 4];
assert_eq!(BakaShrot_GetAttachmentData(data.as_mut_ptr().cast(), 4), 4);
assert_eq!(&data, tiny);
assert_eq!(BakaShrot_FreeAttachmentData(), 1);
assert_eq!(BakaShrot_GetAttachmentData(std::ptr::null_mut(), 0), 0);
assert_eq!(
BakaShrot_LoadAttachmentA(a("logs").as_ptr(), a("kitchen").as_ptr(), 4),
1_500_000
);
BakaShrot_FreeAttachmentData();
// Refused, or the client's own failures: -1, no file.
let none = w(&file("none.bin"));
assert_eq!(
BakaShrot_SaveAttachmentW(logs.as_ptr(), kitchen.as_ptr(), 1, none.as_ptr()),
-1
);
assert_eq!(error().0, code(ErrorCode::NotFound));
assert!(!running.folder.join("none.bin").exists());
assert_eq!(
BakaShrot_SaveAttachmentW(logs.as_ptr(), kitchen.as_ptr(), -1, none.as_ptr()),
-1
);
assert_eq!(error().0, code(ErrorCode::InvalidArgument));
let missing = w(&file("missing.bin"));
assert_eq!(
BakaShrot_PushMessageWithFileW(logs.as_ptr(), std::ptr::null(), missing.as_ptr()),
-1
);
assert_eq!(error().0, code(ErrorCode::FileError));
for (pointer, size) in [(std::ptr::null(), 4), (tiny.as_ptr(), 0)] {
let pushed = BakaShrot_PushMessageWithDataW(
logs.as_ptr(),
std::ptr::null(),
pointer.cast(),
size,
);
assert_eq!(pushed, -1);
assert_eq!(error().0, code(ErrorCode::InvalidArgument));
}
assert_eq!(BakaShrot_IsConnected(), 1);
// Closed: requests refused, the settings kept.
assert_eq!(BakaShrot_Disconnect(), 1);
assert_eq!(BakaShrot_Disconnect(), 0);
assert_eq!(BakaShrot_IsConnected(), 0);
assert_eq!(get_w(BakaShrot_GetNodeW), "");
assert_eq!(BakaShrot_QueryW(w("SELECT 1").as_ptr()), 0);
assert_eq!(error().0, code(ErrorCode::NotConnected));
// Another identity, by the A exports: not allowed to query.
assert_eq!(
BakaShrot_SetCertificateA(a(&file("lounge.crt")).as_ptr()),
1
);
assert_eq!(BakaShrot_SetPrivateKeyA(a(&pem("lounge.key")).as_ptr()), 1);
assert_eq!(
BakaShrot_ConnectA(a("localhost").as_ptr(), port),
1,
"{:?}",
error()
);
assert_eq!(get_a(BakaShrot_GetNodeA), "lounge");
assert_eq!(BakaShrot_QueryA(a("SELECT 1").as_ptr()), 0);
let (failed, why) = error();
assert_eq!(failed, code(ErrorCode::NotAllowed));
assert_eq!(get_a(BakaShrot_GetRefusalReasonA), why);
BakaShrot_Disconnect();
// Nothing listening there.
assert_eq!(BakaShrot_ConnectA(a("127.0.0.1").as_ptr(), 1), 0);
assert_eq!(error().0, code(ErrorCode::ConnectFailed));
}
}
@@ -0,0 +1,20 @@
//! `bindings/c/bakashrot.h` matches the exports: rewritten when it doesn't
//! (the test fails then, check the new one in).
use std::path::Path;
#[test]
fn the_header_is_current() {
let crate_dir = env!("CARGO_MANIFEST_DIR");
let path = Path::new(crate_dir).join("../../bindings/c/bakashrot.h");
let mut generated = Vec::new();
cbindgen::generate(crate_dir)
.expect("cbindgen reads the crate")
.write(&mut generated);
let current = std::fs::read(&path).unwrap_or_default();
if current != generated {
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(&path, &generated).unwrap();
panic!("{} was out of date: rewritten, check it in", path.display());
}
}
@@ -0,0 +1,66 @@
//! `bindings/python/check_bakashrot.py` on the DLL against a server: the
//! Python module and the DLL as an app loads it. Skipped (said so) without
//! a Python 3.11+ on the PATH.
mod common;
use std::path::{Path, PathBuf};
use std::process::Command;
#[test]
fn check_bakashrot_py() {
let Some(python) = ["python3", "python"].into_iter().find(|python| {
Command::new(python)
.args(["-c", "import sys, tomllib; sys.exit(0)"])
.output()
.is_ok_and(|output| output.status.success())
}) else {
eprintln!("SKIPPED: no Python 3.11+ on the PATH");
return;
};
let dll = built_dll();
let running = common::Running::start("python");
running.issue("kitchen", &["home"]);
running.issue("lounge", &["lounge"]);
running.issue("guest", &["guest"]);
let bindings = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../bindings/python");
let output = Command::new(python)
.arg(bindings.join("check_bakashrot.py"))
.arg(&dll)
.arg(&running.folder)
.env("PYTHONPATH", &bindings)
.env("PYTHONIOENCODING", "utf-8")
.output()
.unwrap();
let stdout = String::from_utf8_lossy(&output.stdout);
println!("{stdout}");
eprintln!("{}", String::from_utf8_lossy(&output.stderr));
assert!(output.status.success(), "check_bakashrot.py failed");
assert!(stdout.contains("All checks passed"));
}
/// The DLL cargo built with this test: next to it (cargo's older layout),
/// or the newest in this crate's build folders (`build/bakashrot-capi/*/out/`).
fn built_dll() -> PathBuf {
let name = format!(
"{}bakashrot{}",
std::env::consts::DLL_PREFIX,
std::env::consts::DLL_SUFFIX
);
let exe = std::env::current_exe().unwrap();
let here = exe.parent().unwrap();
if here.join(&name).exists() {
return here.join(name);
}
let builds = here.ancestors().nth(2).unwrap();
std::fs::read_dir(builds)
.unwrap()
.filter_map(|entry| Some(entry.ok()?.path().join("out").join(&name)))
.filter_map(|dll| Some((dll.metadata().ok()?.modified().ok()?, dll)))
.max()
.map(|(_, dll)| dll)
.unwrap_or_else(|| panic!("no {name} built near {}", here.display()))
}
+21
View File
@@ -0,0 +1,21 @@
[package]
name = "bakashrot-client"
description = "BakaShrot's client library: blocking, TLS with the CA's certificates, the requests of protocol 7."
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
authors.workspace = true
repository.workspace = true
publish.workspace = true
[dependencies]
# The attachments' SHA-256: the TLS one's (aws-lc), no other crate.
aws-lc-rs = "1.19.0"
bakashrot-proto = { path = "../bakashrot-proto" }
bakashrot-pki = { path = "../bakashrot-pki" }
# The same as bakashrot-pki's: TLS 1.3 through aws-lc.
rustls = { version = "0.23.46", default-features = false, features = ["aws_lc_rs", "std"] }
[lints]
workspace = true
+543
View File
@@ -0,0 +1,543 @@
//! BakaShrot's client: one connection to a server, blocking, one request
//! at a time (no async runtime: the C DLL wraps this as it is).
//!
//! ```no_run
//! # fn main() -> Result<(), bakashrot_client::Error> {
//! use bakashrot_client::{Client, Settings};
//! let (ca, certificate, key) = (String::new(), String::new(), String::new()); // PEM
//! let settings = Settings { ca: &ca, certificate: &certificate, key: &key, crl: None };
//! let mut client = Client::connect("10.0.0.2:7000", &settings)?;
//! let id = client.push("logs", r#"{"temp": 21}"#)?;
//! let node = client.node().to_owned();
//! let latest = client.get_messages("logs", &node, None, 1)?;
//! # Ok(()) }
//! ```
//!
//! The connection: TLS 1.3 with the CA's certificates (`bakashrot-pki`),
//! ALPN `bakashrot`, both ends' protocol versions, then the server's
//! `Welcome` (`Source/docs/protocol.md`). Errors carry the protocol's codes
//! (`bakashrot_proto::ErrorCode`): a server's refusal keeps its own.
use aws_lc_rs::digest;
use bakashrot_pki::{Revocations, tls};
use bakashrot_proto::limits::{
ALPN, ATTACHMENT_PART_SIZE, MAX_ATTACHMENT_SIZE, MAX_MESSAGE_ID, MAX_MESSAGE_SIZE,
MAX_MESSAGES_PER_PACKET, MAX_PACKET_SIZE,
};
use bakashrot_proto::names::is_valid_name;
use bakashrot_proto::packets::{
Attachment, AttachmentPart, GetAttachment, GetMessages, ListNames, Messages, NameKind,
NamesList, PushMessage, Query,
};
use bakashrot_proto::{ErrorCode, Packet, frame};
use rustls::{ClientConnection, StreamOwned};
use std::fmt;
use std::fs::{self, File};
use std::io::{self, Read, Seek, Write};
use std::net::{Shutdown, TcpStream, ToSocketAddrs};
use std::path::{Path, PathBuf};
use std::time::Duration;
/// How long connecting may take: TCP, TLS, the versions, the welcome.
pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
/// How long an answer may take.
pub const ANSWER_TIMEOUT: Duration = Duration::from_secs(30);
/// What a client connects with, PEM text as files hold it.
#[derive(Debug, Clone, Copy)]
pub struct Settings<'a> {
/// The CA's certificate: servers are taken if it issued theirs.
pub ca: &'a str,
/// This client's certificate: its node, its roles.
pub certificate: &'a str,
/// Its key.
pub key: &'a str,
/// The CA's CRL, if given: servers it revokes are refused.
pub crl: Option<&'a str>,
}
/// What went wrong: a protocol error code (a server's refusal, 1-99, or
/// the client's own, 100 and up) and why.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Error {
code: u32,
message: String,
}
impl Error {
/// An error of `code`, saying why.
pub fn new(code: ErrorCode, message: impl Into<String>) -> Error {
Error {
code: code.code(),
message: message.into(),
}
}
/// Its code (`bakashrot_proto::error`).
pub fn code(&self) -> u32 {
self.code
}
/// Why, in words.
pub fn message(&self) -> &str {
&self.message
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let name = bakashrot_proto::error::code_name(self.code);
write!(f, "{} ({}): {}", name, self.code, self.message)
}
}
impl std::error::Error for Error {}
/// A result of this crate.
pub type Result<T> = std::result::Result<T, Error>;
/// A connection to a server.
pub struct Client {
stream: StreamOwned<ClientConnection, TcpStream>,
server: String,
node: String,
}
impl fmt::Debug for Client {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Client")
.field("server", &self.server)
.field("node", &self.node)
.finish_non_exhaustive()
}
}
impl Client {
/// Connects to the server at `address` (`host:port`): any of the CA's
/// servers, whatever its address.
pub fn connect(address: &str, settings: &Settings<'_>) -> Result<Client> {
let invalid = |what: &str| {
let what = what.to_owned();
move |error: bakashrot_pki::Error| {
Error::new(ErrorCode::InvalidArgument, format!("{what}: {error}"))
}
};
let revocations = match settings.crl {
Some(crl) => Revocations::load(crl, settings.ca).map_err(invalid("the CRL"))?,
None => Revocations::none(),
};
let config = tls::client_config(
settings.ca,
settings.certificate,
settings.key,
revocations.shared(),
)
.map_err(invalid("the certificates"))?;
let tcp = connect_tcp(address)?;
let connection = ClientConnection::new(config, tls::server_name())
.map_err(|error| Error::new(ErrorCode::InvalidArgument, error.to_string()))?;
let mut stream = StreamOwned::new(connection, tcp);
while stream.conn.is_handshaking() {
stream.conn.complete_io(&mut stream.sock).map_err(lost)?;
}
if stream.conn.alpn_protocol() != Some(ALPN) {
return Err(Error::new(
ErrorCode::AuthRejected,
"the server doesn't speak BakaShrot",
));
}
frame::write_version(&mut stream).map_err(lost)?;
stream.flush().map_err(lost)?;
let theirs = frame::read_version(&mut stream).map_err(lost)?;
if let Err(version) = frame::check_version(theirs) {
return Err(Error::new(
ErrorCode::VersionMismatch,
format!(
"the server speaks protocol {version}, this client {}",
bakashrot_proto::limits::PROTOCOL_VERSION
),
));
}
let mut client = Client {
stream,
server: String::new(),
node: String::new(),
};
match client.answer()? {
Packet::Welcome(welcome) => {
client.server = welcome.server;
client.node = welcome.node;
}
other => return Err(unexpected(&other)),
}
let tcp = &client.stream.sock;
tcp.set_read_timeout(Some(ANSWER_TIMEOUT)).map_err(lost)?;
tcp.set_write_timeout(Some(ANSWER_TIMEOUT)).map_err(lost)?;
Ok(client)
}
/// The server's name.
pub fn server(&self) -> &str {
&self.server
}
/// The node this client writes as: its certificate's name.
pub fn node(&self) -> &str {
&self.node
}
/// Whether the connection still looks open: the server hasn't closed
/// it (after its idle timeout, say). Only a request tells for sure.
pub fn is_open(&self) -> bool {
let tcp = &self.stream.sock;
if tcp.set_nonblocking(true).is_err() {
return false;
}
let open = match tcp.peek(&mut [0]) {
Ok(read) => read > 0,
Err(error) => error.kind() == io::ErrorKind::WouldBlock,
};
open && tcp.set_nonblocking(false).is_ok()
}
/// Pushes a message to `topic`, as this client's node: its id.
pub fn push(&mut self, topic: &str, data: &str) -> Result<u64> {
check_name(topic, "topic")?;
check_size(data, "a message")?;
let push = PushMessage {
topic: topic.to_owned(),
data: data.to_owned(),
attachment: None,
};
match self.request(push.into())? {
Packet::MessagePushed(pushed) => Ok(pushed.message_id),
other => Err(unexpected(&other)),
}
}
/// Pushes a message with an attachment read from `source` (a `File`, a
/// `Cursor` over bytes), from its start to its end: twice, for its
/// SHA-256, then to send it (a source changed in between is refused,
/// `DataMismatch`). 1 byte to `MAX_ATTACHMENT_SIZE` (servers may take
/// less, `TooBig`). A source failing while it's sent closes the
/// connection (`FileError`).
pub fn push_with_attachment(
&mut self,
topic: &str,
data: &str,
source: &mut (impl Read + Seek),
) -> Result<u64> {
check_name(topic, "topic")?;
check_size(data, "a message")?;
source.rewind().map_err(file_error)?;
let mut sha256 = digest::Context::new(&digest::SHA256);
let mut buffer = vec![0; ATTACHMENT_PART_SIZE as usize];
let mut size = 0;
loop {
let read = source.read(&mut buffer).map_err(file_error)?;
if read == 0 {
break;
}
sha256.update(&buffer[..read]);
size += read as u64;
}
if !(1..=MAX_ATTACHMENT_SIZE).contains(&size) {
return Err(Error::new(
ErrorCode::InvalidArgument,
format!("an attachment of {size} bytes: 1 to {MAX_ATTACHMENT_SIZE}"),
));
}
source.rewind().map_err(file_error)?;
let mut digest = [0; 32];
digest.copy_from_slice(sha256.finish().as_ref());
let attachment = Attachment {
size,
sha256: digest,
};
let push = PushMessage {
topic: topic.to_owned(),
data: data.to_owned(),
attachment: Some(attachment.clone()),
};
match self.request(push.into())? {
Packet::Continue(_) => {}
other => return Err(unexpected(&other)),
}
for part in 0..attachment.part_count() {
let part = &mut buffer[..attachment.part_len(part) as usize];
if let Err(error) = source.read_exact(part) {
self.close();
return Err(file_error(error));
}
let packet = Packet::from(AttachmentPart {
data: part.to_vec(),
});
frame::write(&mut self.stream, &packet.encode()).map_err(lost)?;
}
self.stream.flush().map_err(lost)?;
match self.answer()? {
Packet::MessagePushed(pushed) => Ok(pushed.message_id),
other => Err(unexpected(&other)),
}
}
/// Writes a message's attachment into `out`, a part at a time, checked
/// with its SHA-256 once all came (`AttachmentMismatch`): its size.
/// What `out` has when it fails is to be thrown away.
pub fn get_attachment(
&mut self,
topic: &str,
node: &str,
message_id: u64,
out: &mut impl Write,
) -> Result<u64> {
check_name(topic, "topic")?;
check_name(node, "node")?;
if !(1..=MAX_MESSAGE_ID).contains(&message_id) {
return Err(Error::new(
ErrorCode::InvalidArgument,
format!("message {message_id}: 1 to {MAX_MESSAGE_ID}"),
));
}
let get = GetAttachment {
topic: topic.to_owned(),
node: node.to_owned(),
message_id,
from_part: 0,
};
let attachment = match self.request(get.into())? {
Packet::Attachment(attachment) => attachment,
other => return Err(unexpected(&other)),
};
let mut sha256 = digest::Context::new(&digest::SHA256);
// A failing `out`: the parts are still all read, the connection
// stays usable.
let mut failed = None;
for part in 0..attachment.part_count() {
let data = match self.answer()? {
Packet::AttachmentPart(part) => part.data,
other => {
self.close();
return Err(unexpected(&other));
}
};
let expected = attachment.part_len(part);
if data.len() as u64 != expected {
self.close();
return Err(Error::new(
ErrorCode::ProtocolError,
format!("part {part}: {} bytes, {expected} expected", data.len()),
));
}
sha256.update(&data);
if failed.is_none() {
failed = out.write_all(&data).err();
}
}
if let Some(error) = failed {
return Err(file_error(error));
}
out.flush().map_err(file_error)?;
if sha256.finish().as_ref() != attachment.sha256 {
return Err(Error::new(
ErrorCode::AttachmentMismatch,
"the attachment doesn't match its SHA-256",
));
}
Ok(attachment.size)
}
/// Saves a message's attachment as `path` ([`Client::get_attachment`]):
/// written aside (`path` and `.download`), then moved over it, so a
/// failed one leaves no file.
pub fn save_attachment(
&mut self,
topic: &str,
node: &str,
message_id: u64,
path: &Path,
) -> Result<u64> {
let mut aside = path.as_os_str().to_owned();
aside.push(".download");
let aside = PathBuf::from(aside);
let mut file = File::create(&aside).map_err(file_error)?;
let saved = self.get_attachment(topic, node, message_id, &mut file);
drop(file);
let saved = saved.and_then(|size| {
fs::rename(&aside, path).map_err(file_error)?;
Ok(size)
});
if saved.is_err() {
let _ = fs::remove_file(&aside);
}
saved
}
/// A topic and node's messages: `after` an id (0 for the first ones),
/// or the last ones (`None`); `limit` at most (1-10000). `more` if
/// others follow.
pub fn get_messages(
&mut self,
topic: &str,
node: &str,
after: Option<u64>,
limit: u32,
) -> Result<Messages> {
check_name(topic, "topic")?;
check_name(node, "node")?;
if !(1..=MAX_MESSAGES_PER_PACKET).contains(&limit) {
return Err(Error::new(
ErrorCode::InvalidArgument,
format!("a limit of {limit}: 1 to {MAX_MESSAGES_PER_PACKET}"),
));
}
if after.is_some_and(|after| after > MAX_MESSAGE_ID) {
return Err(Error::new(
ErrorCode::InvalidArgument,
format!("after {}: {MAX_MESSAGE_ID} at most", after.unwrap_or(0)),
));
}
let get = GetMessages {
topic: topic.to_owned(),
node: node.to_owned(),
after,
limit,
};
match self.request(get.into())? {
Packet::Messages(messages) => Ok(messages),
other => Err(unexpected(&other)),
}
}
/// The topics this client may push to or read (every one if it may
/// query), or every node with messages. `truncated` if some didn't fit.
pub fn list_names(&mut self, kind: NameKind) -> Result<NamesList> {
match self.request(ListNames { kind }.into())? {
Packet::NamesList(names) => Ok(names),
other => Err(unexpected(&other)),
}
}
/// Runs read-only SQL: `{"columns":[...],"rows":[[...],...]}`, every
/// value a string or null (`Source/docs/storage.md`, "The query surface").
pub fn query(&mut self, sql: &str) -> Result<String> {
check_size(sql, "a query")?;
let query = Query {
sql: sql.to_owned(),
};
match self.request(query.into())? {
Packet::QueryResult(result) => Ok(result.json),
other => Err(unexpected(&other)),
}
}
/// Closes the connection: it's out of step (a part not sent, or not
/// as expected). Every request fails then (`ConnectionLost`).
fn close(&mut self) {
let _ = self.stream.sock.shutdown(Shutdown::Both);
}
/// Sends a request, reads its answer.
fn request(&mut self, packet: Packet) -> Result<Packet> {
frame::write(&mut self.stream, &packet.encode()).map_err(lost)?;
self.stream.flush().map_err(lost)?;
self.answer()
}
/// Reads the server's next packet: a refusal is an error.
fn answer(&mut self) -> Result<Packet> {
let bytes = frame::read(&mut self.stream, MAX_PACKET_SIZE)
.map_err(lost)?
.ok_or_else(|| {
Error::new(
ErrorCode::ConnectionLost,
"the server closed the connection",
)
})?;
match Packet::decode(&bytes) {
Ok(Packet::RequestRefused(refused)) => Err(Error {
code: refused.code,
message: refused.reason,
}),
Ok(packet) => Ok(packet),
Err(error) => Err(Error::new(ErrorCode::ProtocolError, error.to_string())),
}
}
}
/// A TCP connection to the first of `address`'s addresses that answers.
fn connect_tcp(address: &str) -> Result<TcpStream> {
let failed = |why: String| Error::new(ErrorCode::ConnectFailed, format!("{address}: {why}"));
let addresses = address
.to_socket_addrs()
.map_err(|error| failed(error.to_string()))?;
let mut last = String::from("no address");
for socket in addresses {
match TcpStream::connect_timeout(&socket, CONNECT_TIMEOUT) {
Ok(tcp) => {
tcp.set_nodelay(true).map_err(lost)?;
tcp.set_read_timeout(Some(CONNECT_TIMEOUT)).map_err(lost)?;
tcp.set_write_timeout(Some(CONNECT_TIMEOUT)).map_err(lost)?;
return Ok(tcp);
}
Err(error) => last = error.to_string(),
}
}
Err(failed(last))
}
/// An I/O error's code: the TLS ones say who refused whom.
fn lost(error: io::Error) -> Error {
let tls = error
.get_ref()
.and_then(|inner| inner.downcast_ref::<rustls::Error>());
match tls {
Some(rustls::Error::InvalidCertificate(why)) => Error::new(
ErrorCode::ServerNotVerified,
format!("the server's certificate: {why:?}"),
),
Some(rustls::Error::AlertReceived(alert)) => Error::new(
ErrorCode::AuthRejected,
format!("the server refused this client's certificate ({alert:?})"),
),
Some(other) => Error::new(ErrorCode::AuthRejected, other.to_string()),
None => Error::new(ErrorCode::ConnectionLost, error.to_string()),
}
}
fn check_name(name: &str, what: &str) -> Result<()> {
if is_valid_name(name) {
Ok(())
} else {
Err(Error::new(
ErrorCode::InvalidArgument,
format!("'{name}' isn't a {what} name"),
))
}
}
fn check_size(text: &str, what: &str) -> Result<()> {
if text.len() <= MAX_MESSAGE_SIZE {
Ok(())
} else {
Err(Error::new(
ErrorCode::InvalidArgument,
format!("{what} of {} bytes: {MAX_MESSAGE_SIZE} at most", text.len()),
))
}
}
fn file_error(error: io::Error) -> Error {
Error::new(ErrorCode::FileError, format!("the attachment: {error}"))
}
fn unexpected(packet: &Packet) -> Error {
Error::new(
ErrorCode::ProtocolError,
format!("the server answered {}", packet.packet_type().name()),
)
}
+23
View File
@@ -0,0 +1,23 @@
[package]
name = "bakashrot-config"
description = "BakaShrot's server config: topics, retention, replication, roles and what they may do."
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
authors.workspace = true
repository.workspace = true
publish.workspace = true
[dependencies]
# The name rules, the limits.
bakashrot-proto = { path = "../bakashrot-proto" }
# Sections kept in the file's order ([retention]'s first matching pattern
# wins): toml's `preserve_order` reads them in order, IndexMap keeps it.
indexmap = { version = "2.14.2", features = ["serde"] }
serde = { version = "1.0.229", features = ["derive"] }
# Reading only (`display`: values quoted back in errors).
toml = { version = "1.2.1", default-features = false, features = ["std", "parse", "serde", "display", "preserve_order"] }
[lints]
workspace = true
@@ -0,0 +1,67 @@
# A BakaShrot server's config, every key with its default where it has
# one. Read by bakashrot-config, explained in Source/docs/config.md.
#
# Names (topics, nodes, roles): 1-64 of A-Z a-z 0-9 _ . -, not only digits,
# case doesn't matter. Lists of topics or nodes also take patterns: * any
# characters, ? one ("sensors.*"), or "*" for all.
# Names with dots are quoted when they're keys: "sensors.kitchen" = "12h",
# [roles."site.reader"]. Durations: numbers with a unit (s m h d w), like
# "30s" or "1d12h". Relative paths are from this file's folder.
[server]
listen = "0.0.0.0:7000" # required: address and port
# The certificates (bakashrot-cert), required. The node this server is,
# for its peers, is its certificate's name.
ca = "ca.crt"
certificate = "server-1.crt"
key = "server-1.key"
# crl = "ca.crl" # the CA's CRL, watched: optional
database = "bakashrot.sqlite"
# The topics clients push to. Peers may bring others (accept_topics).
topics = ["logs", "sensors.kitchen", "sensors.garage"]
# "full": every push flushed to disk before it's answered, it survives a
# power loss. "normal": about twice the pushes, a power loss loses the last
# second or so. ("off" isn't allowed.)
synchronous = "full"
max_attachment_size = "1G" # bytes, or K M G T (1024-based); 0: none
retention_interval = "1m" # how often old messages are deleted
# How long each topic's messages are kept, from when they were first
# pushed. A topic takes its name's line, else the first pattern matching
# it, else "*"'s; without any, it's kept forever.
[retention]
logs = "30d"
"sensors.*" = "12h"
"*" = "forever"
[replication]
peers = [] # dialed: ["10.0.0.2:7000", "server-2.lan:7000"]
# The only topics replicated at all, whatever the roles say: a filter for
# edge nodes. Without it, no filter; [] replicates nothing.
# replicated_topics = ["logs", "alerts.*"]
retry_delay = "10s"
sync_interval = "5s"
batch_size = 100 # messages per packet, 1-10000
# What certificates with a role may do. A certificate gets everything its
# roles allow; one without any role listed here is refused. Every key is
# optional: an empty list allows nothing.
[roles.sensor]
push_topics = ["sensors.*"] # always as its own node (its name)
[roles.dashboard]
read_topics = ["*"]
query = true # read-only SQL, reads every topic
# Peers are roles too: what's replicated with a server whose certificate
# has this role, whichever end dials.
[roles.peer]
send_topics = ["logs", "sensors.*"]
accept_topics = ["logs"]
send_nodes = ["*"] # the default
accept_nodes = ["*"] # the default
+317
View File
@@ -0,0 +1,317 @@
//! The server's config: a TOML file, read and checked in one go.
//!
//! - [`Server`]: where it listens, its files, its topics, its database.
//! - [`Retention`]: how long each topic's messages are kept.
//! - [`Replication`]: the peers it dials, what it replicates, how often.
//! - [`Role`]: what certificates with a role may do; [`Permissions`]: what
//! a certificate's roles allow together.
//!
//! Who connects is the certificate's (`bakashrot-pki`): its name is its
//! node, its roles are looked up here. Peers too: what's replicated with a
//! peer is its roles'. The file, every key and its default:
//! `Source/docs/config.md`.
//!
//! Every value is checked as serde reads it, so a wrong one is refused with
//! its line.
mod roles;
mod values;
pub use roles::{NameList, Permissions, Role};
use bakashrot_proto::names::{is_valid_name, is_valid_pattern, names_equal, pattern_matches};
use indexmap::IndexMap;
use serde::{Deserialize, Deserializer, de::Error as _};
use std::fmt;
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::time::Duration;
use values::{DURATION_HELP, NAME_HELP, parse_age};
/// What's wrong with a config, in words: where (the file, the line) and why.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Error(String);
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for Error {}
/// A result of this crate.
pub type Result<T> = std::result::Result<T, Error>;
/// A server's config.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
/// `[server]`.
pub server: Server,
/// `[retention]`.
#[serde(default)]
pub retention: Retention,
/// `[replication]`.
#[serde(default)]
pub replication: Replication,
/// `[roles.<name>]`, in the file's order.
#[serde(default, deserialize_with = "roles")]
pub roles: Vec<Role>,
}
/// `[server]`.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Server {
/// The address and port it listens on.
#[serde(deserialize_with = "values::listen")]
pub listen: SocketAddr,
/// The CA's certificate.
pub ca: PathBuf,
/// The server's certificate.
pub certificate: PathBuf,
/// The server's key.
pub key: PathBuf,
/// The CA's CRL, watched; none: nothing revoked.
#[serde(default)]
pub crl: Option<PathBuf>,
/// The SQLite database; `bakashrot.sqlite` by default.
#[serde(default = "defaults::database")]
pub database: PathBuf,
/// The topics clients push to, by name.
#[serde(default, deserialize_with = "values::topic_names")]
pub topics: Vec<String>,
/// How hard a push is made sure to be on disk.
#[serde(default)]
pub synchronous: Synchronous,
/// The biggest attachment taken, in bytes; 0: none. 1G by default.
#[serde(
default = "defaults::max_attachment_size",
deserialize_with = "values::size"
)]
pub max_attachment_size: u64,
/// How often messages past their age are deleted; 1m by default.
#[serde(
default = "defaults::retention_interval",
deserialize_with = "values::duration"
)]
pub retention_interval: Duration,
}
impl Server {
/// Whether `topic` is one of its topics.
pub fn has_topic(&self, topic: &str) -> bool {
self.topics.iter().any(|own| names_equal(own, topic))
}
}
/// How hard the database makes sure a push is on disk before answering it
/// (SQLite's `synchronous`).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
#[serde(try_from = "String")]
pub enum Synchronous {
/// Every commit flushed: an answered push survives a power loss. The
/// default.
#[default]
Full,
/// Flushed about once a second: faster, a power loss loses the last
/// second or so of answered pushes.
Normal,
}
impl TryFrom<String> for Synchronous {
type Error = String;
fn try_from(text: String) -> std::result::Result<Self, String> {
match text.trim().to_ascii_lowercase().as_str() {
"full" => Ok(Synchronous::Full),
"normal" => Ok(Synchronous::Normal),
"off" => Err(
"\"off\" isn't allowed: a power loss could corrupt the database. \
\"full\", or \"normal\" to only risk the last second of messages"
.into(),
),
"extra" => Err("\"extra\" does nothing more than \"full\" here: write \"full\"".into()),
_ => Err(format!("'{text}' isn't \"full\" or \"normal\"")),
}
}
}
/// `[retention]`: how long each topic's messages are kept, from when they
/// were first pushed.
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
#[serde(try_from = "IndexMap<String, toml::Value>")]
pub struct Retention {
/// Names and patterns with their age (none: forever), in the file's
/// order.
lines: Vec<(String, Option<Duration>)>,
}
impl TryFrom<IndexMap<String, toml::Value>> for Retention {
type Error = String;
fn try_from(table: IndexMap<String, toml::Value>) -> std::result::Result<Self, String> {
let mut lines: Vec<(String, Option<Duration>)> = Vec::with_capacity(table.len());
for (key, value) in table {
if !is_valid_pattern(&key) && !is_valid_name(&key) {
return Err(format!(
"'{key}' isn't a topic name or a pattern ({NAME_HELP})"
));
}
if lines.iter().any(|(before, _)| names_equal(before, &key)) {
return Err(format!("'{key}' is given twice"));
}
let age = match &value {
toml::Value::String(text) => parse_age(text),
toml::Value::Table(_) => {
return Err(format!(
"'{key}' is a table: quote names with dots, \"{key}.x\" = \"30d\""
));
}
_ => None,
};
let age = age.ok_or_else(|| {
format!("{key} = {value} isn't an age: {DURATION_HELP}, or \"forever\"")
})?;
lines.push((key, age));
}
Ok(Retention { lines })
}
}
impl Retention {
/// How long `topic`'s messages are kept, `None` for forever: its name's
/// line, else the first pattern matching it, else `*`'s, else forever.
pub fn age(&self, topic: &str) -> Option<Duration> {
let line = |found: fn(&str, &str) -> bool| {
self.lines
.iter()
.find(|(key, _)| key != "*" && found(key, topic))
};
line(names_equal)
.or_else(|| line(|key, topic| is_valid_pattern(key) && pattern_matches(key, topic)))
.or_else(|| self.lines.iter().find(|(key, _)| key == "*"))
.and_then(|(_, age)| *age)
}
}
/// `[replication]`.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Replication {
/// The peers it dials (`host:port`); peers dialing in come by
/// themselves. What's replicated with each is its roles'.
#[serde(deserialize_with = "values::peers")]
pub peers: Vec<String>,
/// The only topics replicated at all, whatever the roles say (an edge
/// node's filter); none: no filter.
pub replicated_topics: Option<NameList>,
/// How long to wait before dialing a peer again; 10s by default.
#[serde(deserialize_with = "values::duration")]
pub retry_delay: Duration,
/// How often a linked peer is sent what it misses; 5s by default.
#[serde(deserialize_with = "values::duration")]
pub sync_interval: Duration,
/// The most messages sent to a peer per packet; 100 by default.
#[serde(deserialize_with = "values::batch_size")]
pub batch_size: u32,
}
impl Default for Replication {
fn default() -> Self {
Replication {
peers: Vec::new(),
replicated_topics: None,
retry_delay: Duration::from_secs(10),
sync_interval: Duration::from_secs(5),
batch_size: 100,
}
}
}
/// `[server]`'s defaults.
mod defaults {
use std::path::PathBuf;
use std::time::Duration;
pub(crate) fn database() -> PathBuf {
"bakashrot.sqlite".into()
}
pub(crate) fn max_attachment_size() -> u64 {
1 << 30
}
pub(crate) fn retention_interval() -> Duration {
Duration::from_secs(60)
}
}
/// `[roles.*]`: each section's name is its role's, none twice.
fn roles<'de, D: Deserializer<'de>>(reader: D) -> std::result::Result<Vec<Role>, D::Error> {
let table = IndexMap::<String, Role>::deserialize(reader)?;
let mut roles: Vec<Role> = Vec::with_capacity(table.len());
for (name, mut role) in table {
if !is_valid_name(&name) {
return Err(D::Error::custom(format!(
"'{name}' isn't a role name ({NAME_HELP})"
)));
}
if let Some(before) = roles.iter().find(|role| names_equal(&role.name, &name)) {
return Err(D::Error::custom(format!(
"'{}' and '{name}' are the same role (case doesn't matter)",
before.name
)));
}
role.name = name;
roles.push(role);
}
Ok(roles)
}
impl Config {
/// Reads the config file at `path`. Relative paths in it are from its
/// folder.
pub fn load(path: &Path) -> Result<Config> {
let in_file = |error: &dyn fmt::Display| Error(format!("{}: {error}", path.display()));
let text = std::fs::read_to_string(path).map_err(|error| in_file(&error))?;
let mut config = Config::parse(&text).map_err(|error| in_file(&error))?;
let folder = path.parent().unwrap_or(Path::new(""));
let server = &mut config.server;
for file in [
&mut server.ca,
&mut server.certificate,
&mut server.key,
&mut server.database,
]
.into_iter()
.chain(server.crl.as_mut())
{
*file = folder.join(&*file);
}
Ok(config)
}
/// Reads a config, paths as they're written.
pub fn parse(text: &str) -> Result<Config> {
toml::from_str(text).map_err(|error| Error(error.to_string().trim_end().to_owned()))
}
/// What a certificate with these roles may do: everything its roles
/// with a section allow. `None` if none has one: it's refused.
pub fn permissions<S: AsRef<str>>(&self, roles: &[S]) -> Option<Permissions> {
let roles: Vec<Role> = self
.roles
.iter()
.filter(|role| {
roles
.iter()
.any(|own| names_equal(own.as_ref(), &role.name))
})
.cloned()
.collect();
(!roles.is_empty()).then(|| Permissions {
roles,
replicated_topics: self.replication.replicated_topics.clone(),
})
}
}
+143
View File
@@ -0,0 +1,143 @@
//! Roles, and what a certificate's roles allow together.
use crate::values::check_names;
use bakashrot_proto::names::{names_equal, pattern_matches};
use serde::Deserialize;
/// Topic or node names and patterns (`sensors.*`, `*` for all), none twice.
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
#[serde(try_from = "Vec<String>")]
pub struct NameList(Vec<String>);
impl TryFrom<Vec<String>> for NameList {
type Error = String;
fn try_from(list: Vec<String>) -> Result<Self, String> {
check_names(&list, true)?;
Ok(NameList(list))
}
}
impl NameList {
/// `*`: every name.
pub fn every() -> NameList {
NameList(vec!["*".to_owned()])
}
/// Whether `name` is in it: one of its names, or matched by one of its
/// patterns (without case).
pub fn matches(&self, name: &str) -> bool {
self.0
.iter()
.any(|entry| names_equal(entry, name) || pattern_matches(entry, name))
}
/// Whether it has nothing: matches nothing.
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Its names and patterns, as written.
pub fn entries(&self) -> &[String] {
&self.0
}
}
/// A `[roles.<name>]` section: what certificates with this role may do.
/// Every key is optional.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Role {
/// The role, as certificates say it (compared without case): the
/// section's name.
#[serde(skip)]
pub name: String,
/// The topics it may push to, always as its own node.
#[serde(default)]
pub push_topics: NameList,
/// The topics it may read the messages of.
#[serde(default)]
pub read_topics: NameList,
/// Whether it may run read-only SQL, which reads every topic.
#[serde(default)]
pub query: bool,
/// Replication: the topics sent to it.
#[serde(default)]
pub send_topics: NameList,
/// Replication: the topics taken from it.
#[serde(default)]
pub accept_topics: NameList,
/// Replication: the nodes whose messages are sent to it (all by default).
#[serde(default = "NameList::every")]
pub send_nodes: NameList,
/// Replication: the nodes whose messages are taken from it (all by
/// default).
#[serde(default = "NameList::every")]
pub accept_nodes: NameList,
}
/// What a certificate may do: everything one of its roles allows, each role
/// on its own (a role's topics go with that role's nodes), replication
/// within the server's `replicated_topics`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Permissions {
pub(crate) roles: Vec<Role>,
pub(crate) replicated_topics: Option<NameList>,
}
impl Permissions {
/// Its roles that this server has a section for.
pub fn roles(&self) -> impl Iterator<Item = &str> {
self.roles.iter().map(|role| role.name.as_str())
}
/// Whether it may push to `topic`.
pub fn can_push(&self, topic: &str) -> bool {
self.roles
.iter()
.any(|role| role.push_topics.matches(topic))
}
/// Whether it may read `topic`'s messages.
pub fn can_read(&self, topic: &str) -> bool {
self.roles
.iter()
.any(|role| role.read_topics.matches(topic))
}
/// Whether it may run read-only SQL.
pub fn can_query(&self) -> bool {
self.roles.iter().any(|role| role.query)
}
/// Whether `node`'s messages in `topic` are sent to it.
pub fn sends(&self, topic: &str, node: &str) -> bool {
self.replicated(topic)
&& self
.roles
.iter()
.any(|role| role.send_topics.matches(topic) && role.send_nodes.matches(node))
}
/// Whether `node`'s messages in `topic` are taken from it.
pub fn accepts(&self, topic: &str, node: &str) -> bool {
self.replicated(topic)
&& self
.roles
.iter()
.any(|role| role.accept_topics.matches(topic) && role.accept_nodes.matches(node))
}
/// Whether it replicates at all: a peer.
pub fn replicates(&self) -> bool {
self.roles
.iter()
.any(|role| !role.send_topics.is_empty() || !role.accept_topics.is_empty())
}
fn replicated(&self, topic: &str) -> bool {
self.replicated_topics
.as_ref()
.is_none_or(|topics| topics.matches(topic))
}
}
@@ -0,0 +1,253 @@
//! The values that need more than a type: durations, ages, sizes,
//! addresses, names.
use bakashrot_proto::limits::{MAX_ATTACHMENT_SIZE, MAX_MESSAGES_PER_PACKET};
use bakashrot_proto::names::{is_valid_name, is_valid_name_or_pattern, names_equal};
use serde::de::Error as _;
use serde::{Deserialize, Deserializer};
use std::net::{Ipv6Addr, SocketAddr};
use std::time::Duration;
/// What a duration looks like, for errors.
pub(crate) const DURATION_HELP: &str = "numbers with a unit (s m h d w), like 30s or 1d12h";
/// What a name looks like, for errors.
pub(crate) const NAME_HELP: &str = "1-64 of A-Z a-z 0-9 _ . -, not only digits; patterns: * and ?";
/// A duration: numbers with a unit, added up (`1d12h`). Units `s m h d w`,
/// without case. More than 0.
pub(crate) fn parse_duration(text: &str) -> Option<Duration> {
let mut seconds: u64 = 0;
let mut number: Option<u64> = None;
for c in text.trim().chars() {
if let Some(digit) = c.to_digit(10) {
number = Some(
number
.unwrap_or(0)
.checked_mul(10)?
.checked_add(digit.into())?,
);
continue;
}
let unit: u64 = match c.to_ascii_lowercase() {
's' => 1,
'm' => 60,
'h' => 3600,
'd' => 86_400,
'w' => 604_800,
_ => return None,
};
seconds = seconds.checked_add(number.take()?.checked_mul(unit)?)?;
}
if number.is_some() || seconds == 0 {
return None;
}
Some(Duration::from_secs(seconds))
}
/// A retention age: a duration, or `forever` (`Some(None)`).
pub(crate) fn parse_age(text: &str) -> Option<Option<Duration>> {
if text.trim().eq_ignore_ascii_case("forever") {
return Some(None);
}
parse_duration(text).map(Some)
}
/// A size: bytes (a number), or text with K, M, G or T (1024-based, without
/// case), up to `MAX_ATTACHMENT_SIZE`. 0 is a size.
pub(crate) fn parse_size(value: &toml::Value) -> Option<u64> {
let size = match value {
toml::Value::Integer(bytes) => u64::try_from(*bytes).ok()?,
toml::Value::String(text) => {
let text = text.trim();
let (digits, unit) = match text.char_indices().last()? {
(at, c) if c.is_ascii_alphabetic() => (&text[..at], c.to_ascii_uppercase()),
_ => (text, 'B'),
};
let shift = match unit {
'B' => 0,
'K' => 10,
'M' => 20,
'G' => 30,
'T' => 40,
_ => return None,
};
if digits.is_empty() || !digits.bytes().all(|c| c.is_ascii_digit()) {
return None;
}
digits.parse::<u64>().ok()?.checked_mul(1 << shift)?
}
_ => return None,
};
(size <= MAX_ATTACHMENT_SIZE).then_some(size)
}
/// Whether `text` is a host and a port: `10.0.0.2:7000`,
/// `server-2.lan:7000`, `[fd00::2]:7000`. The port isn't 0.
pub(crate) fn is_peer_address(text: &str) -> bool {
let Some((host, port)) = text.rsplit_once(':') else {
return false;
};
let port = port.parse::<u16>().is_ok_and(|port| port != 0);
let host = match host.strip_prefix('[').and_then(|h| h.strip_suffix(']')) {
Some(v6) => v6.parse::<Ipv6Addr>().is_ok(),
None => {
!host.is_empty()
&& host
.bytes()
.all(|c| c.is_ascii_alphanumeric() || c == b'.' || c == b'-')
}
};
port && host
}
// As serde reads them (`deserialize_with`): a value that's wrong fails
// there, and toml says on which line.
/// A duration, more than 0.
pub(crate) fn duration<'de, D: Deserializer<'de>>(reader: D) -> Result<Duration, D::Error> {
let text = String::deserialize(reader)?;
parse_duration(&text)
.ok_or_else(|| D::Error::custom(format!("'{text}' isn't a duration: {DURATION_HELP}")))
}
/// A size up to `MAX_ATTACHMENT_SIZE`.
pub(crate) fn size<'de, D: Deserializer<'de>>(reader: D) -> Result<u64, D::Error> {
let value = toml::Value::deserialize(reader)?;
parse_size(&value).ok_or_else(|| {
D::Error::custom(format!(
"{value} isn't a size up to 1T: bytes, or a number with K, M, G or T, like \"500M\" \
(0: no attachments)"
))
})
}
/// An address and a port to listen on.
pub(crate) fn listen<'de, D: Deserializer<'de>>(reader: D) -> Result<SocketAddr, D::Error> {
let text = String::deserialize(reader)?;
text.parse().map_err(|_| {
D::Error::custom(format!(
"'{text}' isn't an address and a port, like \"0.0.0.0:7000\""
))
})
}
/// Peer addresses, none twice.
pub(crate) fn peers<'de, D: Deserializer<'de>>(reader: D) -> Result<Vec<String>, D::Error> {
let peers = Vec::<String>::deserialize(reader)?;
for (at, peer) in peers.iter().enumerate() {
if !is_peer_address(peer) {
return Err(D::Error::custom(format!(
"'{peer}' isn't a host and a port, like \"10.0.0.2:7000\" or \
\"server-2.lan:7000\""
)));
}
if peers[..at].contains(peer) {
return Err(D::Error::custom(format!("'{peer}' is given twice")));
}
}
Ok(peers)
}
/// A batch size, 1 to `MAX_MESSAGES_PER_PACKET`.
pub(crate) fn batch_size<'de, D: Deserializer<'de>>(reader: D) -> Result<u32, D::Error> {
let size = u32::deserialize(reader)?;
if !(1..=MAX_MESSAGES_PER_PACKET).contains(&size) {
return Err(D::Error::custom(format!(
"the batch size must be 1 to {MAX_MESSAGES_PER_PACKET}"
)));
}
Ok(size)
}
/// Topic names (no patterns), none twice.
pub(crate) fn topic_names<'de, D: Deserializer<'de>>(reader: D) -> Result<Vec<String>, D::Error> {
let names = Vec::<String>::deserialize(reader)?;
check_names(&names, false).map_err(D::Error::custom)?;
Ok(names)
}
/// Checks a list of names (`patterns`: or patterns), none twice.
pub(crate) fn check_names(list: &[String], patterns: bool) -> Result<(), String> {
for (at, entry) in list.iter().enumerate() {
let (valid, what) = if patterns {
(is_valid_name_or_pattern(entry), "a name or a pattern")
} else {
(is_valid_name(entry), "a name")
};
if !valid {
return Err(format!("'{entry}' isn't {what} ({NAME_HELP})"));
}
if list[..at].iter().any(|before| names_equal(before, entry)) {
return Err(format!("'{entry}' is given twice"));
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn durations() {
let s = Duration::from_secs;
assert_eq!(parse_duration("30s"), Some(s(30)));
assert_eq!(parse_duration("1d12h"), Some(s(129_600)));
assert_eq!(parse_duration(" 2W "), Some(s(1_209_600)));
assert_eq!(parse_duration("1m30s"), Some(s(90)));
for bad in [
"",
"30",
"s",
"1x",
"0s",
"1h 30m",
"-1s",
"99999999999999999999w",
] {
assert_eq!(parse_duration(bad), None, "{bad}");
}
assert_eq!(parse_age("Forever"), Some(None));
assert_eq!(parse_age("30d"), Some(Some(s(2_592_000))));
assert_eq!(parse_age("never"), None);
}
#[test]
fn sizes() {
let text = |t: &str| parse_size(&toml::Value::String(t.into()));
assert_eq!(text("0"), Some(0));
assert_eq!(text("500"), Some(500));
assert_eq!(text("500k"), Some(500 << 10));
assert_eq!(text("1G"), Some(1 << 30));
assert_eq!(text("1T"), Some(1 << 40));
assert_eq!(parse_size(&toml::Value::Integer(1024)), Some(1024));
for bad in ["", "G", "2T", "1.5G", "1GB", "-1", "1 G"] {
assert_eq!(text(bad), None, "{bad}");
}
assert_eq!(parse_size(&toml::Value::Integer(-1)), None);
assert_eq!(parse_size(&toml::Value::Boolean(true)), None);
}
#[test]
fn peer_addresses() {
for good in [
"10.0.0.2:7000",
"server-2.lan:7000",
"[fd00::2]:7000",
"localhost:1",
] {
assert!(is_peer_address(good), "{good}");
}
for bad in [
"10.0.0.2",
"10.0.0.2:0",
":7000",
"fd00::2:7000",
"a b:7000",
"x:70000",
] {
assert!(!is_peer_address(bad), "{bad}");
}
}
}
@@ -0,0 +1,372 @@
//! Configs taken and refused, and what they mean.
use bakashrot_config::{Config, Synchronous};
use std::path::Path;
use std::time::Duration;
const EXAMPLE: &str = include_str!("../example.toml");
/// The least a config has.
const MINIMAL: &str = r#"
[server]
listen = "127.0.0.1:7000"
ca = "ca.crt"
certificate = "server.crt"
key = "server.key"
"#;
fn with(extra: &str) -> String {
format!("{MINIMAL}{extra}")
}
/// The error of a config that must be refused.
fn refused(text: &str) -> String {
match Config::parse(text) {
Ok(config) => panic!("taken: {config:?}\n{text}"),
Err(error) => error.to_string(),
}
}
fn days(days: u64) -> Option<Duration> {
Some(Duration::from_secs(days * 86_400))
}
#[test]
fn the_example() {
let config = Config::parse(EXAMPLE).unwrap();
let server = &config.server;
assert_eq!(server.listen, "0.0.0.0:7000".parse().unwrap());
assert_eq!(server.crl, None);
assert_eq!(server.topics.len(), 3);
assert!(server.has_topic("Sensors.Kitchen"));
assert!(!server.has_topic("sensors"));
assert_eq!(server.synchronous, Synchronous::Full);
assert_eq!(server.max_attachment_size, 1 << 30);
assert_eq!(config.replication.peers, Vec::<String>::new());
assert_eq!(config.retention.age("logs"), days(30));
assert_eq!(
config.retention.age("sensors.kitchen"),
Some(Duration::from_secs(43_200))
);
assert_eq!(config.retention.age("other"), None);
let names: Vec<&str> = config.roles.iter().map(|role| role.name.as_str()).collect();
assert_eq!(names, ["sensor", "dashboard", "peer"]);
}
#[test]
fn defaults() {
let config = Config::parse(MINIMAL).unwrap();
let server = &config.server;
assert_eq!(server.database, Path::new("bakashrot.sqlite"));
assert!(server.topics.is_empty());
assert_eq!(server.synchronous, Synchronous::Full);
assert_eq!(server.max_attachment_size, 1 << 30);
assert_eq!(server.retention_interval, Duration::from_secs(60));
assert_eq!(config.retention.age("logs"), None);
assert_eq!(config.replication.retry_delay, Duration::from_secs(10));
assert_eq!(config.replication.sync_interval, Duration::from_secs(5));
assert_eq!(config.replication.batch_size, 100);
assert_eq!(config.replication.replicated_topics, None);
assert!(config.roles.is_empty());
assert!(config.permissions(&["anything"]).is_none());
}
#[test]
fn settings() {
let config = Config::parse(&with(
r#"crl = "ca.crl"
database = "data/messages.sqlite"
synchronous = "NORMAL"
max_attachment_size = 0
retention_interval = "1h30m"
[replication]
peers = ["10.0.0.2:7000", "server-3.lan:7001", "[fd00::4]:7000"]
retry_delay = "1m"
sync_interval = "2s"
batch_size = 10000
replicated_topics = ["logs"]
"#,
))
.unwrap();
assert_eq!(config.server.crl.as_deref(), Some(Path::new("ca.crl")));
assert_eq!(config.server.synchronous, Synchronous::Normal);
assert_eq!(config.server.max_attachment_size, 0);
assert_eq!(config.server.retention_interval, Duration::from_secs(5400));
assert_eq!(config.replication.peers.len(), 3);
assert_eq!(config.replication.retry_delay, Duration::from_secs(60));
assert_eq!(config.replication.batch_size, 10_000);
}
#[test]
fn retention_order() {
let config = Config::parse(&with(
r#"
[retention]
"*" = "365d"
"sensors.?????" = "1h"
"sensors.*" = "12h"
"sensors.k*" = "2h"
"Sensors.Kitchen" = "forever"
logs = "30d"
"#,
))
.unwrap();
let age = |topic| config.retention.age(topic);
let hours = |hours: u64| Some(Duration::from_secs(hours * 3600));
// Its name's line first, wherever it is.
assert_eq!(age("sensors.kitchen"), None);
assert_eq!(age("LOGS"), days(30));
// Else the first pattern in the file's order (sorted, "sensors.*"
// would come first), not the closest.
assert_eq!(age("sensors.alpha"), hours(1));
assert_eq!(age("sensors.kettle"), hours(12));
// "*" last, though it's first.
assert_eq!(age("other"), days(365));
}
#[test]
fn permissions() {
let config = Config::parse(&with(
r#"
[roles.sensor]
push_topics = ["sensors.*"]
[roles.Reader]
read_topics = ["logs", "sensors.kitchen"]
[roles.admin]
query = true
[roles.peer]
send_topics = ["logs"]
send_nodes = ["kitchen-*"]
[roles.backup]
send_topics = ["sensors.*"]
accept_topics = ["*"]
accept_nodes = ["garage"]
[roles.idle]
"#,
))
.unwrap();
// None of its roles here: refused. Roles compare without case.
assert!(config.permissions(&["unknown"]).is_none());
assert!(config.permissions::<&str>(&[]).is_none());
let idle = config.permissions(&["IDLE", "unknown"]).unwrap();
assert_eq!(idle.roles().collect::<Vec<_>>(), ["idle"]);
assert!(!idle.can_push("logs") && !idle.can_read("logs") && !idle.can_query());
assert!(!idle.replicates());
// Everything its roles allow.
let both = config.permissions(&["sensor", "reader"]).unwrap();
assert!(both.can_push("sensors.garage"));
assert!(!both.can_push("logs"));
assert!(both.can_read("Logs"));
assert!(!both.can_read("sensors.garage"));
assert!(!both.can_query());
assert!(config.permissions(&["admin"]).unwrap().can_query());
// Replication: each role's topics with that role's nodes, not mixed.
let peer = config.permissions(&["peer", "backup"]).unwrap();
assert!(peer.replicates());
assert!(peer.sends("logs", "kitchen-1"));
assert!(!peer.sends("logs", "garage"));
assert!(peer.sends("sensors.a", "garage"));
assert!(!peer.sends("other", "kitchen-1"));
assert!(peer.accepts("anything", "garage"));
assert!(!peer.accepts("logs", "kitchen-1"));
// A role without the topics replicates nothing, whatever its nodes.
let only_peer = config.permissions(&["peer"]).unwrap();
assert!(!only_peer.accepts("logs", "kitchen-1"));
}
#[test]
fn replicated_topics_filter_the_roles() {
let config = Config::parse(&with(
r#"
[replication]
replicated_topics = ["logs", "alerts.*"]
[roles.peer]
send_topics = ["*"]
accept_topics = ["*"]
[roles.sensor]
push_topics = ["*"]
"#,
))
.unwrap();
let peer = config.permissions(&["peer", "sensor"]).unwrap();
assert!(peer.sends("logs", "kitchen") && peer.accepts("Logs", "kitchen"));
assert!(peer.sends("alerts.fire", "kitchen"));
assert!(!peer.sends("sensors.a", "kitchen") && !peer.accepts("sensors.a", "kitchen"));
assert!(peer.replicates());
// Only replication: pushing isn't filtered.
assert!(peer.can_push("sensors.a"));
// Empty: nothing replicated.
let none = Config::parse(&with(
"[replication]\nreplicated_topics = []\n[roles.peer]\nsend_topics = [\"*\"]\n",
))
.unwrap();
assert!(
!none
.permissions(&["peer"])
.unwrap()
.sends("logs", "kitchen")
);
assert!(refused(&with("[replication]\nreplicated_topics = [\"a b\"]\n")).contains("'a b'"));
}
#[test]
fn files_are_from_the_configs_folder() {
let folder = std::env::temp_dir().join(format!("bakashrot-config-{}", std::process::id()));
std::fs::create_dir_all(&folder).unwrap();
let path = folder.join("server.toml");
std::fs::write(&path, with("crl = \"revoked/ca.crl\"\n")).unwrap();
let config = Config::load(&path).unwrap();
assert_eq!(config.server.ca, folder.join("ca.crt"));
assert_eq!(config.server.crl, Some(folder.join("revoked/ca.crl")));
assert_eq!(config.server.database, folder.join("bakashrot.sqlite"));
std::fs::write(&path, "[server]\n").unwrap();
let error = Config::load(&path).unwrap_err().to_string();
assert!(error.starts_with(&path.display().to_string()), "{error}");
assert!(error.contains("listen"), "{error}");
std::fs::remove_dir_all(&folder).unwrap();
let error = Config::load(&folder.join("missing.toml")).unwrap_err();
assert!(error.to_string().contains("missing.toml"), "{error}");
}
#[test]
fn refusals() {
let cases: &[(&str, &str)] = &[
// Not TOML, or another shape: the line is said.
("[server", "line 1"),
("", "missing field `server`"),
(&with("lsiten = \"x\"\n"), "unknown field `lsiten`"),
(&with("[other]\n"), "unknown field `other`"),
// The old ini's keys.
(&with("PrivateKey = \"x\"\n"), "unknown field `PrivateKey`"),
(
&with("[roles.sensor]\nAllowWrite = 1\n"),
"unknown field `AllowWrite`",
),
(
&with("[roles.sensor]\ndefault_topic = \"x\"\n"),
"unknown field `default_topic`",
),
// [server]
(
&MINIMAL.replace("127.0.0.1:7000", "127.0.0.1"),
"'127.0.0.1' isn't an address and a port",
),
(&with("topics = [\"a b\"]\n"), "'a b' isn't a name ("),
(
&with("topics = [\"sensors.*\"]\n"),
"'sensors.*' isn't a name (",
),
(&with("topics = [\"12\"]\n"), "'12' isn't a name"),
(
&with("topics = [\"logs\", \"Logs\"]\n"),
"'Logs' is given twice",
),
(
&with("synchronous = \"OFF\"\n"),
"isn't allowed: a power loss",
),
(&with("synchronous = \"extra\"\n"), "write \"full\""),
(
&with("synchronous = \"fast\"\n"),
"'fast' isn't \"full\" or \"normal\"",
),
(
&with("max_attachment_size = \"2T\"\n"),
"isn't a size up to 1T",
),
(&with("max_attachment_size = -1\n"), "isn't a size up to 1T"),
(
&with("max_attachment_size = \"1GB\"\n"),
"isn't a size up to 1T",
),
(&with("retention_interval = \"3600\"\n"), "isn't a duration"),
(&with("retention_interval = 60\n"), "invalid type: integer"),
// Gone with protocol 7: no upload waits for its message.
(
&with("upload_timeout = \"1h\"\n"),
"unknown field `upload_timeout`",
),
(
&with("retention_interval = \"0s\"\n"),
"'0s' isn't a duration",
),
// [retention]
(
&with("[retention]\nlogs = \"30\"\n"),
"logs = \"30\" isn't an age",
),
(&with("[retention]\nlogs = 30\n"), "isn't an age"),
(
&with("[retention]\n\"a b\" = \"1d\"\n"),
"'a b' isn't a topic name or a pattern",
),
(
&with("[retention]\nlogs = \"1d\"\nLOGS = \"2d\"\n"),
"'LOGS' is given twice",
),
(
&with("[retention]\nsensors.kitchen = \"1d\"\n"),
"quote names with dots",
),
// [replication]
(
&with("[replication]\npeers = [\"10.0.0.2\"]\n"),
"isn't a host and a port",
),
(
&with("[replication]\npeers = [\"a:1\", \"a:1\"]\n"),
"'a:1' is given twice",
),
(
&with("[replication]\nbatch_size = 0\n"),
"batch size must be 1 to 10000",
),
(
&with("[replication]\nbatch_size = 10001\n"),
"batch size must be 1 to 10000",
),
(
&with("[replication]\nsync_interval = \"soon\"\n"),
"'soon' isn't a duration",
),
// [roles]
(&with("[roles.\"a b\"]\n"), "'a b' isn't a role name"),
(
&with("[roles.peer]\n[roles.Peer]\n"),
"'peer' and 'Peer' are the same role",
),
(
&with("[roles.r]\npush_topics = [\"a b\"]\n"),
"'a b' isn't a name or a pattern",
),
(
&with("[roles.r]\naccept_nodes = [\"x\", \"X\"]\n"),
"'X' is given twice",
),
(&with("[roles.r]\nquery = 1\n"), "invalid type: integer"),
(&with("[roles.site.reader]\n"), "unknown field `reader`"),
];
for (text, expected) in cases {
let error = refused(text);
assert!(
error.contains(expected),
"expected {expected:?} in:\n{error}"
);
// Every refusal says where.
assert!(error.contains("line "), "no line in:\n{error}");
}
}
+25
View File
@@ -0,0 +1,25 @@
[package]
name = "bakashrot-pki"
description = "BakaShrot's certificates: issuing them and CRLs, reading identities, the TLS setup of servers and clients."
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
authors.workspace = true
repository.workspace = true
publish.workspace = true
[dependencies]
bakashrot-proto = { path = "../bakashrot-proto" }
# Issuing certificates and CRLs, P-384 keys through aws-lc.
rcgen = { version = "0.14.10", default-features = false, features = ["x509-parser", "pem", "aws_lc_rs"] }
# TLS 1.3 only, through aws-lc (the one with ML-KEM).
rustls = { version = "0.23.46", default-features = false, features = ["aws_lc_rs", "std"] }
time = "0.3.55"
# Reading certificates and CRLs, a CRL's signature checked through aws-lc.
x509-parser = { version = "0.18.1", features = ["verify-aws"] }
# The identity extension's DER (rcgen's own DER library).
yasna = "0.6.0"
[lints]
workspace = true
+238
View File
@@ -0,0 +1,238 @@
//! A CA: issuing client and server certificates, and CRLs.
//!
//! Every key is ECDSA P-384, every signature SHA-384. A server certificate
//! is for servers and clients both (servers are their peers' clients), and
//! has the DNS name [`SERVER_NAME`] its clients ask for.
use crate::{Error, IDENTITY_OID, Identity, Result, SERVER_NAME, parse_certificate, pem_der};
use rcgen::{
BasicConstraints, CertificateParams, CertificateRevocationListParams, CustomExtension,
DistinguishedName, DnType, ExtendedKeyUsagePurpose, IsCa, Issuer, KeyIdMethod, KeyPair,
KeyUsagePurpose, PKCS_ECDSA_P384_SHA384, PublicKeyData, RevokedCertParams, SanType,
SerialNumber,
};
use time::{Duration, OffsetDateTime};
use x509_parser::x509::X509Name;
/// What a certificate is for.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Usage {
/// A client's: it connects to servers.
Client,
/// A server's: clients and peers connect to it, and it connects to its
/// peers.
Server,
}
/// A certificate and its private key, PEM.
#[derive(Debug, Clone)]
pub struct Issued {
/// The certificate: public, goes wherever it's needed.
pub certificate: String,
/// Its private key: stays with its owner.
pub key: String,
}
/// A CA, loaded from its certificate and its key.
pub struct Ca {
certificate: Vec<u8>,
issuer: Issuer<'static, KeyPair>,
}
fn rcgen_error(what: &str) -> impl Fn(rcgen::Error) -> Error + '_ {
move |error| Error::new(format!("{what}: {error}"))
}
fn new_key() -> Result<KeyPair> {
KeyPair::generate_for(&PKCS_ECDSA_P384_SHA384).map_err(rcgen_error("making a key"))
}
/// Parameters valid from now on, for `days`, with `name` as the CN.
fn params(name: &str, days: u32) -> CertificateParams {
let mut params = CertificateParams::default();
let mut subject = DistinguishedName::new();
subject.push(DnType::CommonName, name);
params.distinguished_name = subject;
let now = OffsetDateTime::now_utc();
params.not_before = now;
params.not_after = now + Duration::days(days.into());
params
}
impl Ca {
/// Makes a new CA named `name` (its CN), valid `days`: its certificate
/// and its key. Keep the key off the servers: whoever has it can make
/// any identity.
pub fn create(name: &str, days: u32) -> Result<Issued> {
if name.trim().is_empty() {
return Err(Error::new("a CA needs a name"));
}
let key = new_key()?;
let mut params = params(name, days);
params.is_ca = IsCa::Ca(BasicConstraints::Constrained(0));
params.key_usages = vec![
KeyUsagePurpose::KeyCertSign,
KeyUsagePurpose::CrlSign,
KeyUsagePurpose::DigitalSignature,
];
let certificate = params
.self_signed(&key)
.map_err(rcgen_error("making the CA"))?;
Ok(Issued {
certificate: certificate.pem(),
key: key.serialize_pem(),
})
}
/// Loads a CA from its certificate and its key (PEM). Fails if the
/// certificate isn't a CA's, or the key isn't its.
pub fn load(certificate: &str, key: &str) -> Result<Ca> {
let key = KeyPair::from_pem(key).map_err(rcgen_error("the CA's key"))?;
let der = pem_der(certificate, "CERTIFICATE")?;
{
let parsed = parse_certificate(&der)?;
if !parsed.is_ca() {
return Err(Error::new("the certificate isn't a CA's"));
}
if parsed.public_key().raw != key.subject_public_key_info() {
return Err(Error::new("the key isn't the CA certificate's"));
}
}
let issuer = Issuer::from_ca_cert_pem(certificate, key)
.map_err(rcgen_error("the CA's certificate"))?;
Ok(Ca {
certificate: der,
issuer,
})
}
/// Issues a certificate for `identity`, valid `days`: its certificate and
/// a new key.
pub fn issue(&self, identity: &Identity, usage: Usage, days: u32) -> Result<Issued> {
let key = new_key()?;
let mut params = params(&identity.name, days);
params.key_usages = vec![KeyUsagePurpose::DigitalSignature];
params.use_authority_key_identifier_extension = true;
params.custom_extensions = vec![CustomExtension::from_oid_content(
IDENTITY_OID,
identity.to_der(),
)];
match usage {
Usage::Client => {
params.extended_key_usages = vec![ExtendedKeyUsagePurpose::ClientAuth];
}
Usage::Server => {
params.extended_key_usages = vec![
ExtendedKeyUsagePurpose::ServerAuth,
ExtendedKeyUsagePurpose::ClientAuth,
];
let name = SERVER_NAME
.try_into()
.map_err(rcgen_error("the server name"))?;
params.subject_alt_names = vec![SanType::DnsName(name)];
}
}
let certificate = params
.signed_by(&key, &self.issuer)
.map_err(rcgen_error("issuing the certificate"))?;
Ok(Issued {
certificate: certificate.pem(),
key: key.serialize_pem(),
})
}
/// Whether this CA issued `certificate` (PEM): its signature checks out
/// with the CA's key.
pub fn issued(&self, certificate: &str) -> Result<bool> {
let ca = parse_certificate(&self.certificate)?;
let der = pem_der(certificate, "CERTIFICATE")?;
let certificate = parse_certificate(&der)?;
Ok(certificate.verify_signature(Some(ca.public_key())).is_ok())
}
/// A CRL revoking the certificates of these serial numbers (as
/// [`Summary::serial`] gives them), PEM. It says to expect the next one
/// within `days`; servers don't hold it against an older one.
pub fn revocation_list(&self, serials: &[Vec<u8>], days: u32) -> Result<String> {
let now = OffsetDateTime::now_utc();
let params = CertificateRevocationListParams {
this_update: now,
next_update: now + Duration::days(days.max(1).into()),
crl_number: SerialNumber::from(now.unix_timestamp().max(1) as u64),
issuing_distribution_point: None,
revoked_certs: serials
.iter()
.map(|serial| RevokedCertParams {
serial_number: SerialNumber::from_slice(serial),
revocation_time: now,
reason_code: None,
invalidity_date: None,
})
.collect(),
key_identifier_method: KeyIdMethod::Sha256,
};
let list = params
.signed_by(&self.issuer)
.map_err(rcgen_error("making the CRL"))?;
list.pem().map_err(rcgen_error("writing the CRL"))
}
}
/// What a certificate says, for people (and the tool).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Summary {
/// Its subject's CN.
pub subject: String,
/// Its issuer's CN.
pub issuer: String,
/// Its serial number, as it's written (what a CRL lists).
pub serial: Vec<u8>,
/// Valid from, as written in it.
pub not_before: String,
/// Valid until, as written in it.
pub not_after: String,
/// Whether it's a CA's.
pub is_ca: bool,
/// What it's for, if it's one of ours.
pub usage: Option<Usage>,
/// Who it is, if it has an identity.
pub identity: Option<Identity>,
}
impl Summary {
/// The serial number in hex.
pub fn serial_hex(&self) -> String {
self.serial
.iter()
.map(|byte| format!("{byte:02x}"))
.collect()
}
}
/// What a certificate (PEM) says.
pub fn summarize(certificate: &str) -> Result<Summary> {
let der = pem_der(certificate, "CERTIFICATE")?;
let parsed = parse_certificate(&der)?;
let common_name = |name: &X509Name<'_>| {
name.iter_common_name()
.next()
.and_then(|cn| cn.as_str().ok())
.unwrap_or("")
.to_owned()
};
let usage = match parsed.extended_key_usage() {
Ok(Some(eku)) if eku.value.server_auth => Some(Usage::Server),
Ok(Some(eku)) if eku.value.client_auth => Some(Usage::Client),
_ => None,
};
Ok(Summary {
subject: common_name(parsed.subject()),
issuer: common_name(parsed.issuer()),
serial: parsed.raw_serial().to_vec(),
not_before: parsed.validity().not_before.to_string(),
not_after: parsed.validity().not_after.to_string(),
is_ca: parsed.is_ca(),
usage,
identity: Identity::from_certificate(&der).ok(),
})
}
+147
View File
@@ -0,0 +1,147 @@
//! The identity extension: who a certificate is.
//!
//! ```text
//! BakaShrotIdentity ::= SEQUENCE {
//! version INTEGER, -- 1
//! name UTF8String, -- the node: "kitchen"
//! roles SEQUENCE OF UTF8String -- free: "sensor", "peer"...
//! }
//! ```
//!
//! Non-critical (rustls refuses critical extensions it doesn't know), read
//! by BakaShrot only. Names and roles follow the name rules
//! (`bakashrot_proto::names`).
use crate::{Error, IDENTITY_OID, Result, parse_certificate};
use bakashrot_proto::names::is_valid_name;
use x509_parser::oid_registry::Oid;
/// The version written, the only one read.
const VERSION: u32 = 1;
/// The most roles a certificate may have.
pub const MAX_ROLES: usize = 64;
/// Who a certificate is: a node, and its roles (their meaning is the
/// server's config's).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Identity {
/// The node's name.
pub name: String,
/// Its roles, in order.
pub roles: Vec<String>,
}
impl Identity {
/// An identity, checked: a name, roles that are names too.
pub fn new(name: &str, roles: &[&str]) -> Result<Identity> {
let identity = Identity {
name: name.to_owned(),
roles: roles.iter().map(|role| (*role).to_owned()).collect(),
};
identity.check()?;
Ok(identity)
}
/// Whether it has `role` (roles compare without case, like names).
pub fn has_role(&self, role: &str) -> bool {
self.roles.iter().any(|own| own.eq_ignore_ascii_case(role))
}
fn check(&self) -> Result<()> {
if !is_valid_name(&self.name) {
return Err(Error::new(format!("'{}' isn't a valid name", self.name)));
}
if self.roles.len() > MAX_ROLES {
return Err(Error::new(format!("more than {MAX_ROLES} roles")));
}
if let Some(role) = self.roles.iter().find(|role| !is_valid_name(role)) {
return Err(Error::new(format!("'{role}' isn't a valid role")));
}
Ok(())
}
/// The extension's value, DER.
pub(crate) fn to_der(&self) -> Vec<u8> {
yasna::construct_der(|writer| {
writer.write_sequence(|writer| {
writer.next().write_u32(VERSION);
writer.next().write_utf8_string(&self.name);
writer.next().write_sequence_of(|writer| {
for role in &self.roles {
writer.next().write_utf8_string(role);
}
});
});
})
}
/// Reads the extension's value, DER.
pub(crate) fn from_der(der: &[u8]) -> Result<Identity> {
let (version, name, roles) = yasna::parse_der(der, |reader| {
reader.read_sequence(|reader| {
let version = reader.next().read_u32()?;
let name = reader.next().read_utf8string()?;
let roles = reader
.next()
.collect_sequence_of(|reader| reader.read_utf8string())?;
Ok((version, name, roles))
})
})
.map_err(|error| Error::new(format!("the identity extension isn't readable: {error}")))?;
if version != VERSION {
return Err(Error::new(format!(
"identity version {version}, this one reads {VERSION}"
)));
}
let identity = Identity { name, roles };
identity.check()?;
Ok(identity)
}
/// The identity of a certificate (DER), the one the TLS connection
/// presented once verified.
pub fn from_certificate(der: &[u8]) -> Result<Identity> {
let certificate = parse_certificate(der)?;
let oid = Oid::from(IDENTITY_OID).map_err(|_| Error::new("the identity OID is invalid"))?;
let extension = certificate
.get_extension_unique(&oid)
.map_err(|error| Error::new(format!("the identity extension: {error}")))?
.ok_or_else(|| Error::new("the certificate has no BakaShrot identity"))?;
Identity::from_der(extension.value)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_trip() {
let identity = Identity::new("kitchen", &["sensor", "Reader"]).unwrap();
assert_eq!(Identity::from_der(&identity.to_der()), Ok(identity.clone()));
assert!(identity.has_role("reader"));
assert!(!identity.has_role("peer"));
let alone = Identity::new("kitchen", &[]).unwrap();
assert_eq!(Identity::from_der(&alone.to_der()), Ok(alone));
}
#[test]
fn refused() {
assert!(Identity::new("12", &[]).is_err());
assert!(Identity::new("a b", &[]).is_err());
assert!(Identity::new("kitchen", &["bad role"]).is_err());
assert!(Identity::new("kitchen", &["r"; MAX_ROLES + 1]).is_err());
assert!(Identity::from_der(b"garbage").is_err());
// Another version.
let other = yasna::construct_der(|writer| {
writer.write_sequence(|writer| {
writer.next().write_u32(2);
writer.next().write_utf8_string("kitchen");
writer.next().write_sequence_of(|_| {});
});
});
assert!(Identity::from_der(&other).is_err());
}
}
+87
View File
@@ -0,0 +1,87 @@
//! BakaShrot's certificates, and the TLS they're used with.
//!
//! - [`Identity`]: who a certificate is (a node's name, its roles), in an
//! extension of BakaShrot's own.
//! - [`Ca`]: a CA issuing client and server certificates, and CRLs.
//! - [`Revocations`]: the certificates a CRL revokes, for servers to check
//! (and reload when the CRL file changes).
//! - [`tls`]: the server's and the client's rustls configurations, at the
//! strongest settings rustls has.
//!
//! Everything is PEM text in and out, as files hold it. The profile and the
//! reasons behind it: `Source/docs/certificates.md`.
mod ca;
mod identity;
mod revocation;
pub mod tls;
pub use ca::{Ca, Issued, Summary, Usage, summarize};
pub use identity::Identity;
pub use revocation::{Revocations, SharedRevocations, serial};
use std::fmt;
use x509_parser::certificate::X509Certificate;
/// The identity extension's OID.
///
/// **A placeholder** ([`IDENTITY_OID_IS_PLACEHOLDER`]): under PEN 32473,
/// which RFC 5612 reserves for documentation. Replace it with one under
/// NibblePoker's own PEN once IANA gave it (`Source/docs/oid.md`), before
/// issuing certificates for real: certificates made with this one stop
/// being read once it changes.
pub const IDENTITY_OID: &[u64] = &[1, 3, 6, 1, 4, 1, 32473, 1, 1];
/// Whether [`IDENTITY_OID`] is still the placeholder: `bakashrot-cert`
/// warns when it makes a CA or a certificate then. Set it to `false` with
/// the real OID.
pub const IDENTITY_OID_IS_PLACEHOLDER: bool = true;
/// The DNS name every server certificate has, and every client asks for:
/// a label, not a host. Servers are known by their certificate, wherever
/// they are.
pub const SERVER_NAME: &str = "bakashrot-server";
/// Default lifetimes, in days.
pub const CA_DAYS: u32 = 3650;
/// See [`CA_DAYS`].
pub const CERTIFICATE_DAYS: u32 = 365;
/// What went wrong, in words: everything here fails on a file or a value
/// that isn't right, which people fix.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Error(String);
impl Error {
pub(crate) fn new(what: impl fmt::Display) -> Self {
Error(what.to_string())
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for Error {}
/// A result of this crate.
pub type Result<T> = std::result::Result<T, Error>;
/// Reads one PEM block of `label`, its DER.
fn pem_der(text: &str, label: &str) -> Result<Vec<u8>> {
let (_, pem) = x509_parser::pem::parse_x509_pem(text.as_bytes())
.map_err(|error| Error::new(format!("not PEM: {error}")))?;
if pem.label != label {
return Err(Error::new(format!("a {}, not a {label}", pem.label)));
}
Ok(pem.contents)
}
/// Reads a certificate (DER).
fn parse_certificate(der: &[u8]) -> Result<X509Certificate<'_>> {
let (_, certificate) = x509_parser::parse_x509_certificate(der)
.map_err(|error| Error::new(format!("not a certificate: {error}")))?;
Ok(certificate)
}
@@ -0,0 +1,91 @@
//! The certificates a CRL revokes.
//!
//! A server loads its CRL file into [`Revocations`], shares it with its TLS
//! setup ([`SharedRevocations`]), and replaces what's inside when the file
//! changes: new connections are checked against the new list at once, and
//! the server checks the open ones itself ([`Revocations::revokes_serial`],
//! their serials read once with [`serial`]).
//!
//! A CRL is only taken if it's the CA's: issued by it, its signature
//! checked. Its "next update" isn't held against it: CRLs are pushed by
//! hand, an old one still revokes what it lists.
use crate::{Error, Result, parse_certificate, pem_der};
use std::collections::HashSet;
use std::sync::{Arc, RwLock};
/// The serial numbers of the certificates a CRL revokes.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Revocations {
serials: HashSet<Vec<u8>>,
}
/// Revocations shared between a server's TLS setup and whatever reloads
/// them.
pub type SharedRevocations = Arc<RwLock<Revocations>>;
impl Revocations {
/// Nothing revoked: no CRL file.
pub fn none() -> Revocations {
Revocations::default()
}
/// Reads a CRL (PEM), which must be the CA's (its certificate, PEM).
pub fn load(crl: &str, ca_certificate: &str) -> Result<Revocations> {
let crl_der = pem_der(crl, "X509 CRL")?;
let ca_der = pem_der(ca_certificate, "CERTIFICATE")?;
let (_, list) = x509_parser::parse_x509_crl(&crl_der)
.map_err(|error| Error::new(format!("not a CRL: {error}")))?;
let ca = parse_certificate(&ca_der)
.map_err(|error| Error::new(format!("the CA's certificate: {error}")))?;
if list.issuer().as_raw() != ca.subject().as_raw() {
return Err(Error::new("the CRL is another CA's"));
}
list.verify_signature(ca.public_key())
.map_err(|_| Error::new("the CRL's signature isn't the CA's"))?;
Ok(Revocations {
serials: list
.iter_revoked_certificates()
.map(|revoked| revoked.raw_serial().to_vec())
.collect(),
})
}
/// Whether it revokes this certificate (DER). One that can't be read is
/// taken as revoked.
pub fn revokes(&self, certificate: &[u8]) -> bool {
serial(certificate).map_or(true, |serial| self.revokes_serial(&serial))
}
/// Whether it revokes the certificate with this serial number
/// ([`serial`]): checking an open connection without reading its
/// certificate again.
pub fn revokes_serial(&self, serial: &[u8]) -> bool {
self.serials.contains(serial)
}
/// The serial numbers it revokes.
pub fn serials(&self) -> impl Iterator<Item = &[u8]> {
self.serials.iter().map(Vec::as_slice)
}
/// How many it revokes.
pub fn len(&self) -> usize {
self.serials.len()
}
/// Whether it revokes none.
pub fn is_empty(&self) -> bool {
self.serials.is_empty()
}
/// Wraps it for sharing.
pub fn shared(self) -> SharedRevocations {
Arc::new(RwLock::new(self))
}
}
/// A certificate's (DER) serial number, as CRLs list them.
pub fn serial(certificate: &[u8]) -> Result<Vec<u8>> {
Ok(parse_certificate(certificate)?.raw_serial().to_vec())
}
+254
View File
@@ -0,0 +1,254 @@
//! The TLS setup of servers and clients: TLS 1.3 only, AES-256-GCM-SHA384
//! only, the X25519MLKEM768 key exchange only, ALPN `bakashrot`, and a
//! certificate from the CA on both ends.
//!
//! Each end checks the other with rustls' own verifier (a server's
//! certificate for the name they all have, [`SERVER_NAME`]: no host names
//! or IPs), then that it isn't revoked and has an identity. Both ends take
//! [`SharedRevocations`]: a server dialing its peer is that peer's client,
//! so servers block each other the same way. Once connected, either end
//! reads the other's [`Identity`] with [`peer_identity`].
use crate::{Error, Identity, Result, SERVER_NAME, SharedRevocations};
use bakashrot_proto::limits::ALPN;
use rustls::client::WebPkiServerVerifier;
use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
use rustls::crypto::{CryptoProvider, aws_lc_rs};
use rustls::pki_types::pem::PemObject;
use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName, UnixTime};
use rustls::server::WebPkiClientVerifier;
use rustls::server::danger::{ClientCertVerified, ClientCertVerifier};
use rustls::{
CertificateError, ClientConfig, DigitallySignedStruct, DistinguishedName, RootCertStore,
ServerConfig, SignatureScheme,
};
use std::sync::Arc;
/// aws-lc, with only the strongest cipher suite and key exchange.
pub fn provider() -> Arc<CryptoProvider> {
Arc::new(CryptoProvider {
cipher_suites: vec![aws_lc_rs::cipher_suite::TLS13_AES_256_GCM_SHA384],
kx_groups: vec![aws_lc_rs::kx_group::X25519MLKEM768],
..aws_lc_rs::default_provider()
})
}
/// The name a client asks for: [`SERVER_NAME`].
pub fn server_name() -> ServerName<'static> {
ServerName::try_from(SERVER_NAME).expect("SERVER_NAME is a DNS name")
}
/// A server's configuration: its certificate and key (PEM), the CA it takes
/// clients from (PEM), and the revocations it checks them against.
pub fn server_config(
ca: &str,
certificate: &str,
key: &str,
revocations: SharedRevocations,
) -> Result<Arc<ServerConfig>> {
let provider = provider();
let webpki = WebPkiClientVerifier::builder_with_provider(roots(ca)?, provider.clone())
.build()
.map_err(|error| Error::new(format!("the CA: {error}")))?;
let mut config = ServerConfig::builder_with_provider(provider)
.with_protocol_versions(&[&rustls::version::TLS13])
.map_err(tls_error)?
.with_client_cert_verifier(Arc::new(ClientCheck {
webpki,
revocations,
}))
.with_single_cert(chain(certificate)?, private_key(key)?)
.map_err(tls_error)?;
config.alpn_protocols = vec![ALPN.to_vec()];
Ok(Arc::new(config))
}
/// A client's configuration: its certificate and key (PEM), the CA it takes
/// servers from (PEM), and the revocations it checks them against
/// (`Revocations::none()` without a CRL). Connect with [`server_name`].
pub fn client_config(
ca: &str,
certificate: &str,
key: &str,
revocations: SharedRevocations,
) -> Result<Arc<ClientConfig>> {
let provider = provider();
let webpki = WebPkiServerVerifier::builder_with_provider(roots(ca)?, provider.clone())
.build()
.map_err(|error| Error::new(format!("the CA: {error}")))?;
let mut config = ClientConfig::builder_with_provider(provider)
.with_protocol_versions(&[&rustls::version::TLS13])
.map_err(tls_error)?
.dangerous()
.with_custom_certificate_verifier(Arc::new(ServerCheck {
webpki,
revocations,
}))
.with_client_auth_cert(chain(certificate)?, private_key(key)?)
.map_err(tls_error)?;
config.alpn_protocols = vec![ALPN.to_vec()];
Ok(Arc::new(config))
}
/// The identity of the other end, from its certificates once connected
/// (`peer_certificates()` of a rustls connection).
pub fn peer_identity(certificates: Option<&[CertificateDer<'_>]>) -> Result<Identity> {
let certificate = certificates
.and_then(<[_]>::first)
.ok_or_else(|| Error::new("no certificate from the other end"))?;
Identity::from_certificate(certificate)
}
fn tls_error(error: rustls::Error) -> Error {
Error::new(format!("TLS: {error}"))
}
fn roots(ca: &str) -> Result<Arc<RootCertStore>> {
let mut roots = RootCertStore::empty();
for certificate in CertificateDer::pem_slice_iter(ca.as_bytes()) {
let certificate = certificate.map_err(|error| Error::new(format!("the CA: {error}")))?;
roots.add(certificate).map_err(tls_error)?;
}
if roots.is_empty() {
return Err(Error::new("the CA: no certificate"));
}
Ok(Arc::new(roots))
}
fn chain(certificate: &str) -> Result<Vec<CertificateDer<'static>>> {
let chain = CertificateDer::pem_slice_iter(certificate.as_bytes())
.collect::<std::result::Result<Vec<_>, _>>()
.map_err(|error| Error::new(format!("the certificate: {error}")))?;
if chain.is_empty() {
return Err(Error::new("the certificate: none in it"));
}
Ok(chain)
}
fn private_key(key: &str) -> Result<PrivateKeyDer<'static>> {
PrivateKeyDer::from_pem_slice(key.as_bytes())
.map_err(|error| Error::new(format!("the key: {error}")))
}
/// What both ends check once rustls' verifier took the other's certificate:
/// not revoked, an identity.
fn ours(
certificate: &CertificateDer<'_>,
revocations: &SharedRevocations,
) -> std::result::Result<(), rustls::Error> {
// A poisoned lock: refuse rather than guess.
let revoked = revocations
.read()
.map_or(true, |revocations| revocations.revokes(certificate));
if revoked {
return Err(rustls::Error::InvalidCertificate(CertificateError::Revoked));
}
if Identity::from_certificate(certificate).is_err() {
return Err(rustls::Error::InvalidCertificate(
CertificateError::ApplicationVerificationFailure,
));
}
Ok(())
}
/// The server's check of clients: rustls', then [`ours`].
#[derive(Debug)]
struct ClientCheck {
webpki: Arc<dyn ClientCertVerifier>,
revocations: SharedRevocations,
}
impl ClientCertVerifier for ClientCheck {
fn root_hint_subjects(&self) -> &[DistinguishedName] {
self.webpki.root_hint_subjects()
}
fn verify_client_cert(
&self,
end_entity: &CertificateDer<'_>,
intermediates: &[CertificateDer<'_>],
now: UnixTime,
) -> std::result::Result<ClientCertVerified, rustls::Error> {
let verified = self
.webpki
.verify_client_cert(end_entity, intermediates, now)?;
ours(end_entity, &self.revocations)?;
Ok(verified)
}
fn verify_tls12_signature(
&self,
message: &[u8],
certificate: &CertificateDer<'_>,
signature: &DigitallySignedStruct,
) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {
self.webpki
.verify_tls12_signature(message, certificate, signature)
}
fn verify_tls13_signature(
&self,
message: &[u8],
certificate: &CertificateDer<'_>,
signature: &DigitallySignedStruct,
) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {
self.webpki
.verify_tls13_signature(message, certificate, signature)
}
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
self.webpki.supported_verify_schemes()
}
}
/// The client's check of servers: rustls', then [`ours`].
#[derive(Debug)]
struct ServerCheck {
webpki: Arc<WebPkiServerVerifier>,
revocations: SharedRevocations,
}
impl ServerCertVerifier for ServerCheck {
fn verify_server_cert(
&self,
end_entity: &CertificateDer<'_>,
intermediates: &[CertificateDer<'_>],
server_name: &ServerName<'_>,
ocsp_response: &[u8],
now: UnixTime,
) -> std::result::Result<ServerCertVerified, rustls::Error> {
let verified = self.webpki.verify_server_cert(
end_entity,
intermediates,
server_name,
ocsp_response,
now,
)?;
ours(end_entity, &self.revocations)?;
Ok(verified)
}
fn verify_tls12_signature(
&self,
message: &[u8],
certificate: &CertificateDer<'_>,
signature: &DigitallySignedStruct,
) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {
self.webpki
.verify_tls12_signature(message, certificate, signature)
}
fn verify_tls13_signature(
&self,
message: &[u8],
certificate: &CertificateDer<'_>,
signature: &DigitallySignedStruct,
) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {
self.webpki
.verify_tls13_signature(message, certificate, signature)
}
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
self.webpki.supported_verify_schemes()
}
}
+235
View File
@@ -0,0 +1,235 @@
//! Issuing: what certificates and CRLs hold, and OpenSSL agreeing.
use bakashrot_pki::{Ca, Identity, Revocations, Usage, summarize};
use std::path::PathBuf;
use std::process::Command;
fn ca() -> (Ca, String) {
let issued = Ca::create("Test CA", 30).unwrap();
(
Ca::load(&issued.certificate, &issued.key).unwrap(),
issued.certificate,
)
}
#[test]
fn certificates_say_who_and_what_for() {
let (ca, ca_certificate) = ca();
let identity = Identity::new("kitchen", &["sensor", "reader"]).unwrap();
let client = ca.issue(&identity, Usage::Client, 365).unwrap();
let server = ca
.issue(
&Identity::new("server-1", &["peer"]).unwrap(),
Usage::Server,
365,
)
.unwrap();
let summary = summarize(&client.certificate).unwrap();
assert_eq!(summary.identity, Some(identity));
assert_eq!(summary.subject, "kitchen");
assert_eq!(summary.issuer, "Test CA");
assert_eq!(summary.usage, Some(Usage::Client));
assert!(!summary.is_ca);
assert!(!summary.serial.is_empty());
assert_eq!(
summarize(&server.certificate).unwrap().usage,
Some(Usage::Server)
);
let ca_summary = summarize(&ca_certificate).unwrap();
assert!(ca_summary.is_ca);
assert_eq!(ca_summary.identity, None);
assert!(ca.issued(&client.certificate).unwrap());
let (other, _) = self::ca();
assert!(!other.issued(&client.certificate).unwrap());
}
#[test]
fn a_ca_needs_its_own_key() {
let first = Ca::create("First", 30).unwrap();
let second = Ca::create("Second", 30).unwrap();
assert!(Ca::load(&first.certificate, &second.key).is_err());
assert!(Ca::load(&first.certificate, &first.key).is_ok());
let ca = Ca::load(&first.certificate, &first.key).unwrap();
let client = ca
.issue(&Identity::new("kitchen", &[]).unwrap(), Usage::Client, 30)
.unwrap();
assert!(
Ca::load(&client.certificate, &client.key).is_err(),
"not a CA"
);
assert!(Ca::create(" ", 30).is_err());
}
#[test]
fn crls_revoke_what_they_list() {
let (ca, ca_certificate) = ca();
let certificates: Vec<String> = (0..8)
.map(|n| {
let identity = Identity::new(&format!("node-{n}"), &[]).unwrap();
ca.issue(&identity, Usage::Client, 30).unwrap().certificate
})
.collect();
let serials: Vec<Vec<u8>> = certificates[..4]
.iter()
.map(|certificate| summarize(certificate).unwrap().serial)
.collect();
let crl = ca.revocation_list(&serials, 30).unwrap();
let revocations = Revocations::load(&crl, &ca_certificate).unwrap();
assert_eq!(revocations.len(), 4);
for (n, certificate) in certificates.iter().enumerate() {
assert_eq!(revocations.revokes(&der(certificate)), n < 4, "node-{n}");
}
assert!(Revocations::none().is_empty());
assert!(!Revocations::none().revokes(&der(&certificates[0])));
let empty = ca.revocation_list(&[], 30).unwrap();
assert!(
Revocations::load(&empty, &ca_certificate)
.unwrap()
.is_empty()
);
}
#[test]
fn only_the_cas_crls_are_taken() {
let (ca, ca_certificate) = ca();
let (other, other_certificate) = self::ca();
let crl = other.revocation_list(&[vec![1]], 30).unwrap();
assert!(
Revocations::load(&crl, &ca_certificate).is_err(),
"another CA's"
);
assert!(Revocations::load(&crl, &other_certificate).is_ok());
// Tampered: a character of its Base64 changed.
let crl = ca.revocation_list(&[vec![1]], 30).unwrap();
let at = crl.len() / 2;
let swapped = if &crl[at..=at] == "A" { "B" } else { "A" };
let tampered = format!("{}{}{}", &crl[..at], swapped, &crl[at + 1..]);
assert!(Revocations::load(&tampered, &ca_certificate).is_err());
assert!(Revocations::load("not a CRL", &ca_certificate).is_err());
assert!(
Revocations::load(&ca_certificate, &ca_certificate).is_err(),
"a certificate"
);
}
fn der(certificate: &str) -> Vec<u8> {
use rustls::pki_types::{CertificateDer, pem::PemObject};
CertificateDer::from_pem_slice(certificate.as_bytes())
.unwrap()
.to_vec()
}
/// OpenSSL, from the PATH or Git for Windows'.
fn openssl() -> Option<PathBuf> {
let candidates = [
PathBuf::from("openssl"),
PathBuf::from(r"C:\Program Files\Git\ucrt64\bin\openssl.exe"),
PathBuf::from(r"C:\Program Files\Git\mingw64\bin\openssl.exe"),
PathBuf::from(r"C:\Program Files\Git\usr\bin\openssl.exe"),
];
candidates.into_iter().find(|candidate| {
Command::new(candidate)
.arg("version")
.output()
.is_ok_and(|output| output.status.success())
})
}
#[test]
fn openssl_agrees() {
let Some(openssl) = openssl() else {
eprintln!("SKIP: no openssl");
return;
};
let folder = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("pki-openssl");
let _ = std::fs::remove_dir_all(&folder);
std::fs::create_dir_all(&folder).unwrap();
let issued = Ca::create("Test CA", 30).unwrap();
let ca = Ca::load(&issued.certificate, &issued.key).unwrap();
let client = ca
.issue(
&Identity::new("kitchen", &["sensor"]).unwrap(),
Usage::Client,
30,
)
.unwrap();
let server = ca
.issue(&Identity::new("server-1", &[]).unwrap(), Usage::Server, 30)
.unwrap();
let serial = summarize(&client.certificate).unwrap().serial;
let files = [
("ca.crt", issued.certificate.clone()),
("client.crt", client.certificate),
("server.crt", server.certificate),
("ca.crl", ca.revocation_list(&[serial], 30).unwrap()),
];
for (name, text) in &files {
std::fs::write(folder.join(name), text).unwrap();
}
let run = |args: &[&str]| {
let output = Command::new(&openssl)
.args(args)
.current_dir(&folder)
.output()
.unwrap();
let text = format!(
"{}{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
(output.status.success(), text)
};
let (ok, text) = run(&[
"verify",
"-CAfile",
"ca.crt",
"-purpose",
"sslclient",
"client.crt",
]);
assert!(ok, "{text}");
let (ok, text) = run(&[
"verify",
"-CAfile",
"ca.crt",
"-purpose",
"sslserver",
"server.crt",
]);
assert!(ok, "{text}");
let (ok, _) = run(&[
"verify",
"-CAfile",
"ca.crt",
"-purpose",
"sslserver",
"client.crt",
]);
assert!(!ok, "a client's certificate isn't a server's");
let (ok, text) = run(&["crl", "-in", "ca.crl", "-CAfile", "ca.crt", "-noout"]);
assert!(ok && text.contains("verify OK"), "{text}");
let (ok, text) = run(&[
"verify",
"-CAfile",
"ca.crt",
"-CRLfile",
"ca.crl",
"-crl_check",
"client.crt",
]);
assert!(!ok && text.contains("revoked"), "{text}");
let (ok, text) = run(&["x509", "-in", "server.crt", "-noout", "-text"]);
assert!(
ok && text.contains("NIST CURVE: P-384") && text.contains("DNS:bakashrot-server"),
"{text}"
);
}
+388
View File
@@ -0,0 +1,388 @@
//! Handshakes in memory, no sockets: what's accepted and what's refused.
use bakashrot_pki::tls::{self, peer_identity};
use bakashrot_pki::{Ca, Identity, Issued, Revocations, SharedRevocations, Usage, summarize};
use bakashrot_proto::limits::ALPN;
use rustls::{ClientConfig, ClientConnection, ConnectionCommon, ServerConfig, ServerConnection};
use std::io::{Read, Write};
use std::sync::Arc;
struct Pki {
ca: Ca,
ca_certificate: String,
ca_key: String,
}
impl Pki {
fn new(name: &str) -> Pki {
let issued = Ca::create(name, 30).unwrap();
Pki {
ca: Ca::load(&issued.certificate, &issued.key).unwrap(),
ca_certificate: issued.certificate,
ca_key: issued.key,
}
}
fn issue(&self, name: &str, roles: &[&str], usage: Usage) -> Issued {
self.ca
.issue(&Identity::new(name, roles).unwrap(), usage, 30)
.unwrap()
}
fn server(&self, issued: &Issued, revocations: SharedRevocations) -> Arc<ServerConfig> {
tls::server_config(
&self.ca_certificate,
&issued.certificate,
&issued.key,
revocations,
)
.unwrap()
}
fn client(&self, issued: &Issued) -> Arc<ClientConfig> {
self.client_checking(issued, Revocations::none().shared())
}
fn client_checking(
&self,
issued: &Issued,
revocations: SharedRevocations,
) -> Arc<ClientConfig> {
tls::client_config(
&self.ca_certificate,
&issued.certificate,
&issued.key,
revocations,
)
.unwrap()
}
/// Revocations listing these certificates.
fn revoking(&self, certificates: &[&Issued]) -> SharedRevocations {
let serials: Vec<Vec<u8>> = certificates
.iter()
.map(|issued| summarize(&issued.certificate).unwrap().serial)
.collect();
let crl = self.ca.revocation_list(&serials, 30).unwrap();
Revocations::load(&crl, &self.ca_certificate)
.unwrap()
.shared()
}
}
fn transfer<A, B>(from: &mut ConnectionCommon<A>, to: &mut ConnectionCommon<B>) {
while from.wants_write() {
let mut bytes = Vec::new();
from.write_tls(&mut bytes).unwrap();
let mut rest = &bytes[..];
while !rest.is_empty() {
to.read_tls(&mut rest).unwrap();
}
}
}
/// A handshake, then a byte each way: the connections, or which end
/// refused and why.
fn connect(
client: Arc<ClientConfig>,
server: Arc<ServerConfig>,
) -> Result<(ClientConnection, ServerConnection), String> {
let mut client = ClientConnection::new(client, tls::server_name()).unwrap();
let mut server = ServerConnection::new(server).unwrap();
for _ in 0..10 {
transfer(&mut client, &mut server);
server
.process_new_packets()
.map_err(|e| format!("server: {e}"))?;
transfer(&mut server, &mut client);
client
.process_new_packets()
.map_err(|e| format!("client: {e}"))?;
if !client.is_handshaking() && !server.is_handshaking() {
break;
}
}
client.writer().write_all(b"c").unwrap();
transfer(&mut client, &mut server);
server
.process_new_packets()
.map_err(|e| format!("server: {e}"))?;
server.writer().write_all(b"s").unwrap();
transfer(&mut server, &mut client);
client
.process_new_packets()
.map_err(|e| format!("client: {e}"))?;
let mut byte = [0];
server
.reader()
.read_exact(&mut byte)
.map_err(|e| format!("server read: {e}"))?;
assert_eq!(&byte, b"c");
client
.reader()
.read_exact(&mut byte)
.map_err(|e| format!("client read: {e}"))?;
assert_eq!(&byte, b"s");
Ok((client, server))
}
#[test]
fn connected_at_the_strongest_settings() {
let pki = Pki::new("Test CA");
let server = pki.issue("server-1", &["peer"], Usage::Server);
let client = pki.issue("kitchen", &["sensor"], Usage::Client);
let (client, server) = connect(
pki.client(&client),
pki.server(&server, Revocations::none().shared()),
)
.unwrap();
assert_eq!(
client.protocol_version(),
Some(rustls::ProtocolVersion::TLSv1_3)
);
assert_eq!(
client.negotiated_cipher_suite().unwrap().suite(),
rustls::CipherSuite::TLS13_AES_256_GCM_SHA384
);
assert_eq!(
client.negotiated_key_exchange_group().unwrap().name(),
rustls::NamedGroup::X25519MLKEM768
);
assert_eq!(client.alpn_protocol(), Some(ALPN));
assert_eq!(server.alpn_protocol(), Some(ALPN));
// Each end knows who the other is.
let client_identity = peer_identity(server.peer_certificates()).unwrap();
assert_eq!(
client_identity,
Identity::new("kitchen", &["sensor"]).unwrap()
);
let server_identity = peer_identity(client.peer_certificates()).unwrap();
assert_eq!(server_identity.name, "server-1");
assert!(server_identity.has_role("peer"));
}
#[test]
fn servers_connect_to_their_peers() {
let pki = Pki::new("Test CA");
let first = pki.issue("server-1", &["peer"], Usage::Server);
let second = pki.issue("server-2", &["peer"], Usage::Server);
// A server's certificate is a client's too.
let (_, server) = connect(
pki.client(&first),
pki.server(&second, Revocations::none().shared()),
)
.unwrap();
assert_eq!(
peer_identity(server.peer_certificates()).unwrap().name,
"server-1"
);
}
#[test]
fn a_client_of_another_ca_is_refused() {
let pki = Pki::new("Test CA");
let other = Pki::new("Other CA");
let server = pki.server(
&pki.issue("server-1", &[], Usage::Server),
Revocations::none().shared(),
);
let stranger = other.issue("kitchen", &[], Usage::Client);
let client = tls::client_config(
&pki.ca_certificate,
&stranger.certificate,
&stranger.key,
Revocations::none().shared(),
)
.unwrap();
let error = connect(client, server).unwrap_err();
assert!(error.starts_with("server:"), "{error}");
}
#[test]
fn a_server_of_another_ca_is_refused() {
let pki = Pki::new("Test CA");
let other = Pki::new("Other CA");
let client = pki.client(&pki.issue("kitchen", &[], Usage::Client));
let impostor = other.issue("server-1", &[], Usage::Server);
let server = tls::server_config(
&pki.ca_certificate,
&impostor.certificate,
&impostor.key,
Revocations::none().shared(),
)
.unwrap();
let error = connect(client, server).unwrap_err();
assert!(error.starts_with("client:"), "{error}");
}
#[test]
fn a_clients_certificate_isnt_a_servers() {
let pki = Pki::new("Test CA");
let client = pki.client(&pki.issue("kitchen", &[], Usage::Client));
let posing = pki.issue("server-1", &[], Usage::Client);
let error = connect(client, pki.server(&posing, Revocations::none().shared())).unwrap_err();
assert!(error.starts_with("client:"), "{error}");
}
#[test]
fn revoked_clients_are_refused_and_reloading_takes_effect() {
let pki = Pki::new("Test CA");
let revocations = Revocations::none().shared();
let server = pki.server(
&pki.issue("server-1", &[], Usage::Server),
revocations.clone(),
);
let kitchen = pki.issue("kitchen", &[], Usage::Client);
let garage = pki.issue("garage", &[], Usage::Client);
assert!(connect(pki.client(&kitchen), server.clone()).is_ok());
// The CRL changes: the same server configuration refuses at once.
let serial = summarize(&kitchen.certificate).unwrap().serial;
let crl = pki.ca.revocation_list(&[serial], 30).unwrap();
*revocations.write().unwrap() = Revocations::load(&crl, &pki.ca_certificate).unwrap();
let error = connect(pki.client(&kitchen), server.clone()).unwrap_err();
assert!(
error.starts_with("server:") && error.contains("Revoked"),
"{error}"
);
assert!(
connect(pki.client(&garage), server.clone()).is_ok(),
"only kitchen"
);
*revocations.write().unwrap() = Revocations::none();
assert!(connect(pki.client(&kitchen), server).is_ok());
}
#[test]
fn a_certificate_without_an_identity_is_refused() {
let pki = Pki::new("Test CA");
let server = pki.server(
&pki.issue("server-1", &[], Usage::Server),
Revocations::none().shared(),
);
// Signed by the right CA, but not by Ca::issue: no identity extension.
let ca_key = rcgen::KeyPair::from_pem(&pki.ca_key).unwrap();
let issuer = rcgen::Issuer::from_ca_cert_pem(&pki.ca_certificate, ca_key).unwrap();
let key = rcgen::KeyPair::generate_for(&rcgen::PKCS_ECDSA_P384_SHA384).unwrap();
let mut params = rcgen::CertificateParams::default();
params.extended_key_usages = vec![rcgen::ExtendedKeyUsagePurpose::ClientAuth];
let certificate = params.signed_by(&key, &issuer).unwrap().pem();
let client = tls::client_config(
&pki.ca_certificate,
&certificate,
&key.serialize_pem(),
Revocations::none().shared(),
)
.unwrap();
let error = connect(client, server).unwrap_err();
assert!(error.starts_with("server:"), "{error}");
}
#[test]
fn another_protocol_is_refused() {
let pki = Pki::new("Test CA");
let server = pki.server(
&pki.issue("server-1", &[], Usage::Server),
Revocations::none().shared(),
);
let client = pki.issue("kitchen", &[], Usage::Client);
let mut config = (*pki.client(&client)).clone();
config.alpn_protocols = vec![b"http/1.1".to_vec()];
let error = connect(Arc::new(config), server).unwrap_err();
assert!(error.starts_with("server:"), "{error}");
}
#[test]
fn bad_files_are_told() {
let pki = Pki::new("Test CA");
let client = pki.issue("kitchen", &[], Usage::Client);
let none = || Revocations::none().shared();
assert!(tls::client_config("", &client.certificate, &client.key, none()).is_err());
assert!(tls::client_config(&pki.ca_certificate, "", &client.key, none()).is_err());
assert!(tls::client_config(&pki.ca_certificate, &client.certificate, "", none()).is_err());
assert!(peer_identity(None).is_err());
}
#[test]
fn clients_given_a_crl_refuse_revoked_servers() {
let pki = Pki::new("Test CA");
let server = pki.issue("server-1", &[], Usage::Server);
let client = pki.issue("kitchen", &[], Usage::Client);
let config = pki.server(&server, Revocations::none().shared());
assert!(connect(pki.client(&client), config.clone()).is_ok());
let error = connect(
pki.client_checking(&client, pki.revoking(&[&server])),
config,
)
.unwrap_err();
assert!(
error.starts_with("client:") && error.contains("Revoked"),
"{error}"
);
}
#[test]
fn servers_block_each_other() {
let pki = Pki::new("Test CA");
let first = pki.issue("server-1", &["peer"], Usage::Server);
let second = pki.issue("server-2", &["peer"], Usage::Server);
let crl = pki.revoking(&[&second]);
// server-1 has the CRL: it refuses server-2 both ways.
let error = connect(pki.client(&second), pki.server(&first, crl.clone())).unwrap_err();
assert!(
error.starts_with("server:") && error.contains("Revoked"),
"{error}"
);
let error = connect(
pki.client_checking(&first, crl),
pki.server(&second, Revocations::none().shared()),
)
.unwrap_err();
assert!(
error.starts_with("client:") && error.contains("Revoked"),
"{error}"
);
}
#[test]
fn same_named_servers_have_their_own_certificates() {
let pki = Pki::new("Test CA");
let first = pki.issue("server-1", &["peer"], Usage::Server);
let second = pki.issue("server-1", &["peer"], Usage::Server);
assert_ne!(first.certificate, second.certificate);
assert_ne!(
summarize(&first.certificate).unwrap().serial,
summarize(&second.certificate).unwrap().serial
);
let client = pki.issue("kitchen", &[], Usage::Client);
for server in [&first, &second] {
assert!(
connect(
pki.client(&client),
pki.server(server, Revocations::none().shared())
)
.is_ok()
);
}
// Revoking one leaves the other alone, as a server and as a client.
let crl = pki.revoking(&[&first]);
let checking = pki.client_checking(&client, crl.clone());
assert!(
connect(
checking.clone(),
pki.server(&first, Revocations::none().shared())
)
.is_err()
);
assert!(connect(checking, pki.server(&second, Revocations::none().shared())).is_ok());
let gate = pki.server(&pki.issue("server-2", &[], Usage::Server), crl);
assert!(connect(pki.client(&first), gate.clone()).is_err());
assert!(connect(pki.client(&second), gate).is_ok());
}
+28
View File
@@ -0,0 +1,28 @@
[package]
name = "bakashrot-proto"
description = "BakaShrot's protocol: packets, frames, names, limits and error codes, shared by the server, the clients and the tools."
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
authors.workspace = true
repository.workspace = true
publish.workspace = true
[lints]
workspace = true
# As few as possible: every other crate builds on this one.
[dependencies]
rmp-serde = "1.3.1"
serde = { version = "1.0.229", features = ["derive"] }
serde_bytes = "0.11.19"
tokio-util = { version = "0.7.20", features = ["codec"], optional = true }
[features]
# `frame::codec()`, for the async server: the blocking client (the DLL)
# leaves it off and never pulls tokio in.
tokio = ["dep:tokio-util"]
[dev-dependencies]
bytes = "1.12.1"
+181
View File
@@ -0,0 +1,181 @@
//! The error codes: what a server sends with each refusal (1-99, in a
//! `RequestRefused`), and the client's own (100 and up, what the DLL's
//! `BakaShrot_GetLastError()` returns). The same numbers as protocol 6
//! (`OldSource/Client/BakaShrot_ErrorCodes.pbi`): never renumber one, only
//! add new ones.
//!
//! What to do about each:
//! - reconnect, then retry: `NotConnected`, `ConnectFailed`,
//! `ConnectionLost`, `ProtocolError` (the connection is closed);
//! - retry later: `NotReady`, `ServerError`;
//! - fix the configuration: `AuthRejected`, `ServerNotVerified`,
//! `NotAllowed`, `UnknownName`, `NoDefaultTopic`;
//! - update one end: `VersionMismatch`;
//! - fix the call: `InvalidArgument`, `InvalidRequest`, `TooBig`,
//! `QueryFailed`, `FileError`;
//! - gone, or not there yet: `NotFound`;
//! - send it again: `DataMismatch` (an upload), `AttachmentMismatch` (a
//! download).
//!
//! A push whose answer was lost (`ConnectionLost`) may have been stored all
//! the same: pushed again, it's stored twice. Delivery is at least once.
use std::fmt;
/// The highest code a refusal can have: anything above is the client's own.
pub const MAX_REFUSAL_CODE: u32 = 99;
macro_rules! error_codes {
($( $name:ident = $code:literal, $description:literal; )*) => {
/// An error code, see the [module](self).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u32)]
pub enum ErrorCode {
$( #[doc = $description] $name = $code, )*
}
impl ErrorCode {
/// Every code, in order.
pub const ALL: &'static [ErrorCode] = &[$(ErrorCode::$name),*];
/// The code with this number, if there's one.
pub const fn from_code(code: u32) -> Option<ErrorCode> {
match code {
$( $code => Some(ErrorCode::$name), )*
_ => None,
}
}
/// Its name, as the constants have it: "NotFound".
pub const fn name(self) -> &'static str {
match self {
$( ErrorCode::$name => stringify!($name), )*
}
}
/// What it means: its documentation.
pub const fn description(self) -> &'static str {
match self {
$( ErrorCode::$name => $description, )*
}
}
}
};
}
// One text per code: its documentation, and what `description()` says.
error_codes! {
// Refused by the server: the connection is still open.
NotAllowed = 1, "Not allowed to this client: its roles' permissions, or a request only peers may make.";
UnknownName = 2, "A topic or node this server doesn't know.";
NotFound = 3, "No such message or attachment.";
NotReady = 4, "The attachment isn't on this server yet (still being replicated).";
TooBig = 5, "A message, attachment or query result over a limit, or an attachment bigger than this server keeps.";
NoDefaultTopic = 6, "Protocol 6's: a push without a topic and no default one. Protocol 7 pushes always name their topic: never sent, kept so the number isn't reused.";
InvalidRequest = 7, "A request that doesn't fit: an attachment's parts not matching its size, a part that doesn't exist...";
DataMismatch = 8, "An uploaded attachment that doesn't match its SHA-256: dropped.";
QueryFailed = 9, "The SQL of a query failed (its error in the reason).";
ServerError = 10, "The server couldn't store or read something: its database failed.";
// The client's own.
NotConnected = 100, "Not connected: never, or the connection was closed or lost before.";
ConnectFailed = 101, "The server couldn't be reached at that host and port.";
AuthRejected = 102, "The server refused the connection: a certificate it doesn't take (another CA, revoked, expired), or another protocol version.";
ServerNotVerified = 103, "The server's certificate isn't from the expected CA, or isn't for that host.";
ConnectionLost = 104, "The connection broke during a request (it's closed now). A push may still have been stored.";
ProtocolError = 105, "The server answered something unexpected or malformed: the connection is closed.";
InvalidArgument = 106, "A bad argument: a topic or node that isn't a name, a null pointer, a message or attachment over the limits, a setting missing before connecting.";
FileError = 107, "A file couldn't be opened, read or written.";
AttachmentMismatch = 108, "A downloaded attachment doesn't match its SHA-256.";
AlreadyConnected = 109, "Already connected: disconnect first.";
Internal = 110, "Out of memory, or another failure inside the client.";
VersionMismatch = 111, "The server speaks another version of the protocol: update the client or the server.";
}
impl ErrorCode {
/// Its number.
pub const fn code(self) -> u32 {
self as u32
}
/// Whether a server sends it with a refusal (1-99): the connection is
/// still open.
pub const fn is_refusal(self) -> bool {
is_refusal_code(self.code())
}
}
/// Whether `code` is a refusal's (1-99), known or not.
pub const fn is_refusal_code(code: u32) -> bool {
code >= 1 && code <= MAX_REFUSAL_CODE
}
/// The name of any code: `None` for 0, the code's name, or `Error <code>`
/// for one this version doesn't know.
pub fn code_name(code: u32) -> String {
match ErrorCode::from_code(code) {
Some(known) => known.name().to_owned(),
None if code == 0 => "None".to_owned(),
None => format!("Error {code}"),
}
}
impl fmt::Display for ErrorCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_numbers_of_protocol_6() {
let expected: &[(u32, &str)] = &[
(1, "NotAllowed"),
(2, "UnknownName"),
(3, "NotFound"),
(4, "NotReady"),
(5, "TooBig"),
(6, "NoDefaultTopic"),
(7, "InvalidRequest"),
(8, "DataMismatch"),
(9, "QueryFailed"),
(10, "ServerError"),
(100, "NotConnected"),
(101, "ConnectFailed"),
(102, "AuthRejected"),
(103, "ServerNotVerified"),
(104, "ConnectionLost"),
(105, "ProtocolError"),
(106, "InvalidArgument"),
(107, "FileError"),
(108, "AttachmentMismatch"),
(109, "AlreadyConnected"),
(110, "Internal"),
(111, "VersionMismatch"),
];
assert_eq!(ErrorCode::ALL.len(), expected.len());
for (code, name) in expected {
let known = ErrorCode::from_code(*code).expect("a known code");
assert_eq!(known.code(), *code);
assert_eq!(known.name(), *name);
assert_eq!(known.is_refusal(), *code < 100);
assert!(!known.description().is_empty());
}
}
#[test]
fn names_of_any_code() {
assert_eq!(code_name(0), "None");
assert_eq!(code_name(3), "NotFound");
assert_eq!(code_name(42), "Error 42");
assert_eq!(ErrorCode::from_code(0), None);
assert_eq!(ErrorCode::from_code(42), None);
assert!(is_refusal_code(42));
assert!(!is_refusal_code(0));
assert!(!is_refusal_code(100));
assert_eq!(ErrorCode::TooBig.to_string(), "TooBig");
}
}
+252
View File
@@ -0,0 +1,252 @@
//! Frames: every packet goes as one, its size as a 4-byte little-endian
//! unsigned integer, then the packet. A frame of more than the limit is
//! invalid as soon as its size arrived: the connection is aborted without
//! waiting for the rest. An empty one is too (as a frame here, as a packet
//! that doesn't decode with [`codec()`]).
//!
//! Over TLS, which takes care of the encryption: unlike protocol 6, frames
//! carry packets as they are.
//!
//! Before any frame, right after TLS, each end sends its protocol version
//! (4 bytes, little-endian) and reads the other's: [`write_version()`],
//! [`read_version()`], [`check_version()`]. Ends of different versions
//! abandon the connection there, whatever later versions do to frames and
//! packets.
//!
//! - [`write()`] and [`read()`]: on a blocking stream, the client's (the
//! DLL has no async runtime).
//! - [`codec()`], with the `tokio` feature: the same frames for the async
//! server, `tokio-util`'s codec (with `Framed`, a connection becomes a
//! stream of packets in and a sink of packets out).
use crate::limits::{MAX_PACKET_SIZE, PROTOCOL_VERSION};
use std::fmt;
use std::io::{self, Read, Write};
/// The size of a frame's header.
pub const HEADER_SIZE: usize = 4;
/// The size of the version each end sends first.
pub const VERSION_SIZE: usize = 4;
/// The version bytes this end sends: [`PROTOCOL_VERSION`], little-endian.
pub const fn version_bytes() -> [u8; VERSION_SIZE] {
PROTOCOL_VERSION.to_le_bytes()
}
/// Checks the version bytes the other end sent: `Err` with its version if
/// it isn't this one (abandon the connection then).
pub const fn check_version(bytes: [u8; VERSION_SIZE]) -> Result<(), u32> {
let theirs = u32::from_le_bytes(bytes);
if theirs == PROTOCOL_VERSION {
Ok(())
} else {
Err(theirs)
}
}
/// Sends this end's version, on a blocking stream.
pub fn write_version<W: Write>(writer: &mut W) -> io::Result<()> {
writer.write_all(&version_bytes())
}
/// Reads the other end's version, on a blocking stream: compare it with
/// [`check_version()`].
pub fn read_version<R: Read>(reader: &mut R) -> io::Result<[u8; VERSION_SIZE]> {
let mut bytes = [0; VERSION_SIZE];
reader.read_exact(&mut bytes)?;
Ok(bytes)
}
/// Why a frame is invalid. Either aborts the connection.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FrameError {
/// A frame of 0 bytes.
Empty,
/// A frame bigger than the limit.
TooBig {
/// Its size.
size: usize,
/// The limit.
max: usize,
},
}
impl fmt::Display for FrameError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
FrameError::Empty => f.write_str("an empty frame"),
FrameError::TooBig { size, max } => {
write!(f, "a frame of {size} bytes, over the limit of {max}")
}
}
}
}
impl std::error::Error for FrameError {}
fn check(size: usize, max: usize) -> Result<(), FrameError> {
if size == 0 {
Err(FrameError::Empty)
} else if size > max {
Err(FrameError::TooBig { size, max })
} else {
Ok(())
}
}
/// `packet` as a frame: its size, then itself. Fails if it's empty or over
/// [`MAX_PACKET_SIZE`].
pub fn encode(packet: &[u8]) -> Result<Vec<u8>, FrameError> {
check(packet.len(), MAX_PACKET_SIZE)?;
let mut frame = Vec::with_capacity(HEADER_SIZE + packet.len());
frame.extend_from_slice(&(packet.len() as u32).to_le_bytes());
frame.extend_from_slice(packet);
Ok(frame)
}
/// Writes `packet` as a frame, in one write.
pub fn write<W: Write>(writer: &mut W, packet: &[u8]) -> io::Result<()> {
let frame =
encode(packet).map_err(|error| io::Error::new(io::ErrorKind::InvalidInput, error))?;
writer.write_all(&frame)
}
/// Reads the next frame's packet, at most `max` bytes.
///
/// `Ok(None)` when the stream ended cleanly, before the next frame. An
/// error of kind `UnexpectedEof` if it ended inside one, `InvalidData` (a
/// [`FrameError`] inside) if its size is 0 or over `max`.
pub fn read<R: Read>(reader: &mut R, max: usize) -> io::Result<Option<Vec<u8>>> {
let mut header = [0u8; HEADER_SIZE];
let mut got = 0;
while got < HEADER_SIZE {
match reader.read(&mut header[got..]) {
Ok(0) if got == 0 => return Ok(None),
Ok(0) => return Err(io::ErrorKind::UnexpectedEof.into()),
Ok(count) => got += count,
Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
Err(error) => return Err(error),
}
}
let size = u32::from_le_bytes(header) as usize;
check(size, max).map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
let mut packet = vec![0; size];
reader.read_exact(&mut packet)?;
Ok(Some(packet))
}
/// The frames as `tokio-util` cuts and writes them, for the async server:
/// the same as [`read()`] and [`write()`], packets of up to `max` bytes
/// ([`MAX_PACKET_SIZE`] at most). Use it with `tokio_util::codec::Framed`.
#[cfg(feature = "tokio")]
pub fn codec(max: usize) -> tokio_util::codec::LengthDelimitedCodec {
tokio_util::codec::LengthDelimitedCodec::builder()
.little_endian()
.length_field_length(HEADER_SIZE)
.max_frame_length(max.min(MAX_PACKET_SIZE))
.new_codec()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn blocking_round_trip() {
let mut stream = Vec::new();
write(&mut stream, b"abc").unwrap();
write(&mut stream, &[7; 300]).unwrap();
assert_eq!(&stream[..7], &[3, 0, 0, 0, b'a', b'b', b'c']);
let mut reader = &stream[..];
assert_eq!(read(&mut reader, 1000).unwrap(), Some(b"abc".to_vec()));
assert_eq!(read(&mut reader, 1000).unwrap(), Some(vec![7; 300]));
assert_eq!(read(&mut reader, 1000).unwrap(), None);
}
#[test]
fn versions() {
let mut stream = Vec::new();
write_version(&mut stream).unwrap();
assert_eq!(stream, [7, 0, 0, 0]);
let bytes = read_version(&mut &stream[..]).unwrap();
assert_eq!(check_version(bytes), Ok(()));
assert_eq!(check_version([6, 0, 0, 0]), Err(6));
assert_eq!(check_version([8, 0, 0, 0]), Err(8));
assert!(read_version(&mut &[7u8, 0][..]).is_err());
}
#[test]
fn blocking_refusals() {
assert_eq!(encode(&[]), Err(FrameError::Empty));
assert!(write(&mut Vec::new(), &[]).is_err());
let kind = |bytes: &[u8], max| read(&mut &bytes[..], max).unwrap_err().kind();
assert_eq!(kind(&[0, 0, 0, 0], 10), io::ErrorKind::InvalidData);
assert_eq!(kind(&[11, 0, 0, 0], 10), io::ErrorKind::InvalidData);
assert_eq!(kind(&[3, 0], 10), io::ErrorKind::UnexpectedEof);
assert_eq!(kind(&[3, 0, 0, 0, 1], 10), io::ErrorKind::UnexpectedEof);
}
#[cfg(feature = "tokio")]
mod codec {
use super::super::*;
use bytes::{Bytes, BytesMut};
use tokio_util::codec::{Decoder, Encoder};
#[test]
fn the_same_frames() {
let mut codec = codec(MAX_PACKET_SIZE);
let mut written = BytesMut::new();
codec
.encode(Bytes::from_static(b"abc"), &mut written)
.unwrap();
assert_eq!(&written[..], &encode(b"abc").unwrap()[..]);
}
#[test]
fn byte_by_byte() {
let mut stream = encode(b"first").unwrap();
stream.extend(encode(&[1; 70_000]).unwrap());
stream.extend(encode(b"third").unwrap());
let mut codec = codec(100_000);
let mut buffer = BytesMut::new();
let mut packets = Vec::new();
for byte in &stream {
buffer.extend_from_slice(&[*byte]);
while let Some(packet) = codec.decode(&mut buffer).unwrap() {
packets.push(packet.to_vec());
}
}
assert_eq!(
packets,
vec![b"first".to_vec(), vec![1; 70_000], b"third".to_vec()]
);
}
#[test]
fn refused_as_soon_as_the_size_came() {
let mut codec = codec(10);
let mut buffer = BytesMut::from(&[11u8, 0, 0][..]);
assert!(codec.decode(&mut buffer).unwrap().is_none());
buffer.extend_from_slice(&[0]);
assert!(codec.decode(&mut buffer).is_err());
// Never above the protocol's limit.
assert_eq!(
super::super::codec(usize::MAX).max_frame_length(),
MAX_PACKET_SIZE
);
}
#[test]
fn an_empty_frame_is_an_empty_packet() {
let mut codec = codec(10);
let mut buffer = BytesMut::from(&[0u8, 0, 0, 0][..]);
let packet = codec.decode(&mut buffer).unwrap().unwrap();
assert!(crate::Packet::decode(&packet).is_err());
}
}
}
+23
View File
@@ -0,0 +1,23 @@
//! BakaShrot's protocol, version 7: what the server, the clients and the
//! tools share, and nothing else.
//!
//! No I/O of its own beyond reading and writing frames on a stream it's
//! given: everything here is tested on its own. Packets are MessagePack,
//! through `serde` and `rmp-serde`.
//!
//! - [`limits`]: the protocol's numbers (sizes, counts, the version).
//! - [`error`]: the error codes, the same numbers as protocol 6.
//! - [`names`]: topic and node names, wildcards.
//! - [`frame`]: frames, a 4-byte size then a packet.
//! - [`packets`]: every packet, and [`Packet`] to encode and decode them.
//!
//! The wire format is described in `Source/docs/protocol.md`.
pub mod error;
pub mod frame;
pub mod limits;
pub mod names;
pub mod packets;
pub use error::ErrorCode;
pub use packets::{Body, DecodeError, Packet, PacketType};
+105
View File
@@ -0,0 +1,105 @@
//! The protocol's numbers: its version, sizes and counts. Servers may set
//! lower limits of their own (a smaller maximum attachment, say), never
//! higher ones.
/// The protocol's version. Both ends must have the same: they tell each
/// other first thing (`frame::write_version()`), and abandon the
/// connection if it differs. 6 was the last PureBasic one (`OldSource/`);
/// 7 runs over TLS.
pub const PROTOCOL_VERSION: u32 = 7;
/// The ALPN protocol name both ends offer during the TLS handshake: what
/// isn't BakaShrot doesn't get past it. Not versioned: the version is
/// checked once connected, so a mismatch is told as such.
pub const ALPN: &[u8] = b"bakashrot";
/// The biggest packet on the wire, in bytes (a frame's size field).
pub const MAX_PACKET_SIZE: usize = 16 * 1024 * 1024;
/// The biggest message a client may push, in UTF-8 bytes. It leaves room
/// for the fields around it, so a stored message fits in every packet that
/// carries one (a `Messages` or `ReplicateMessages` of one).
pub const MAX_MESSAGE_SIZE: usize = MAX_PACKET_SIZE - 4096;
/// The latest time a message can have been pushed: 9999-12-31 23:59:59.999
/// UTC, in milliseconds since 1970-01-01 00:00:00 UTC. Times on the wire go
/// from 1 to this.
pub const MAX_TIMESTAMP: u64 = 253_402_300_799_999;
/// The biggest message id: 2^43 - 1, about 8.8 trillion per topic and
/// node. Servers store it in 43 bits of a packed key
/// (`Source/docs/storage.md`, "Keys").
pub const MAX_MESSAGE_ID: u64 = (1 << 43) - 1;
/// The longest topic or node name, in characters (ASCII only).
pub const MAX_NAME_LENGTH: usize = 64;
/// The most messages a `GetMessages` may ask for, a `Messages` may carry,
/// and a `ReplicateMessages` may hold.
pub const MAX_MESSAGES_PER_PACKET: u32 = 10_000;
/// The most names in a `NamesList`, and in each list of a `SyncState`.
pub const MAX_NAMES_LIST_ENTRIES: usize = 65_536;
/// The most attachments a `SyncState` lists as missing at once.
pub const MAX_MISSING_ATTACHMENTS: usize = 256;
/// Attachments go in parts of this many bytes, the last one what's left.
pub const ATTACHMENT_PART_SIZE: u64 = 1024 * 1024;
/// The biggest attachment the protocol allows (1 TiB).
pub const MAX_ATTACHMENT_SIZE: u64 = 1 << 40;
/// How many parts the biggest attachment takes.
pub const MAX_ATTACHMENT_PARTS: u64 = MAX_ATTACHMENT_SIZE / ATTACHMENT_PART_SIZE;
/// How many parts an attachment of `size` bytes takes.
pub const fn attachment_part_count(size: u64) -> u64 {
size.div_ceil(ATTACHMENT_PART_SIZE)
}
/// The size of part `index` of an attachment of `size` bytes, 0 if it has
/// no such part.
pub const fn attachment_part_len(size: u64, index: u64) -> u64 {
if index >= attachment_part_count(size) {
0
} else if index == attachment_part_count(size) - 1 {
size - index * ATTACHMENT_PART_SIZE
} else {
ATTACHMENT_PART_SIZE
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parts() {
assert_eq!(attachment_part_count(0), 0);
assert_eq!(attachment_part_count(1), 1);
assert_eq!(attachment_part_count(ATTACHMENT_PART_SIZE), 1);
assert_eq!(attachment_part_count(ATTACHMENT_PART_SIZE + 1), 2);
assert_eq!(
attachment_part_count(MAX_ATTACHMENT_SIZE),
MAX_ATTACHMENT_PARTS
);
let size = 2 * ATTACHMENT_PART_SIZE + 10;
assert_eq!(attachment_part_len(size, 0), ATTACHMENT_PART_SIZE);
assert_eq!(attachment_part_len(size, 1), ATTACHMENT_PART_SIZE);
assert_eq!(attachment_part_len(size, 2), 10);
assert_eq!(attachment_part_len(size, 3), 0);
assert_eq!(attachment_part_len(0, 0), 0);
assert_eq!(
attachment_part_len(ATTACHMENT_PART_SIZE, 0),
ATTACHMENT_PART_SIZE
);
}
#[test]
fn a_stored_message_fits_in_a_packet() {
const { assert!(MAX_MESSAGE_SIZE + 4096 <= MAX_PACKET_SIZE) };
assert!(MAX_PACKET_SIZE <= u32::MAX as usize);
}
}
+148
View File
@@ -0,0 +1,148 @@
//! Topic and node names, and wildcards: the rules of protocol 6
//! (`OldSource/Commons/Networking/Names.pbi`), without its ids.
//!
//! Topics and nodes go by name everywhere on the wire: a server's ids for
//! them are its own business, in its database.
//!
//! - A **name** is 1-64 characters out of `A-Z a-z 0-9 _ . -`, not only
//! digits, compared without case ("Logs" is "logs").
//! - A **pattern** is a name with wildcards, like file names: `*` any
//! characters (none included), `?` exactly one.
use crate::limits::MAX_NAME_LENGTH;
/// Whether `c` may be in a name.
const fn is_name_char(c: u8) -> bool {
c.is_ascii_alphanumeric() || c == b'_' || c == b'.' || c == b'-'
}
/// Whether `name` can be a topic or node name, see the [module](self).
pub fn is_valid_name(name: &str) -> bool {
!name.is_empty()
&& name.len() <= MAX_NAME_LENGTH
&& !name.bytes().all(|c| c.is_ascii_digit())
&& name.bytes().all(is_name_char)
}
/// Whether two names are the same name (without case).
pub fn names_equal(a: &str, b: &str) -> bool {
a.eq_ignore_ascii_case(b)
}
/// Whether `pattern` is a valid pattern: a `*` or a `?` at least, and
/// otherwise only characters a name can have, 64 at most.
pub fn is_valid_pattern(pattern: &str) -> bool {
!pattern.is_empty()
&& pattern.len() <= MAX_NAME_LENGTH
&& pattern.bytes().any(|c| c == b'*' || c == b'?')
&& pattern
.bytes()
.all(|c| is_name_char(c) || c == b'*' || c == b'?')
}
/// Whether `text` is a name or a pattern: what a list of topics or nodes
/// holds (`SyncState`, configs).
pub fn is_valid_name_or_pattern(text: &str) -> bool {
is_valid_name(text) || is_valid_pattern(text)
}
/// Whether the name `name` matches `pattern` (without case). Anything that
/// isn't a valid name never matches.
pub fn pattern_matches(pattern: &str, name: &str) -> bool {
if !is_valid_name(name) {
return false;
}
let pattern = pattern.as_bytes();
let name = name.as_bytes();
let (mut p, mut n) = (0, 0);
// Where the last `*` was, and where in the name it started matching.
let mut star: Option<(usize, usize)> = None;
// Greedy, going back to the last `*` on a mismatch: linear enough for
// 64 characters.
while n < name.len() {
if p < pattern.len() && pattern[p] == b'*' {
star = Some((p, n));
p += 1;
} else if p < pattern.len()
&& (pattern[p] == b'?' || pattern[p].eq_ignore_ascii_case(&name[n]))
{
p += 1;
n += 1;
} else if let Some((star_p, star_n)) = star {
p = star_p + 1;
n = star_n + 1;
star = Some((star_p, star_n + 1));
} else {
return false;
}
}
pattern[p..].iter().all(|c| *c == b'*')
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn names() {
for name in [
"logs",
"Logs",
"kitchen-1",
"a.b_c-d",
"x",
"1a",
&"a".repeat(64),
] {
assert!(is_valid_name(name), "{name}");
}
for name in ["", "12", "0", "a b", "é", "a/b", "a*", &"a".repeat(65)] {
assert!(!is_valid_name(name), "{name}");
}
assert!(names_equal("Logs", "lOGS"));
assert!(!names_equal("logs", "log"));
}
#[test]
fn patterns() {
for pattern in ["*", "?", "sensors.*", "kitchen-??", "*a*b*"] {
assert!(is_valid_pattern(pattern), "{pattern}");
assert!(is_valid_name_or_pattern(pattern), "{pattern}");
}
for pattern in ["", "logs", "a b*", "a/*", &format!("{}*", "a".repeat(64))] {
assert!(!is_valid_pattern(pattern), "{pattern}");
}
assert!(is_valid_name_or_pattern("logs"));
assert!(!is_valid_name_or_pattern("12"));
assert!(!is_valid_name_or_pattern("a b"));
let cases = [
("*", "logs", true),
("sensors.*", "sensors.kitchen", true),
// `*` matches nothing too, and "sensors." is a name.
("sensors.*", "sensors.", true),
("sensors.*", "SENSORS.x", true),
("sensors.*", "sensor.x", false),
("kitchen-??", "kitchen-12", true),
("kitchen-??", "kitchen-1", false),
("kitchen-??", "kitchen-123", false),
("*a*b*", "xxaxxbxx", true),
("*a*b", "ab", true),
("*a*b", "aba", false),
("a*a*a", "aaa", true),
("a*a*a", "aa", false),
("**", "x", true),
("*", "12", false),
("?", "1", false),
("*", "", false),
];
for (pattern, name, expected) in cases {
assert_eq!(
pattern_matches(pattern, name),
expected,
"{pattern} / {name}"
);
}
}
}
@@ -0,0 +1,108 @@
//! Attachments: one per message at most, in parts of `ATTACHMENT_PART_SIZE`
//! (the last one what's left), checked with their SHA-256 once all came.
//!
//! Parts are streamed, without a request or an answer each:
//! - **Pushing:** `PushMessage` with its `Attachment`, the server's
//! `Continue`, every part, then `MessagePushed` (or `RequestRefused`,
//! `DataMismatch` if the SHA-256 doesn't match). Once it said `Continue`,
//! the server reads every part even if storing them failed, then refuses.
//! - **Reading:** `GetAttachment`, the server's `Attachment`, then the
//! parts from the one asked to the last. A server that fails while
//! sending them closes the connection.
//! - **Replicating:** `ReplicateAttachment`, the server's `Continue`, the
//! parts from the one it lacks, then `MessagePushed`.
//!
//! A part is its data alone: its index follows from the order, its size
//! from the attachment's ([`Attachment::part_len`]), which the receiver
//! checks.
use super::rules;
use super::{Check, DecodeError};
use crate::limits::{
ATTACHMENT_PART_SIZE, MAX_ATTACHMENT_PARTS, MAX_ATTACHMENT_SIZE, attachment_part_count,
attachment_part_len,
};
use serde::{Deserialize, Serialize};
/// An attachment's size and checksum: in a `PushMessage` or a replicated
/// message, and on its own before the parts of a `GetAttachment`.
///
/// `[9, [size, sha256]]`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Attachment {
/// Its size, 1 to `MAX_ATTACHMENT_SIZE` (servers may take less).
pub size: u64,
/// Its SHA-256.
#[serde(with = "serde_bytes")]
pub sha256: [u8; 32],
}
impl Attachment {
/// How many parts it takes.
pub const fn part_count(&self) -> u64 {
attachment_part_count(self.size)
}
/// The size its part `index` must have, 0 if it has no such part.
pub const fn part_len(&self, index: u64) -> u64 {
attachment_part_len(self.size, index)
}
}
impl Check for Attachment {
fn check(&self) -> Result<(), DecodeError> {
rules::range(self.size, 1, MAX_ATTACHMENT_SIZE, "Attachment.size")
}
}
/// A part of an attachment, the next one.
///
/// `[10, [data]]`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AttachmentPart {
/// The part, 1 to `ATTACHMENT_PART_SIZE` bytes (its exact size is the
/// receiver's to check).
#[serde(with = "serde_bytes")]
pub data: Vec<u8>,
}
impl Check for AttachmentPart {
fn check(&self) -> Result<(), DecodeError> {
rules::range(
self.data.len() as u64,
1,
ATTACHMENT_PART_SIZE,
"AttachmentPart.data",
)
}
}
/// A message's attachment, from a part on (0 for all of it).
///
/// `[8, [topic, node, message_id, from_part]]`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct GetAttachment {
/// The topic.
pub topic: String,
/// The node.
pub node: String,
/// The message.
pub message_id: u64,
/// The first part to send: a client going on from where a lost
/// connection stopped.
pub from_part: u64,
}
impl Check for GetAttachment {
fn check(&self) -> Result<(), DecodeError> {
rules::name(&self.topic, "GetAttachment.topic")?;
rules::name(&self.node, "GetAttachment.node")?;
rules::message_id(self.message_id, "GetAttachment.message_id")?;
rules::range(
self.from_part,
0,
MAX_ATTACHMENT_PARTS - 1,
"GetAttachment.from_part",
)
}
}
@@ -0,0 +1,235 @@
//! Clients' requests and their answers: pushing and reading messages,
//! names, queries.
use super::rules;
use super::{Attachment, Check, DecodeError};
use crate::limits::{
MAX_ATTACHMENT_SIZE, MAX_MESSAGE_ID, MAX_MESSAGES_PER_PACKET, MAX_NAMES_LIST_ENTRIES,
};
use serde::{Deserialize, Serialize};
/// A message's attachment, as reads show it.
///
/// `[size, ready]`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct StoredAttachment {
/// Its size, 1 and up.
pub size: u64,
/// Whether all of it is on this server (it may still be on its way from
/// a peer).
pub ready: bool,
}
/// A stored message, as `Messages` carries it.
///
/// `[id, pushed_at, data, attachment]`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MessageEntry {
/// Its id, in its topic/node pair (1 and up).
pub id: u64,
/// When it was pushed: milliseconds since 1970 UTC, by the server it was
/// pushed to, kept as is by replication.
pub pushed_at: u64,
/// The message, as pushed (JSON or not).
pub data: String,
/// Its attachment, if it has one.
pub attachment: Option<StoredAttachment>,
}
impl Check for MessageEntry {
fn check(&self) -> Result<(), DecodeError> {
rules::message_id(self.id, "message.id")?;
rules::timestamp(self.pushed_at, "message.pushed_at")?;
if let Some(attachment) = &self.attachment {
rules::range(
attachment.size,
1,
MAX_ATTACHMENT_SIZE,
"message.attachment.size",
)?;
}
Ok(())
}
}
/// Stores a message under the client's node. With an attachment, the
/// server answers `Continue` (or refuses), the client sends all its parts,
/// then the server stores both and answers `MessagePushed`.
///
/// `[4, [topic, data, attachment]]`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PushMessage {
/// The topic: a push always names it.
pub topic: String,
/// The message (JSON or not), up to `MAX_MESSAGE_SIZE` bytes (the
/// server refuses bigger ones).
pub data: String,
/// Its attachment, whose parts follow the server's `Continue`.
pub attachment: Option<Attachment>,
}
impl Check for PushMessage {
fn check(&self) -> Result<(), DecodeError> {
rules::name(&self.topic, "PushMessage.topic")?;
if let Some(attachment) = &self.attachment {
attachment.check()?;
}
Ok(())
}
}
/// The id a message was stored with (the last of a replicated batch).
///
/// `[5, [message_id]]`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MessagePushed {
/// The id.
pub message_id: u64,
}
impl Check for MessagePushed {
fn check(&self) -> Result<(), DecodeError> {
rules::message_id(self.message_id, "MessagePushed.message_id")
}
}
/// A topic/node's messages, in id order: those after an id, or its last
/// ones.
///
/// `[6, [topic, node, after, limit]]`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct GetMessages {
/// The topic.
pub topic: String,
/// The node.
pub node: String,
/// Those with a higher id than this (0 for all), or nil for the last
/// `limit` ones (the latest message: nil and 1).
pub after: Option<u64>,
/// At most this many, 1 to `MAX_MESSAGES_PER_PACKET`.
pub limit: u32,
}
impl Check for GetMessages {
fn check(&self) -> Result<(), DecodeError> {
rules::name(&self.topic, "GetMessages.topic")?;
rules::name(&self.node, "GetMessages.node")?;
if let Some(after) = self.after {
rules::range(after, 0, MAX_MESSAGE_ID, "GetMessages.after")?;
}
rules::range(
self.limit.into(),
1,
MAX_MESSAGES_PER_PACKET.into(),
"GetMessages.limit",
)
}
}
/// A run of a topic/node's messages, in id order. None isn't a refusal.
///
/// `[7, [more, [message...]]]`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Messages {
/// Whether more follow the last one: ask again after its id.
pub more: bool,
/// The messages, ids strictly increasing, `MAX_MESSAGES_PER_PACKET` at
/// most; fewer than asked once they reach about a megabyte (the
/// server's choice), a bigger message alone.
pub messages: Vec<MessageEntry>,
}
impl Check for Messages {
fn check(&self) -> Result<(), DecodeError> {
rules::most(
self.messages.len(),
MAX_MESSAGES_PER_PACKET as usize,
"Messages.messages",
)?;
rules::increasing(self.messages.iter().map(|m| m.id), "Messages.messages")?;
self.messages.iter().try_for_each(Check::check)
}
}
/// Raw read-only SQL.
///
/// `[13, [sql]]`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Query {
/// The query: one statement, starting with SELECT or WITH.
pub sql: String,
}
impl Check for Query {}
/// A query's result.
///
/// `[14, [json]]`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct QueryResult {
/// `{"columns":[...],"rows":[[...],...]}`.
pub json: String,
}
impl Check for QueryResult {}
/// Topics or nodes: 1 or 2 on the wire.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(into = "u8", try_from = "u8")]
pub enum NameKind {
/// Topics.
Topic = 1,
/// Nodes.
Node = 2,
}
impl From<NameKind> for u8 {
fn from(kind: NameKind) -> u8 {
kind as u8
}
}
impl TryFrom<u8> for NameKind {
type Error = &'static str;
fn try_from(value: u8) -> Result<NameKind, Self::Error> {
match value {
1 => Ok(NameKind::Topic),
2 => Ok(NameKind::Node),
_ => Err("a name kind is 1 (topics) or 2 (nodes)"),
}
}
}
/// Every topic or node the client may see.
///
/// `[11, [kind]]`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ListNames {
/// Topics or nodes.
pub kind: NameKind,
}
impl Check for ListNames {}
/// Topics or nodes.
///
/// `[12, [kind, truncated, [name...]]]`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct NamesList {
/// Topics or nodes.
pub kind: NameKind,
/// Whether some didn't fit.
pub truncated: bool,
/// The names, `MAX_NAMES_LIST_ENTRIES` at most.
pub names: Vec<String>,
}
impl Check for NamesList {
fn check(&self) -> Result<(), DecodeError> {
rules::most(self.names.len(), MAX_NAMES_LIST_ENTRIES, "NamesList.names")?;
self.names
.iter()
.try_for_each(|name| rules::name(name, "NamesList.names"))
}
}
@@ -0,0 +1,324 @@
//! Every packet of protocol 7.
//!
//! A packet is a MessagePack array of two: its type, then its fields as an
//! array, `[type, [field, field, ...]]`. Structs inside are arrays of their
//! fields too, `Option`s nil or their value, bytes binaries. All of it is
//! derived with `serde` (`rmp-serde`'s compact form): the structs below
//! are the format, `Source/docs/protocol.md` lists them.
//!
//! [`Packet::decode`] checks everything: the types and the number of
//! fields (`serde`), then each packet's rules ([`Check`]: ranges, names,
//! ids in order), and that nothing follows. (A struct given as a map of its
//! field names is taken too, `serde`'s derive: nothing writes that form, it
//! isn't part of the format, its values are checked all the same.) Whatever isn't right is a
//! [`DecodeError`]: the connection is aborted. What's well-formed but not
//! allowed or not found (a topic this server doesn't have) is the server's
//! to refuse, with a `RequestRefused`.
//!
//! Topics and nodes are names everywhere, never ids.
//!
//! Adding a packet: a struct deriving `Serialize` and `Deserialize`, with
//! its [`Check`], in the file of its family; a line in the `packets!` table
//! below with the next id (never reuse one); a sample in `tests/packets.rs`;
//! its row in `Source/docs/protocol.md`.
mod attachments;
mod messages;
mod replication;
mod session;
pub use attachments::{Attachment, AttachmentPart, GetAttachment};
pub use messages::{
GetMessages, ListNames, MessageEntry, MessagePushed, Messages, NameKind, NamesList,
PushMessage, Query, QueryResult, StoredAttachment,
};
pub use replication::{
Head, MissingAttachment, ReplicateAttachment, ReplicateMessages, ReplicatedMessage, SyncState,
SyncStateRequest,
};
pub use session::{Continue, RequestRefused, Welcome};
use serde::de::{self, DeserializeOwned, IgnoredAny, SeqAccess, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
use std::io::Cursor;
/// Why a packet couldn't be read. Any of these aborts the connection.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DecodeError {
/// Not a packet: not MessagePack, a value of the wrong type, a field
/// missing or one too many, a type this version doesn't know.
Malformed(String),
/// Bytes after the packet.
TrailingBytes,
/// A field breaking a rule of its packet.
Invalid {
/// The field.
field: &'static str,
/// The rule it breaks.
rule: &'static str,
},
}
impl fmt::Display for DecodeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
DecodeError::Malformed(why) => write!(f, "malformed packet: {why}"),
DecodeError::TrailingBytes => f.write_str("bytes after the end of the packet"),
DecodeError::Invalid { field, rule } => write!(f, "{field}: {rule}"),
}
}
}
impl std::error::Error for DecodeError {}
/// The rules a packet's fields follow beyond their types, checked by
/// [`Packet::decode`]. None by default.
pub trait Check {
/// Fails on the first rule broken.
fn check(&self) -> Result<(), DecodeError> {
Ok(())
}
}
/// What every packet's struct is, implemented by the `packets!` table.
pub trait Body: Serialize + DeserializeOwned + Check + Into<Packet> {
/// Its type, the packet's first value.
const TYPE: PacketType;
/// The whole packet: `[type, [fields...]]`.
fn encode(&self) -> Vec<u8> {
rmp_serde::to_vec(&(Self::TYPE.id(), self)).expect("packets always serialize")
}
}
// The one table of packets: their names (the struct's and the variant's)
// and ids. Protocol 7's own: protocol 6's ids don't apply (the versions are
// checked before any packet).
macro_rules! packets {
($( $(#[$doc:meta])* $name:ident = $id:literal, )*) => {
/// The type of a packet: its first value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum PacketType {
$( $(#[$doc])* $name = $id, )*
}
impl PacketType {
/// Every type.
pub const ALL: &'static [PacketType] = &[$(PacketType::$name),*];
/// The type with this id, if there's one.
pub const fn from_id(id: u64) -> Option<PacketType> {
match id {
$( $id => Some(PacketType::$name), )*
_ => None,
}
}
/// Its id.
pub const fn id(self) -> u8 {
self as u8
}
/// Its name: "PushMessage".
pub const fn name(self) -> &'static str {
match self {
$( PacketType::$name => stringify!($name), )*
}
}
}
/// Any packet.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Packet {
$( $(#[$doc])* $name($name), )*
}
$(
impl Body for $name {
const TYPE: PacketType = PacketType::$name;
}
impl From<$name> for Packet {
fn from(body: $name) -> Packet {
Packet::$name(body)
}
}
)*
impl Packet {
/// Its type.
pub const fn packet_type(&self) -> PacketType {
match self {
$( Packet::$name(_) => PacketType::$name, )*
}
}
fn check(&self) -> Result<(), DecodeError> {
match self {
$( Packet::$name(body) => body.check(), )*
}
}
}
impl Serialize for Packet {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
match self {
$( Packet::$name(body) => (PacketType::$name.id(), body).serialize(serializer), )*
}
}
}
impl<'de> Deserialize<'de> for Packet {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Packet, D::Error> {
struct PacketVisitor;
impl<'de> Visitor<'de> for PacketVisitor {
type Value = Packet;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a packet, [type, [fields...]]")
}
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Packet, A::Error> {
let id: u64 = seq
.next_element()?
.ok_or_else(|| de::Error::invalid_length(0, &self))?;
let packet = match PacketType::from_id(id) {
$(
Some(PacketType::$name) => Packet::$name(
seq.next_element()?
.ok_or_else(|| de::Error::invalid_length(1, &self))?,
),
)*
None => return Err(de::Error::custom(format_args!("unknown packet type {id}"))),
};
if seq.next_element::<IgnoredAny>()?.is_some() {
return Err(de::Error::invalid_length(3, &self));
}
Ok(packet)
}
}
deserializer.deserialize_seq(PacketVisitor)
}
}
};
}
packets! {
/// S→C, S→P: the server's first packet, once TLS is up.
Welcome = 1,
/// S→C, S→P: a request refused, with an error code; the connection stays.
RequestRefused = 2,
/// S→C, S→P: send the attachment's parts now.
Continue = 3,
/// C→S: stores a message, its attachment's parts after it if it has one
/// (`MessagePushed` / `RequestRefused`, `Continue` first for an attachment).
PushMessage = 4,
/// S→C, S→P: the stored message's id (the last one of a replicated batch).
MessagePushed = 5,
/// C→S: a topic/node's messages after an id, or its last ones (`Messages` / `RequestRefused`).
GetMessages = 6,
/// S→C: a run of messages.
Messages = 7,
/// C→S: a message's attachment, from a part on (`Attachment` then its parts / `RequestRefused`).
GetAttachment = 8,
/// S→C: the attachment whose parts follow.
Attachment = 9,
/// C→S, S→C, P→S: a part of an attachment, the next one.
AttachmentPart = 10,
/// C→S: every topic or node the client may see (`NamesList`).
ListNames = 11,
/// S→C: topics or nodes.
NamesList = 12,
/// C→S: read-only SQL (`QueryResult` / `RequestRefused`).
Query = 13,
/// S→C: a query's result.
QueryResult = 14,
/// P→S: what the server takes from this peer and has (`SyncState` / `RequestRefused`).
SyncStateRequest = 15,
/// S→P: what the server takes from this peer, how far it is, the attachments it lacks.
SyncState = 16,
/// P→S: messages of a topic/node the server is missing (`MessagePushed` / `RequestRefused`).
ReplicateMessages = 17,
/// P→S: an attachment the server is missing, its parts after it (`Continue`, then `MessagePushed` / `RequestRefused`).
ReplicateAttachment = 18,
}
impl Packet {
/// It, encoded: what goes in a frame.
pub fn encode(&self) -> Vec<u8> {
rmp_serde::to_vec(self).expect("packets always serialize")
}
/// Reads a packet, a frame's contents. See the [module](self) for what's
/// checked.
pub fn decode(bytes: &[u8]) -> Result<Packet, DecodeError> {
// A reader that grows its buffers as the data comes, never from a
// length the packet announces.
let mut deserializer = rmp_serde::Deserializer::new(Cursor::new(bytes));
let packet = Packet::deserialize(&mut deserializer)
.map_err(|error| DecodeError::Malformed(error.to_string()))?;
if deserializer.position() != bytes.len() as u64 {
return Err(DecodeError::TrailingBytes);
}
packet.check()?;
Ok(packet)
}
}
// The rules fields follow, for the `Check`s.
pub(crate) mod rules {
use super::DecodeError;
use crate::limits::{MAX_MESSAGE_ID, MAX_TIMESTAMP};
use crate::names;
/// Fails with `rule` unless `ok`.
pub fn require(ok: bool, field: &'static str, rule: &'static str) -> Result<(), DecodeError> {
if ok {
Ok(())
} else {
Err(DecodeError::Invalid { field, rule })
}
}
/// From `min` to `max`.
pub fn range(value: u64, min: u64, max: u64, field: &'static str) -> Result<(), DecodeError> {
require((min..=max).contains(&value), field, "out of range")
}
/// At most `max` items.
pub fn most(len: usize, max: usize, field: &'static str) -> Result<(), DecodeError> {
require(len <= max, field, "too many")
}
/// A topic or node name.
pub fn name(value: &str, field: &'static str) -> Result<(), DecodeError> {
require(names::is_valid_name(value), field, "must be a name")
}
/// A message id: 1 and up.
pub fn message_id(value: u64, field: &'static str) -> Result<(), DecodeError> {
range(value, 1, MAX_MESSAGE_ID, field)
}
/// When a message was pushed: milliseconds since 1970 UTC, 1 to 9999-12-31.
pub fn timestamp(value: u64, field: &'static str) -> Result<(), DecodeError> {
range(value, 1, MAX_TIMESTAMP, field)
}
/// Strictly increasing ids.
pub fn increasing(
ids: impl Iterator<Item = u64>,
field: &'static str,
) -> Result<(), DecodeError> {
let mut last = 0;
for id in ids {
require(id > last, field, "ids must be strictly increasing")?;
last = id;
}
Ok(())
}
}
@@ -0,0 +1,199 @@
//! Replication, between servers: at each check-in a peer (P) asks the
//! server (S) what it takes and has, then sends what it's missing,
//! messages first, then attachments (`OldSource/Design/Packets.md`,
//! "Replication"). Servers only ever send each other names: each has its
//! own ids.
use super::rules;
use super::{Attachment, Check, DecodeError};
use crate::limits::{
MAX_ATTACHMENT_PARTS, MAX_MESSAGE_ID, MAX_MESSAGES_PER_PACKET, MAX_MISSING_ATTACHMENTS,
MAX_NAMES_LIST_ENTRIES,
};
use crate::names;
use serde::{Deserialize, Serialize};
/// What the server takes from this peer, how far it is, and the
/// attachments it lacks.
///
/// `[15, []]`
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct SyncStateRequest {}
impl Check for SyncStateRequest {}
/// How far the server is in a topic/node pair.
///
/// `[topic, node, last_id]`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Head {
/// The topic.
pub topic: String,
/// The node.
pub node: String,
/// The highest message id it has (deleted ones included).
pub last_id: u64,
}
/// An attachment the server lacks, and where to go on from.
///
/// `[topic, node, message_id, next_part]`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MissingAttachment {
/// The topic.
pub topic: String,
/// The node.
pub node: String,
/// The message.
pub message_id: u64,
/// The next part it needs (it keeps what it got).
pub next_part: u64,
}
/// What the server takes from this peer, how far it is, and the
/// attachments it lacks: all a check-in needs.
///
/// `[16, [[topic...], [node...], [head...], [missing...]]]`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SyncState {
/// The topics it takes from this peer: names, and wildcards (it takes
/// the names they match, even those it doesn't have yet).
pub topics: Vec<String>,
/// The nodes it takes from this peer, the same way.
pub nodes: Vec<String>,
/// Its highest message id in each topic/node pair of those.
pub heads: Vec<Head>,
/// The attachments it lacks among those, `MAX_MISSING_ATTACHMENTS` at
/// most.
pub missing: Vec<MissingAttachment>,
}
impl Check for SyncState {
fn check(&self) -> Result<(), DecodeError> {
for (list, field) in [
(&self.topics, "SyncState.topics"),
(&self.nodes, "SyncState.nodes"),
] {
rules::most(list.len(), MAX_NAMES_LIST_ENTRIES, field)?;
for item in list {
rules::require(
names::is_valid_name_or_pattern(item),
field,
"must be a name or a pattern",
)?;
}
}
for head in &self.heads {
rules::name(&head.topic, "SyncState.heads.topic")?;
rules::name(&head.node, "SyncState.heads.node")?;
rules::range(head.last_id, 0, MAX_MESSAGE_ID, "SyncState.heads.last_id")?;
}
rules::most(
self.missing.len(),
MAX_MISSING_ATTACHMENTS,
"SyncState.missing",
)?;
for missing in &self.missing {
rules::name(&missing.topic, "SyncState.missing.topic")?;
rules::name(&missing.node, "SyncState.missing.node")?;
rules::message_id(missing.message_id, "SyncState.missing.message_id")?;
rules::range(
missing.next_part,
0,
MAX_ATTACHMENT_PARTS - 1,
"SyncState.missing.next_part",
)?;
}
Ok(())
}
}
/// A message as replication carries it.
///
/// `[id, pushed_at, data, attachment]`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReplicatedMessage {
/// Its id, as on its origin.
pub id: u64,
/// When it was pushed to its origin.
pub pushed_at: u64,
/// The message.
pub data: String,
/// Its attachment's size and SHA-256, if it has one: its parts come
/// later, by `ReplicateAttachment`.
pub attachment: Option<Attachment>,
}
/// Messages of a topic/node pair the server is missing, in id order.
///
/// `[17, [topic, node, [message...]]]`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReplicateMessages {
/// The topic.
pub topic: String,
/// The node.
pub node: String,
/// The messages, 1 to `MAX_MESSAGES_PER_PACKET`, ids strictly
/// increasing.
pub messages: Vec<ReplicatedMessage>,
}
impl Check for ReplicateMessages {
fn check(&self) -> Result<(), DecodeError> {
rules::name(&self.topic, "ReplicateMessages.topic")?;
rules::name(&self.node, "ReplicateMessages.node")?;
rules::require(
!self.messages.is_empty(),
"ReplicateMessages.messages",
"one at least",
)?;
rules::most(
self.messages.len(),
MAX_MESSAGES_PER_PACKET as usize,
"ReplicateMessages.messages",
)?;
rules::increasing(
self.messages.iter().map(|m| m.id),
"ReplicateMessages.messages",
)?;
for message in &self.messages {
rules::message_id(message.id, "ReplicateMessages.id")?;
rules::timestamp(message.pushed_at, "ReplicateMessages.pushed_at")?;
if let Some(attachment) = &message.attachment {
attachment.check()?;
}
}
Ok(())
}
}
/// An attachment the server is missing: the server answers `Continue` (or
/// refuses), the peer sends its parts from `from_part` to the last, the
/// server checks it all and answers `MessagePushed` with the message's id.
///
/// `[18, [topic, node, message_id, from_part]]`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReplicateAttachment {
/// The topic.
pub topic: String,
/// The node.
pub node: String,
/// The message.
pub message_id: u64,
/// The first part sent: the `next_part` the server listed.
pub from_part: u64,
}
impl Check for ReplicateAttachment {
fn check(&self) -> Result<(), DecodeError> {
rules::name(&self.topic, "ReplicateAttachment.topic")?;
rules::name(&self.node, "ReplicateAttachment.node")?;
rules::message_id(self.message_id, "ReplicateAttachment.message_id")?;
rules::range(
self.from_part,
0,
MAX_ATTACHMENT_PARTS - 1,
"ReplicateAttachment.from_part",
)
}
}
@@ -0,0 +1,76 @@
//! The connection itself: the server's welcome, refusals, and the go-ahead
//! for an attachment's parts.
use super::Check;
use super::DecodeError;
use super::rules;
use crate::error::{ErrorCode, MAX_REFUSAL_CODE};
use serde::{Deserialize, Serialize};
/// The server's first packet, once TLS is up and both ends' versions
/// matched (`frame::check_version()`): who this connection is, as the
/// server sees it.
///
/// `[1, [server, node]]`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Welcome {
/// The server's own name (its node).
pub server: String,
/// The node this connection writes as, from its certificate.
pub node: String,
}
impl Check for Welcome {
fn check(&self) -> Result<(), DecodeError> {
rules::name(&self.server, "Welcome.server")?;
rules::name(&self.node, "Welcome.node")
}
}
/// A request refused: the connection stays open.
///
/// `[2, [code, reason]]`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RequestRefused {
/// What kind of refusal, 1-99: what clients act on. Kept as a number,
/// a newer server may send one this version doesn't know.
pub code: u32,
/// Why, for logs and people.
pub reason: String,
}
impl RequestRefused {
/// A refusal with a known code (a refusal's, 1-99).
pub fn new(code: ErrorCode, reason: impl Into<String>) -> Self {
debug_assert!(code.is_refusal(), "{code} isn't a refusal's code");
RequestRefused {
code: code.code(),
reason: reason.into(),
}
}
/// Its code, if this version knows it.
pub fn error_code(&self) -> Option<ErrorCode> {
ErrorCode::from_code(self.code)
}
}
impl Check for RequestRefused {
fn check(&self) -> Result<(), DecodeError> {
rules::range(
self.code.into(),
1,
MAX_REFUSAL_CODE.into(),
"RequestRefused.code",
)
}
}
/// Send the attachment's parts now: the answer to a `PushMessage` or a
/// `ReplicateAttachment` with an attachment, when the server takes it.
///
/// `[3, []]`
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Continue {}
impl Check for Continue {}
@@ -0,0 +1,563 @@
//! Every packet: round trips, the exact bytes of a few, what decoding
//! refuses, and that no input makes it panic.
use bakashrot_proto::limits::{
ATTACHMENT_PART_SIZE, MAX_ATTACHMENT_SIZE, MAX_MESSAGE_ID, MAX_MESSAGES_PER_PACKET,
MAX_TIMESTAMP,
};
use bakashrot_proto::packets::*;
use bakashrot_proto::{Body, DecodeError, ErrorCode, Packet, PacketType};
fn message(id: u64) -> MessageEntry {
MessageEntry {
id,
pushed_at: 1_763_000_000_000 + id,
data: format!("{{\"n\":{id}}}"),
attachment: None,
}
}
fn attachment(size: u64) -> Attachment {
Attachment {
size,
sha256: [0xab; 32],
}
}
/// One packet of each type at least, with values at their limits here and
/// there.
fn samples() -> Vec<Packet> {
vec![
Welcome {
server: "server-1".into(),
node: "kitchen".into(),
}
.into(),
RequestRefused::new(ErrorCode::UnknownName, "Unknown topic 'nope'").into(),
Continue {}.into(),
PushMessage {
topic: "logs".into(),
data: "é€ \u{1F600} {\"a\":[1,2]}".into(),
attachment: None,
}
.into(),
PushMessage {
topic: "sensors".into(),
data: String::new(),
attachment: Some(attachment(MAX_ATTACHMENT_SIZE)),
}
.into(),
MessagePushed {
message_id: MAX_MESSAGE_ID,
}
.into(),
GetMessages {
topic: "logs".into(),
node: "kitchen".into(),
after: Some(0),
limit: MAX_MESSAGES_PER_PACKET,
}
.into(),
GetMessages {
topic: "logs".into(),
node: "kitchen".into(),
after: None,
limit: 1,
}
.into(),
Messages {
more: true,
messages: (1..=20)
.map(|i| MessageEntry {
attachment: (i % 3 == 0).then_some(StoredAttachment {
size: i,
ready: i % 2 == 0,
}),
..message(i * 3)
})
.collect(),
}
.into(),
Messages {
more: false,
messages: vec![],
}
.into(),
GetAttachment {
topic: "sensors".into(),
node: "kitchen".into(),
message_id: 4,
from_part: 2,
}
.into(),
attachment(2 * ATTACHMENT_PART_SIZE + 10).into(),
AttachmentPart {
data: vec![0x5a; ATTACHMENT_PART_SIZE as usize],
}
.into(),
AttachmentPart { data: vec![1] }.into(),
ListNames {
kind: NameKind::Topic,
}
.into(),
NamesList {
kind: NameKind::Node,
truncated: true,
names: vec!["kitchen".into(), "garage-1".into()],
}
.into(),
Query {
sql: "SELECT * FROM messages WHERE topic = 'logs'".into(),
}
.into(),
QueryResult {
json: r#"{"columns":["a"],"rows":[[1],[null]]}"#.into(),
}
.into(),
SyncStateRequest {}.into(),
SyncState {
topics: vec!["logs".into(), "sensors.*".into()],
nodes: vec!["*".into()],
heads: vec![
Head {
topic: "logs".into(),
node: "kitchen".into(),
last_id: 0,
},
Head {
topic: "sensors.a".into(),
node: "garage-1".into(),
last_id: 123_456_789,
},
],
missing: vec![MissingAttachment {
topic: "logs".into(),
node: "kitchen".into(),
message_id: 11,
next_part: 3,
}],
}
.into(),
ReplicateMessages {
topic: "logs".into(),
node: "kitchen".into(),
messages: vec![
ReplicatedMessage {
id: 10,
pushed_at: 1,
data: "not JSON".into(),
attachment: None,
},
ReplicatedMessage {
id: 11,
pushed_at: MAX_TIMESTAMP,
data: "{}".into(),
attachment: Some(attachment(5)),
},
],
}
.into(),
ReplicateAttachment {
topic: "logs".into(),
node: "kitchen".into(),
message_id: 11,
from_part: 3,
}
.into(),
]
}
/// Encodes anything serializable as a packet's body, `[type, body]`: to make
/// packets that break rules or have the wrong shape.
fn raw(packet_type: PacketType, body: impl serde::Serialize) -> Vec<u8> {
rmp_serde::to_vec(&(packet_type.id(), body)).unwrap()
}
fn refused(bytes: &[u8]) -> DecodeError {
Packet::decode(bytes).expect_err("must be refused")
}
fn invalid(bytes: &[u8]) -> bool {
matches!(refused(bytes), DecodeError::Invalid { .. })
}
fn malformed(bytes: &[u8]) -> bool {
matches!(refused(bytes), DecodeError::Malformed(_))
}
#[test]
fn every_type_has_a_sample() {
let samples = samples();
for packet_type in PacketType::ALL {
assert!(
samples.iter().any(|p| p.packet_type() == *packet_type),
"no sample of {}",
packet_type.name()
);
}
for (index, packet_type) in PacketType::ALL.iter().enumerate() {
assert_eq!(
usize::from(packet_type.id()),
index + 1,
"ids follow each other"
);
assert_eq!(
PacketType::from_id(packet_type.id().into()),
Some(*packet_type)
);
}
}
#[test]
fn round_trips() {
for packet in samples() {
let bytes = packet.encode();
assert_eq!(
Packet::decode(&bytes),
Ok(packet.clone()),
"{}",
packet.packet_type().name()
);
assert_eq!(bytes[1], packet.packet_type().id(), "the type comes first");
}
}
#[test]
fn golden_bytes() {
// [4, ["logs", "{}", nil]]: what protocol.md shows.
let push = PushMessage {
topic: "logs".into(),
data: "{}".into(),
attachment: None,
};
assert_eq!(
push.encode(),
[
0x92, 0x04, 0x93, 0xa4, b'l', b'o', b'g', b's', 0xa2, b'{', b'}', 0xc0
]
);
assert_eq!(Continue {}.encode(), [0x92, 0x03, 0x90]);
assert_eq!(
MessagePushed { message_id: 300 }.encode(),
[0x92, 0x05, 0x91, 0xcd, 0x01, 0x2c]
);
// Bytes are binaries, not arrays of numbers.
assert_eq!(
AttachmentPart { data: vec![7, 8] }.encode(),
[0x92, 0x0a, 0x91, 0xc4, 0x02, 7, 8]
);
let sha = attachment(1).encode();
assert_eq!(sha[..6], [0x92, 0x09, 0x92, 0x01, 0xc4, 0x20]);
}
#[test]
fn every_truncation_is_refused() {
for packet in samples() {
let bytes = packet.encode();
// The 1 MB part's prefixes are all alike past its header.
let step = if bytes.len() > 4096 { 4093 } else { 1 };
for len in (0..bytes.len()).step_by(step) {
assert!(
Packet::decode(&bytes[..len]).is_err(),
"{} cut at {len}",
packet.packet_type().name()
);
}
}
}
#[test]
fn trailing_bytes_are_refused() {
for packet in samples() {
let mut bytes = packet.encode();
bytes.push(0);
assert_eq!(Packet::decode(&bytes), Err(DecodeError::TrailingBytes));
}
}
#[test]
fn shapes() {
// Unknown types, not a packet.
assert!(malformed(&raw_unknown(0)));
assert!(malformed(&raw_unknown(19)));
assert!(malformed(&raw_unknown(255)));
assert!(malformed(&[0x90]), "empty");
assert!(malformed(&[0x91, 0x05]), "no body");
assert!(malformed(&[0x05]), "not an array");
assert!(malformed(&[0x93, 0x03, 0x90, 0x90]), "one value too many");
// A field missing, one too many.
assert!(malformed(&raw(PacketType::MessagePushed, ())));
assert!(malformed(&raw(PacketType::MessagePushed, ((),))));
assert!(malformed(&raw(PacketType::MessagePushed, (1u64, 2u64))));
assert!(malformed(&raw(PacketType::Continue, (1u64,))));
// The wrong types.
assert!(malformed(&raw(PacketType::MessagePushed, ("1",))));
assert!(malformed(&raw(PacketType::MessagePushed, (-1i64,))));
assert!(malformed(&raw(
PacketType::Messages,
(1u8, Vec::<u8>::new())
)));
assert!(malformed(&raw(PacketType::ListNames, (3u8,))), "kind 3");
assert!(malformed(&raw(PacketType::ListNames, (0u8,))), "kind 0");
assert!(
malformed(&raw(
PacketType::Attachment,
(1u64, serde_bytes::Bytes::new(&[0; 31]))
)),
"a 31-byte SHA-256"
);
// A strings that isn't UTF-8: "ab" -> 0xc3 0x28.
let mut bytes = Query { sql: "ab".into() }.encode();
let at = bytes.len() - 2;
bytes[at] = 0xc3;
bytes[at + 1] = 0x28;
assert!(malformed(&bytes));
// An integer written as a signed one, still taken.
assert_eq!(
Packet::decode(&raw(PacketType::MessagePushed, (300i64,))),
Ok(MessagePushed { message_id: 300 }.into())
);
// A binary announcing 4 GiB: refused without allocating it.
assert!(malformed(&[
0x92, 0x0a, 0x91, 0xc6, 0xff, 0xff, 0xff, 0xff, 0x00
]));
assert!(malformed(&[
0x92, 0x07, 0x92, 0xc3, 0xdd, 0xff, 0xff, 0xff, 0xff
]));
}
fn raw_unknown(id: u8) -> Vec<u8> {
rmp_serde::to_vec(&(id, ())).unwrap()
}
#[test]
fn ranges() {
assert!(invalid(&raw(PacketType::MessagePushed, (0u64,))));
assert!(invalid(&raw(PacketType::MessagePushed, (1u64 << 63,))));
// Ids end where a server's 43 bits do.
assert!(Packet::decode(&raw(PacketType::MessagePushed, (MAX_MESSAGE_ID,))).is_ok());
assert!(invalid(&raw(
PacketType::MessagePushed,
(MAX_MESSAGE_ID + 1,)
)));
let refusal = |code: u32| raw(PacketType::RequestRefused, (code, "x"));
assert!(
Packet::decode(&refusal(99)).is_ok(),
"an unknown refusal code still decodes"
);
assert!(invalid(&refusal(0)));
assert!(invalid(&refusal(100)));
let get = |after: Option<u64>, limit: u32| {
GetMessages {
topic: "t".into(),
node: "n".into(),
after,
limit,
}
.encode()
};
assert!(Packet::decode(&get(None, 1)).is_ok());
assert!(invalid(&get(None, 0)));
assert!(invalid(&get(Some(0), 10_001)));
assert!(invalid(&get(Some(1 << 63), 1)));
assert!(Packet::decode(&get(Some(MAX_MESSAGE_ID), 1)).is_ok());
assert!(invalid(&get(Some(MAX_MESSAGE_ID + 1), 1)));
let times = |pushed_at| {
Messages {
more: false,
messages: vec![MessageEntry {
pushed_at,
..message(1)
}],
}
.encode()
};
assert!(Packet::decode(&times(MAX_TIMESTAMP)).is_ok());
assert!(invalid(&times(0)));
assert!(invalid(&times(MAX_TIMESTAMP + 1)));
let sizes = |size| {
PushMessage {
topic: "logs".into(),
data: String::new(),
attachment: Some(attachment(size)),
}
.encode()
};
assert!(invalid(&sizes(0)));
assert!(invalid(&sizes(MAX_ATTACHMENT_SIZE + 1)));
let part = |len| AttachmentPart { data: vec![0; len] }.encode();
assert!(invalid(&part(0)));
assert!(invalid(&part(ATTACHMENT_PART_SIZE as usize + 1)));
}
#[test]
fn parts_of_an_attachment() {
let attachment = attachment(2 * ATTACHMENT_PART_SIZE + 10);
assert_eq!(attachment.part_count(), 3);
assert_eq!(attachment.part_len(0), ATTACHMENT_PART_SIZE);
assert_eq!(attachment.part_len(2), 10);
assert_eq!(attachment.part_len(3), 0);
}
#[test]
fn ids_in_order() {
let messages = |ids: &[u64]| {
Messages {
more: false,
messages: ids.iter().map(|id| message(*id)).collect(),
}
.encode()
};
assert!(Packet::decode(&messages(&[1, 2, 5])).is_ok());
assert!(invalid(&messages(&[1, 1])));
assert!(invalid(&messages(&[3, 2])));
assert!(invalid(&messages(&[0])));
let replicated = |ids: &[u64]| {
ReplicateMessages {
topic: "logs".into(),
node: "kitchen".into(),
messages: ids
.iter()
.map(|id| ReplicatedMessage {
id: *id,
pushed_at: 1,
data: String::new(),
attachment: None,
})
.collect(),
}
.encode()
};
assert!(invalid(&replicated(&[2, 1])));
assert!(invalid(&replicated(&[])));
}
#[test]
fn too_many_items() {
let too_many = Messages {
more: false,
messages: (1..=u64::from(MAX_MESSAGES_PER_PACKET) + 1)
.map(message)
.collect(),
};
assert!(invalid(&too_many.encode()));
let missing = SyncState {
topics: vec![],
nodes: vec![],
heads: vec![],
missing: (1..=257)
.map(|id| MissingAttachment {
topic: "t".into(),
node: "n".into(),
message_id: id,
next_part: 0,
})
.collect(),
};
assert!(invalid(&missing.encode()));
}
#[test]
fn names_everywhere() {
for bad in ["12", "", "a b", "é"] {
let get = GetMessages {
topic: bad.into(),
node: "kitchen".into(),
after: None,
limit: 1,
};
assert!(invalid(&get.encode()), "{bad:?}");
let push = PushMessage {
topic: bad.into(),
data: String::new(),
attachment: None,
};
assert!(invalid(&push.encode()), "{bad:?}");
let replicate = ReplicateMessages {
topic: "logs".into(),
node: bad.into(),
messages: vec![ReplicatedMessage {
id: 1,
pushed_at: 1,
data: String::new(),
attachment: None,
}],
};
assert!(invalid(&replicate.encode()), "{bad:?}");
let list = NamesList {
kind: NameKind::Topic,
truncated: false,
names: vec![bad.into()],
};
assert!(invalid(&list.encode()), "{bad:?}");
}
let state = |topic: &str| {
SyncState {
topics: vec![topic.into()],
nodes: vec![],
heads: vec![],
missing: vec![],
}
.encode()
};
assert!(Packet::decode(&state("*")).is_ok());
assert!(Packet::decode(&state("logs")).is_ok());
assert!(invalid(&state("12")));
assert!(invalid(&state("a b*")));
let welcome = Welcome {
server: "s".into(),
node: "7".into(),
};
assert!(invalid(&welcome.encode()));
}
/// xorshift64*, enough to make bytes that look like anything.
struct Random(u64);
impl Random {
fn next(&mut self) -> u64 {
self.0 ^= self.0 >> 12;
self.0 ^= self.0 << 25;
self.0 ^= self.0 >> 27;
self.0.wrapping_mul(0x2545_f491_4f6c_dd1d)
}
}
#[test]
fn nothing_makes_it_panic() {
let mut random = Random(0x9e37_79b9_7f4a_7c15);
// Random bytes, often starting like a packet.
for round in 0..200_000 {
let len = (random.next() % 48) as usize;
let mut bytes: Vec<u8> = (0..len).map(|_| random.next() as u8).collect();
if round % 2 == 0 && bytes.len() > 2 {
bytes[0] = 0x92;
bytes[1] = 1 + (bytes[1] % 18);
bytes[2] = 0x90 | (bytes[2] & 0x0f);
}
let _ = Packet::decode(&bytes);
}
// Every sample with bytes changed here and there.
let samples: Vec<Vec<u8>> = samples()
.iter()
.map(Packet::encode)
.filter(|bytes| bytes.len() < 4096)
.collect();
for _ in 0..50_000 {
let mut bytes = samples[(random.next() % samples.len() as u64) as usize].clone();
for _ in 0..1 + random.next() % 3 {
let at = (random.next() % bytes.len() as u64) as usize;
bytes[at] = random.next() as u8;
}
let _ = Packet::decode(&bytes);
}
}
+31
View File
@@ -0,0 +1,31 @@
[package]
name = "bakashrot-server"
description = "BakaShrot's server: TLS, identities from certificates, the requests of protocol 7 on the storage."
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
authors.workspace = true
repository.workspace = true
publish.workspace = true
[dependencies]
bakashrot-proto = { path = "../bakashrot-proto", features = ["tokio"] }
bakashrot-pki = { path = "../bakashrot-pki" }
bakashrot-config = { path = "../bakashrot-config" }
bakashrot-storage = { path = "../bakashrot-storage" }
tokio = { version = "1.54.1", features = ["rt-multi-thread", "net", "time", "macros", "signal", "io-util", "sync"] }
tokio-rustls = { version = "0.26.6", default-features = false }
tokio-util = { version = "0.7.20", features = ["codec"] }
futures-util = { version = "0.3.34", default-features = false, features = ["sink"] }
bytes = "1.12.1"
# The attachments' SHA-256: the TLS one's (aws-lc), no other crate.
aws-lc-rs = "1.19.0"
tracing = "0.1.44"
tracing-subscriber = { version = "0.3.23", default-features = false, features = ["fmt", "std", "ansi"] }
[lints]
workspace = true
[dev-dependencies]
bakashrot-client = { path = "../bakashrot-client" }
@@ -0,0 +1,519 @@
//! One connection: TLS, the versions, who it is, then its requests, one at
//! a time (`Source/docs/protocol.md`).
use crate::writer::Write;
use crate::{Shared, now};
use aws_lc_rs::digest;
use bakashrot_config::Permissions;
use bakashrot_pki::Identity;
use bakashrot_proto::limits::{MAX_MESSAGE_SIZE, MAX_NAMES_LIST_ENTRIES, MAX_PACKET_SIZE};
use bakashrot_proto::names::names_equal;
use bakashrot_proto::packets::{
Attachment, AttachmentPart, Continue, GetAttachment, GetMessages, ListNames, MessagePushed,
Messages, NameKind, NamesList, PushMessage, Query, QueryResult, RequestRefused, Welcome,
};
use bakashrot_proto::{ErrorCode, Packet, PacketType, frame};
use bakashrot_storage::AttachmentState;
use futures_util::{SinkExt, StreamExt};
use std::collections::VecDeque;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
use tokio::time::timeout;
use tokio_rustls::server::TlsStream;
use tokio_util::codec::{Framed, LengthDelimitedCodec};
use tracing::{debug, info};
/// How long TLS and the versions may take.
const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
/// How long a connection may stay silent between requests.
const IDLE_TIMEOUT: Duration = Duration::from_secs(300);
/// How long an attachment's next part may take to come.
const PART_TIMEOUT: Duration = Duration::from_secs(30);
/// An upload's parts given to the writer and not written yet, at most: the
/// next ones wait (the client with them, through TCP).
const PARTS_IN_FLIGHT: usize = 4;
type Frames = Framed<TlsStream<TcpStream>, LengthDelimitedCodec>;
/// Serves one connection until it ends, logging why.
pub(crate) async fn handle(shared: Arc<Shared>, tcp: TcpStream, peer: SocketAddr) {
match serve(&shared, tcp).await {
Ok(node) => debug!("{peer} ({node}): closed"),
Err(why) => info!("{peer}: {why}"),
}
}
/// Who it is once checked: its node, its certificate's serial (for later
/// revocations), what it may do.
struct Peer {
node: String,
serial: Vec<u8>,
permissions: Permissions,
}
async fn serve(shared: &Arc<Shared>, tcp: TcpStream) -> Result<String, String> {
tcp.set_nodelay(true).map_err(|error| error.to_string())?;
let (mut frames, peer) = timeout(HANDSHAKE_TIMEOUT, open(shared, tcp))
.await
.map_err(|_| "too slow to connect".to_owned())??;
debug!("{} connected", peer.node);
loop {
let bytes = match timeout(IDLE_TIMEOUT, frames.next()).await {
Err(_) => return Err(format!("{}: idle too long", peer.node)),
Ok(None) => return Ok(peer.node),
Ok(Some(bytes)) => bytes.map_err(|error| format!("{}: {error}", peer.node))?,
};
let revoked = shared
.revocations
.read()
.map_or(true, |revocations| revocations.revokes_serial(&peer.serial));
if revoked {
return Err(format!("{}: its certificate was revoked", peer.node));
}
let packet = Packet::decode(&bytes).map_err(|error| format!("{}: {error}", peer.node))?;
let failed = |why: String| format!("{}: {why}", peer.node);
let answer = match packet {
Packet::PushMessage(push) => self::push(shared, &peer, &mut frames, push)
.await
.map_err(failed)?,
Packet::GetAttachment(get) => {
match get_attachment(shared, &peer, &mut frames, get)
.await
.map_err(failed)?
{
Some(refusal) => refusal,
None => continue,
}
}
Packet::GetMessages(get) => get_messages(shared, &peer, get).await,
Packet::ListNames(list) => list_names(shared, &peer, list).await,
Packet::Query(query) => self::query(shared, &peer, query).await,
other if is_request(other.packet_type()) => RequestRefused::new(
ErrorCode::InvalidRequest,
format!("{} isn't answered yet", other.packet_type().name()),
)
.into(),
other => {
return Err(format!(
"{}: sent {}, not a request",
peer.node,
other.packet_type().name()
));
}
};
send(&mut frames, answer)
.await
.map_err(|error| format!("{}: {error}", peer.node))?;
}
}
/// TLS, the versions, the identity, the welcome (or the refusal).
async fn open(shared: &Arc<Shared>, tcp: TcpStream) -> Result<(Frames, Peer), String> {
let mut stream = shared
.acceptor
.accept(tcp)
.await
.map_err(|error| format!("TLS: {error}"))?;
stream
.write_all(&frame::version_bytes())
.await
.map_err(|error| error.to_string())?;
stream.flush().await.map_err(|error| error.to_string())?;
let mut theirs = [0; frame::VERSION_SIZE];
stream
.read_exact(&mut theirs)
.await
.map_err(|error| error.to_string())?;
frame::check_version(theirs).map_err(|version| format!("speaks protocol {version}"))?;
let (_, connection) = stream.get_ref();
let certificate = connection
.peer_certificates()
.and_then(<[_]>::first)
.map(|certificate| certificate.to_vec())
.unwrap_or_default();
let identity = Identity::from_certificate(&certificate).map_err(|error| error.to_string())?;
let serial = bakashrot_pki::serial(&certificate).map_err(|error| error.to_string())?;
let mut frames = Framed::new(stream, frame::codec(MAX_PACKET_SIZE));
let Some(permissions) = shared.config.permissions(&identity.roles) else {
let refused = RequestRefused::new(
ErrorCode::NotAllowed,
format!(
"none of {}'s roles ({}) is allowed on this server",
identity.name,
identity.roles.join(", ")
),
);
let _ = send(&mut frames, refused.into()).await;
return Err(format!(
"{}: refused, none of its roles is allowed",
identity.name
));
};
let welcome = Welcome {
server: shared.name.clone(),
node: identity.name.clone(),
};
send(&mut frames, welcome.into())
.await
.map_err(|error| error.to_string())?;
Ok((
frames,
Peer {
node: identity.name,
serial,
permissions,
},
))
}
/// A push, with its attachment's parts if it has one. An error closes the
/// connection.
async fn push(
shared: &Arc<Shared>,
peer: &Peer,
frames: &mut Frames,
push: PushMessage,
) -> Result<Packet, String> {
if !shared.config.server.has_topic(&push.topic) {
return Ok(refused(
ErrorCode::UnknownName,
format!("unknown topic '{}'", push.topic),
));
}
if !peer.permissions.can_push(&push.topic) {
return Ok(refused(
ErrorCode::NotAllowed,
format!("{} may not push to '{}'", peer.node, push.topic),
));
}
if push.data.len() > MAX_MESSAGE_SIZE {
return Ok(refused(
ErrorCode::TooBig,
format!(
"a message of {} bytes: {MAX_MESSAGE_SIZE} at most",
push.data.len()
),
));
}
let PushMessage {
topic,
data,
attachment,
} = push;
let Some(attachment) = attachment else {
let write = Write::Push {
topic,
node: peer.node.clone(),
pushed_at: now(),
data,
};
return Ok(pushed(shared.pushes.send(write).await));
};
let max = shared.config.server.max_attachment_size;
if attachment.size > max {
return Ok(refused(
ErrorCode::TooBig,
format!(
"an attachment of {} bytes: {max} at most on this server",
attachment.size
),
));
}
let start = Write::StartUpload {
size: attachment.size,
sha256: attachment.sha256,
};
let upload = match shared.pushes.send(start).await {
Ok(upload) => upload,
Err(refusal) => return Ok(refusal.into()),
};
let received = match send(frames, Continue {}.into()).await {
Ok(()) => receive_parts(shared, frames, upload, &attachment).await,
Err(error) => Err(error.to_string()),
};
let refusal = match received {
Ok(None) => {
let write = Write::PushWithUpload {
upload,
topic,
node: peer.node.clone(),
pushed_at: now(),
data,
};
match shared.pushes.send(write).await {
Ok(message_id) => return Ok(MessagePushed { message_id }.into()),
Err(refusal) => Ok(refusal),
}
}
Ok(Some(refusal)) => Ok(refusal),
Err(why) => Err(why),
};
// Not pushed: the upload goes (queued after its parts).
drop(shared.pushes.send(Write::CancelUpload { upload }));
refusal.map(Packet::from)
}
/// Reads every part of an upload, has the writer store them while the next
/// ones come, checks the SHA-256: the refusal if one is due (the parts all
/// read even then), an error if the connection must close.
async fn receive_parts(
shared: &Arc<Shared>,
frames: &mut Frames,
upload: u64,
attachment: &Attachment,
) -> Result<Option<RequestRefused>, String> {
let mut sha256 = digest::Context::new(&digest::SHA256);
let mut writing = VecDeque::new();
let mut refusal = None;
for part in 0..attachment.part_count() {
let bytes = match timeout(PART_TIMEOUT, frames.next()).await {
Err(_) => return Err(format!("part {part} of an attachment: too slow")),
Ok(None) => return Err(format!("closed at part {part} of an attachment")),
Ok(Some(bytes)) => bytes.map_err(|error| error.to_string())?,
};
let Packet::AttachmentPart(AttachmentPart { data }) =
Packet::decode(&bytes).map_err(|error| error.to_string())?
else {
return Err(format!(
"sent something else than part {part} of an attachment"
));
};
if refusal.is_some() {
continue;
}
let expected = attachment.part_len(part);
if data.len() as u64 != expected {
refusal = Some(RequestRefused::new(
ErrorCode::InvalidRequest,
format!("part {part}: {} bytes, {expected} expected", data.len()),
));
continue;
}
sha256.update(&data);
writing.push_back(shared.pushes.send(Write::Part { upload, part, data }));
if writing.len() >= PARTS_IN_FLIGHT
&& let Some(written) = writing.pop_front()
&& let Err(refused) = written.await
{
refusal = Some(refused);
}
}
for written in writing {
if let Err(refused) = written.await {
refusal.get_or_insert(refused);
}
}
if refusal.is_none() && sha256.finish().as_ref() != attachment.sha256 {
refusal = Some(RequestRefused::new(
ErrorCode::DataMismatch,
"the attachment doesn't match its SHA-256",
));
}
Ok(refusal)
}
/// A message's attachment: its size and SHA-256, then its parts from
/// `from_part`, sent here; or the refusal to send. An error (a part that
/// can't be read, the connection) closes the connection: the client asks
/// again from the part it lacks.
async fn get_attachment(
shared: &Arc<Shared>,
peer: &Peer,
frames: &mut Frames,
get: GetAttachment,
) -> Result<Option<Packet>, String> {
if !peer.permissions.can_read(&get.topic) {
return Ok(Some(refused(
ErrorCode::NotAllowed,
format!("{} may not read '{}'", peer.node, get.topic),
)));
}
if !shared.config.server.has_topic(&get.topic) {
return Ok(Some(refused(
ErrorCode::UnknownName,
format!("unknown topic '{}'", get.topic),
)));
}
let message = format!("{}:{}#{}", get.topic, get.node, get.message_id);
let GetAttachment {
topic,
node,
message_id,
from_part,
} = get;
let found = shared
.read(move |reader| reader.attachment(&topic, &node, message_id))
.await;
let stored = match found {
Ok(Some(stored)) => stored,
Ok(None) => {
return Ok(Some(refused(
ErrorCode::NotFound,
format!("no attachment for {message}"),
)));
}
Err(refusal) => return Ok(Some(refusal.into())),
};
let not_here = match stored.state {
AttachmentState::Ready => None,
AttachmentState::TooBig => Some((
ErrorCode::TooBig,
"bigger than this server keeps: get it from another one",
)),
AttachmentState::Replicating => Some((ErrorCode::NotReady, "isn't on this server yet")),
AttachmentState::Uploading | AttachmentState::Deleting => {
Some((ErrorCode::NotFound, "isn't there any more"))
}
};
if let Some((code, why)) = not_here {
return Ok(Some(refused(
code,
format!("the attachment of {message} {why}"),
)));
}
let attachment = Attachment {
size: stored.size,
sha256: stored.sha256,
};
let count = attachment.part_count();
if from_part >= count {
return Ok(Some(refused(
ErrorCode::InvalidRequest,
format!("from part {from_part}: the attachment of {message} has {count}"),
)));
}
send(frames, attachment.into())
.await
.map_err(|error| error.to_string())?;
for part in from_part..count {
let data = shared
.read(move |reader| reader.read_part(stored.id, part))
.await
.map_err(|refusal| format!("part {part} of {message}: {}", refusal.reason))?;
send(frames, AttachmentPart { data }.into())
.await
.map_err(|error| error.to_string())?;
}
Ok(None)
}
/// A push's answer.
fn pushed(outcome: crate::writer::Outcome) -> Packet {
match outcome {
Ok(message_id) => MessagePushed { message_id }.into(),
Err(refusal) => refusal.into(),
}
}
async fn get_messages(shared: &Arc<Shared>, peer: &Peer, get: GetMessages) -> Packet {
if !peer.permissions.can_read(&get.topic) {
return refused(
ErrorCode::NotAllowed,
format!("{} may not read '{}'", peer.node, get.topic),
);
}
if !shared.config.server.has_topic(&get.topic) {
return refused(
ErrorCode::UnknownName,
format!("unknown topic '{}'", get.topic),
);
}
let GetMessages {
topic,
node,
after,
limit,
} = get;
// Its own node is known even before its first push.
let own = names_equal(&node, &peer.node);
match shared
.read(move |reader| reader.messages(&topic, &node, after, limit))
.await
{
Ok(messages) => messages.into(),
Err(refused) if own && refused.code == ErrorCode::UnknownName.code() => Messages {
more: false,
messages: Vec::new(),
}
.into(),
Err(refused) => refused.into(),
}
}
/// Topics: the server's, those it may push to or read unless it may query
/// (queries read everything). Nodes: every one with messages.
async fn list_names(shared: &Arc<Shared>, peer: &Peer, list: ListNames) -> Packet {
let mut names = match list.kind {
NameKind::Topic => shared
.config
.server
.topics
.iter()
.filter(|topic| {
peer.permissions.can_query()
|| peer.permissions.can_push(topic)
|| peer.permissions.can_read(topic)
})
.cloned()
.collect(),
NameKind::Node => match shared.read(|reader| reader.nodes()).await {
Ok(nodes) => nodes,
Err(refused) => return refused.into(),
},
};
let truncated = names.len() > MAX_NAMES_LIST_ENTRIES;
names.truncate(MAX_NAMES_LIST_ENTRIES);
NamesList {
kind: list.kind,
truncated,
names,
}
.into()
}
async fn query(shared: &Arc<Shared>, peer: &Peer, query: Query) -> Packet {
if !peer.permissions.can_query() {
return refused(
ErrorCode::NotAllowed,
format!("{} may not run queries", peer.node),
);
}
match shared.query(query.sql).await {
Ok(json) => QueryResult { json }.into(),
Err(refused) => refused.into(),
}
}
fn refused(code: ErrorCode, reason: String) -> Packet {
RequestRefused::new(code, reason).into()
}
/// The packets a client or a peer sends: the others are answers.
fn is_request(kind: PacketType) -> bool {
matches!(
kind,
PacketType::PushMessage
| PacketType::GetMessages
| PacketType::GetAttachment
| PacketType::ListNames
| PacketType::Query
| PacketType::SyncStateRequest
| PacketType::ReplicateMessages
| PacketType::ReplicateAttachment
)
}
async fn send(frames: &mut Frames, packet: Packet) -> std::io::Result<()> {
frames.send(bytes::Bytes::from(packet.encode())).await
}
+277
View File
@@ -0,0 +1,277 @@
//! BakaShrot's server: takes TLS connections from the CA's clients and
//! peers, knows each by its certificate (its node, its roles), and answers
//! their requests from the database.
//!
//! - [`Server::start`]: reads the certificates, opens the database, starts
//! the writer's thread.
//! - [`Server::serve`]: takes connections, a task each
//! (`connection.rs`); pushes go to the writer's thread (`writer.rs`),
//! reads and queries to pools of connections.
//! - [`Server::watch_revocations`]: reloads the CRL file when it changes;
//! a revoked certificate's connection is dropped at its next request.
//! - [`Server::apply_retention`]: deletes messages past their topic's age
//! (`retention.rs`).
//!
//! What it answers so far: pushes and their attachments, messages,
//! attachments, names and queries. Replication comes with step 11
//! (`../../revamp.md`, "Plan").
mod connection;
mod retention;
mod writer;
use bakashrot_config::Config;
use bakashrot_pki::{Revocations, SharedRevocations, summarize, tls};
use bakashrot_proto::ErrorCode;
use bakashrot_proto::packets::RequestRefused;
use bakashrot_storage::{Database, QueryRunner, Reader};
use std::net::SocketAddr;
use std::path::Path;
use std::sync::{Arc, Mutex};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tokio::net::TcpListener;
use tokio_rustls::TlsAcceptor;
use tracing::{info, warn};
use writer::Pushes;
/// How often the CRL file is looked at.
const CRL_POLL: Duration = Duration::from_secs(5);
/// How often the WAL is checkpointed.
const CHECKPOINT_INTERVAL: Duration = Duration::from_secs(1);
/// A server, ready to take connections.
#[derive(Clone)]
pub struct Server {
shared: Arc<Shared>,
}
/// What every connection uses.
struct Shared {
config: Config,
/// The server's own name: its certificate's.
name: String,
acceptor: TlsAcceptor,
revocations: SharedRevocations,
/// The CA's certificate, to check CRLs with.
ca: String,
database: Database,
pushes: Pushes,
/// Read connections not in use.
readers: Mutex<Vec<Reader>>,
/// Query connections not in use.
queries: Mutex<Vec<QueryRunner>>,
}
impl Server {
/// Reads the server's certificates and CRL, opens its database, starts
/// its writer. Errors say which file and why.
pub fn start(config: Config) -> Result<Server, String> {
let server = &config.server;
let ca = read(&server.ca)?;
let certificate = read(&server.certificate)?;
let key = read(&server.key)?;
let name = summarize(&certificate)
.ok()
.and_then(|summary| summary.identity)
.map(|identity| identity.name)
.ok_or_else(|| {
format!(
"{}: not a BakaShrot certificate",
server.certificate.display()
)
})?;
let revocations = load_revocations(server.crl.as_deref(), &ca)?.shared();
let tls = tls::server_config(&ca, &certificate, &key, revocations.clone())
.map_err(|error| format!("the server's TLS: {error}"))?;
let database = Database::open(&server.database, server.synchronous)
.map_err(|error| error.to_string())?;
let pushes = Pushes::start(database.writer().map_err(|error| error.to_string())?)
.map_err(|error| format!("the writer's thread: {error}"))?;
start_checkpoints(&database)?;
Ok(Server {
shared: Arc::new(Shared {
name,
acceptor: TlsAcceptor::from(tls),
revocations,
ca,
database,
pushes,
readers: Mutex::new(Vec::new()),
queries: Mutex::new(Vec::new()),
config,
}),
})
}
/// The server's name: its certificate's.
pub fn name(&self) -> &str {
&self.shared.name
}
/// Where the config says to listen.
pub fn listen(&self) -> SocketAddr {
self.shared.config.server.listen
}
/// Takes connections on `listener`, each in a task of its own, until
/// the listener fails.
pub async fn serve(&self, listener: TcpListener) -> std::io::Result<()> {
loop {
let (tcp, peer) = listener.accept().await?;
tokio::spawn(connection::handle(self.shared.clone(), tcp, peer));
}
}
/// Reloads the CRL file whenever it changes (its time or size, looked
/// at every few seconds). A CRL that can't be read or isn't the CA's is
/// refused: the previous one stays. Never returns.
pub async fn watch_revocations(&self) {
let Some(path) = self.shared.config.server.crl.clone() else {
return std::future::pending().await;
};
let mut seen = stamp(&path);
loop {
tokio::time::sleep(CRL_POLL).await;
let now = stamp(&path);
if now != seen {
seen = now;
match self.reload_revocations() {
Ok(count) => info!("{}: reloaded, {count} revoked", path.display()),
Err(error) => warn!("{error}: the previous CRL stays"),
}
}
}
}
/// Deletes each topic's messages past its age (`[retention]`), then
/// their attachments: right away, then every `retention_interval`.
/// Never returns.
pub async fn apply_retention(&self) {
retention::run(&self.shared).await
}
/// Reloads the CRL file now: how many certificates it revokes.
pub fn reload_revocations(&self) -> Result<usize, String> {
let shared = &self.shared;
let revocations = load_revocations(shared.config.server.crl.as_deref(), &shared.ca)?;
let count = revocations.len();
// A poisoned lock: the TLS checks refuse everyone, replace it all.
match shared.revocations.write() {
Ok(mut current) => *current = revocations,
Err(poisoned) => *poisoned.into_inner() = revocations,
}
Ok(count)
}
}
impl Shared {
/// Runs `read` on a read connection, off the async threads.
async fn read<T: Send + 'static>(
self: &Arc<Self>,
read: impl FnOnce(&Reader) -> bakashrot_storage::Result<T> + Send + 'static,
) -> Result<T, RequestRefused> {
self.pooled(|shared| &shared.readers, Database::reader, read)
.await
}
/// Runs a client's SQL on a query connection, off the async threads.
async fn query(self: &Arc<Self>, sql: String) -> Result<String, RequestRefused> {
self.pooled(
|shared| &shared.queries,
Database::query_runner,
move |runner: &QueryRunner| runner.run(&sql),
)
.await
}
/// Runs `work` on an idle connection of `pool`, or a new one, then
/// puts it back.
async fn pooled<C: Send + 'static, T: Send + 'static>(
self: &Arc<Self>,
pool: fn(&Shared) -> &Mutex<Vec<C>>,
open: fn(&Database) -> bakashrot_storage::Result<C>,
work: impl FnOnce(&C) -> bakashrot_storage::Result<T> + Send + 'static,
) -> Result<T, RequestRefused> {
let shared = self.clone();
tokio::task::spawn_blocking(move || {
let idle = pool(&shared).lock().ok().and_then(|mut idle| idle.pop());
let connection = match idle {
Some(connection) => connection,
None => open(&shared.database).map_err(refusal)?,
};
let value = work(&connection).map_err(refusal);
if let Ok(mut idle) = pool(&shared).lock() {
idle.push(connection);
}
value
})
.await
.unwrap_or_else(|_| Err(server_error("a read failed")))
}
}
/// Checkpoints the WAL every second, on a thread and a connection of its
/// own, so the writer doesn't do it in the middle of a commit (2.5 times
/// the pushes: `Source/docs/storage.md`, "Against the old storage").
fn start_checkpoints(database: &Database) -> Result<(), String> {
let checkpointer = database.checkpointer().map_err(|error| error.to_string())?;
std::thread::Builder::new()
.name("checkpoints".into())
.spawn(move || {
loop {
std::thread::sleep(CHECKPOINT_INTERVAL);
if let Err(error) = checkpointer.checkpoint() {
warn!("checkpointing the database: {error}");
}
}
})
.map(|_| ())
.map_err(|error| format!("the checkpoints' thread: {error}"))
}
/// A storage error as the refusal clients get.
fn refusal(error: bakashrot_storage::Error) -> RequestRefused {
use bakashrot_storage::Error;
let code = match &error {
Error::Invalid(_) => ErrorCode::InvalidRequest,
Error::NotFound(_) => ErrorCode::NotFound,
Error::UnknownName(_) => ErrorCode::UnknownName,
Error::TooBig(_) => ErrorCode::TooBig,
Error::Query(_) => ErrorCode::QueryFailed,
Error::Sqlite(_) | Error::Unusable(_) => {
warn!("the database: {error}");
return server_error("the database failed");
}
};
RequestRefused::new(code, error.to_string())
}
fn server_error(reason: &str) -> RequestRefused {
RequestRefused::new(ErrorCode::ServerError, reason)
}
fn read(path: &Path) -> Result<String, String> {
std::fs::read_to_string(path).map_err(|error| format!("{}: {error}", path.display()))
}
/// The CRL file's revocations; none without one (no file, or not set).
fn load_revocations(path: Option<&Path>, ca: &str) -> Result<Revocations, String> {
let Some(path) = path.filter(|path| path.exists()) else {
return Ok(Revocations::none());
};
Revocations::load(&read(path)?, ca).map_err(|error| format!("{}: {error}", path.display()))
}
/// Now, in ms since 1970 UTC: when a message is pushed.
fn now() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |since| since.as_millis() as u64)
}
/// A file's time and size, to see it changed.
fn stamp(path: &Path) -> Option<(SystemTime, u64)> {
let metadata = std::fs::metadata(path).ok()?;
Some((metadata.modified().ok()?, metadata.len()))
}
@@ -0,0 +1,40 @@
//! `bakashrot-server <config.toml>`: runs a server until Ctrl+C.
use bakashrot_config::Config;
use bakashrot_server::Server;
use std::path::PathBuf;
use std::process::ExitCode;
use tokio::net::TcpListener;
use tracing::{error, info};
#[tokio::main]
async fn main() -> ExitCode {
tracing_subscriber::fmt().with_target(false).init();
let Some(path) = std::env::args_os().nth(1).map(PathBuf::from) else {
eprintln!("usage: bakashrot-server <config.toml>");
return ExitCode::from(2);
};
match run(&path).await {
Ok(()) => ExitCode::SUCCESS,
Err(why) => {
error!("{why}");
ExitCode::FAILURE
}
}
}
async fn run(path: &std::path::Path) -> Result<(), String> {
let config = Config::load(path).map_err(|error| error.to_string())?;
let server = Server::start(config)?;
let listener = TcpListener::bind(server.listen())
.await
.map_err(|error| format!("listening on {}: {error}", server.listen()))?;
info!("{} listening on {}", server.name(), server.listen());
tokio::select! {
served = server.serve(listener) => served.map_err(|error| format!("accepting: {error}"))?,
_ = server.watch_revocations() => {}
_ = server.apply_retention() => {}
_ = tokio::signal::ctrl_c() => info!("stopping"),
}
Ok(())
}
@@ -0,0 +1,69 @@
//! Retention: right away, then every `retention_interval`, each topic's
//! messages past its age (`[retention]`) are deleted, then their
//! attachments' parts. Every topic in the database, by its name (one no
//! longer in `topics` too). Through the writer's queue, a batch at a time,
//! so pushes go on in between.
use crate::Shared;
use crate::writer::Write;
use bakashrot_proto::packets::RequestRefused;
use std::sync::Arc;
use tracing::{info, warn};
/// Most messages deleted in one write.
const MESSAGES_PER_WRITE: usize = 10_000;
/// Most attachment parts (1 MiB each) deleted in one write.
const PARTS_PER_WRITE: usize = 64;
/// Deletes what's past its age at every interval. Never returns.
pub(crate) async fn run(shared: &Arc<Shared>) {
loop {
if let Err(refused) = once(shared).await {
warn!("retention: {}", refused.reason);
}
tokio::time::sleep(shared.config.server.retention_interval).await;
}
}
/// One pass: every topic, then the attachments (also what a pass cut short
/// left).
async fn once(shared: &Arc<Shared>) -> Result<(), RequestRefused> {
let now = crate::now();
for topic in shared.read(|reader| reader.topics()).await? {
let Some(age) = shared.config.retention.age(&topic) else {
continue;
};
let cutoff = now.saturating_sub(age.as_millis() as u64);
let deleted = repeat(shared, MESSAGES_PER_WRITE, |limit| Write::DeleteBefore {
topic: topic.clone(),
cutoff,
limit,
})
.await?;
if deleted > 0 {
info!("deleted {deleted} messages of topic '{topic}'");
}
}
repeat(shared, PARTS_PER_WRITE, |max_parts| {
Write::PurgeAttachments { max_parts }
})
.await?;
Ok(())
}
/// Sends `write(limit)` until one does less than `limit`: how many in all.
async fn repeat(
shared: &Shared,
limit: usize,
write: impl Fn(usize) -> Write,
) -> Result<u64, RequestRefused> {
let mut total = 0;
loop {
let count = shared.pushes.send(write(limit)).await?;
total += count;
if count < limit as u64 {
return Ok(total);
}
}
}
@@ -0,0 +1,161 @@
//! The writer's thread: every write goes through one queue, and the thread
//! writes whatever is queued in one transaction (a group commit): the
//! busier, the bigger the groups.
use crate::refusal;
use bakashrot_proto::packets::RequestRefused;
use bakashrot_storage::{Batch, Writer};
use std::sync::mpsc;
use tokio::sync::oneshot;
/// Most writes in one transaction.
const MAX_GROUP: usize = 1000;
/// A write's outcome: a number (a message's id, an upload's), or the
/// refusal to answer.
pub(crate) type Outcome = Result<u64, RequestRefused>;
/// What the writer does (`bakashrot_storage::Batch`'s).
pub(crate) enum Write {
/// A message: its id.
Push {
topic: String,
node: String,
pushed_at: u64,
data: String,
},
/// An attachment's upload: its id.
StartUpload { size: u64, sha256: [u8; 32] },
/// An upload's next part: 1 if it was the last, 0 otherwise.
Part {
upload: u64,
part: u64,
data: Vec<u8>,
},
/// A message with its whole, checked upload: its id.
PushWithUpload {
upload: u64,
topic: String,
node: String,
pushed_at: u64,
data: String,
},
/// Drops an upload: 0.
CancelUpload { upload: u64 },
/// Retention: deletes a topic's messages pushed before `cutoff`,
/// `limit` at most: how many.
DeleteBefore {
topic: String,
cutoff: u64,
limit: usize,
},
/// Deletes deleted messages' attachment parts, `max_parts` at most:
/// how many.
PurgeAttachments { max_parts: usize },
}
impl Write {
fn run(&self, batch: &mut Batch<'_>) -> bakashrot_storage::Result<u64> {
// Upload ids are SQLite rowids: positive.
match self {
Write::Push {
topic,
node,
pushed_at,
data,
} => batch.push(topic, node, *pushed_at, data),
Write::StartUpload { size, sha256 } => {
batch.start_upload(*size, sha256).map(|id| id as u64)
}
Write::Part { upload, part, data } => {
batch.write_part(*upload as i64, *part, data).map(u64::from)
}
Write::PushWithUpload {
upload,
topic,
node,
pushed_at,
data,
} => batch.push_with_attachment(*upload as i64, topic, node, *pushed_at, data),
Write::CancelUpload { upload } => batch.cancel_upload(*upload as i64).map(|()| 0),
Write::DeleteBefore {
topic,
cutoff,
limit,
} => batch
.delete_before(topic, *cutoff, *limit)
.map(|count| count as u64),
Write::PurgeAttachments { max_parts } => batch
.purge_attachments(*max_parts)
.map(|count| count as u64),
}
}
}
struct Job {
write: Write,
done: oneshot::Sender<Outcome>,
}
/// The queue to the writer's thread.
pub(crate) struct Pushes {
queue: mpsc::Sender<Job>,
}
impl Pushes {
/// Starts the writer's thread on `writer`. It ends with the queue.
pub(crate) fn start(mut writer: Writer) -> std::io::Result<Pushes> {
let (queue, pending) = mpsc::channel::<Job>();
std::thread::Builder::new()
.name("writer".into())
.spawn(move || {
while let Ok(first) = pending.recv() {
let mut group = vec![first];
while group.len() < MAX_GROUP {
let Ok(next) = pending.try_recv() else { break };
group.push(next);
}
write(&mut writer, group);
}
})?;
Ok(Pushes { queue })
}
/// Queues a write now (writes are done in the order queued), its
/// outcome once its group is committed. Dropping the future doesn't
/// take the write back.
pub(crate) fn send(&self, write: Write) -> impl Future<Output = Outcome> + use<> {
let (done, outcome) = oneshot::channel();
let queued = self.queue.send(Job { write, done });
async move {
queued.map_err(|_| stopped())?;
outcome.await.unwrap_or_else(|_| Err(stopped()))
}
}
}
/// Writes a group in one transaction, then answers each write.
fn write(writer: &mut Writer, group: Vec<Job>) {
let mut outcomes = Vec::with_capacity(group.len());
let committed = writer.batch(|batch| {
for job in &group {
outcomes.push(job.write.run(batch).map_err(refusal));
}
Ok(())
});
if let Err(error) = committed {
let refused = refusal(error);
outcomes = group.iter().map(|_| Err(refused.clone())).collect();
}
for (job, outcome) in group.into_iter().zip(outcomes) {
// Its connection may be gone: nothing to answer then.
let _ = job.done.send(outcome);
}
}
fn stopped() -> RequestRefused {
RequestRefused::new(
bakashrot_proto::ErrorCode::ServerError,
"the server is stopping",
)
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,28 @@
[package]
name = "bakashrot-storage"
description = "BakaShrot's database: SQLite, schema v9, messages by stream, attachments, read-only queries."
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
authors.workspace = true
repository.workspace = true
publish.workspace = true
[dependencies]
# The limits (message ids, attachment parts).
bakashrot-proto = { path = "../bakashrot-proto" }
# Synchronous, as the config says it.
bakashrot-config = { path = "../bakashrot-config" }
# SQLite itself compiled in (`bundled`): the same version everywhere, with
# its JSON functions, no system library to install. `fallible_uint`: u64
# in and out, an error past i64::MAX instead of a wrap.
rusqlite = { version = "0.42.0", features = ["bundled", "fallible_uint"] }
# Query results as JSON.
serde_json = "1.0.154"
[lints]
workspace = true
[dev-dependencies]
serde_json = "1.0.154"
@@ -0,0 +1,394 @@
//! Writing: the writer's connection, and what a batch (one transaction)
//! does.
use crate::{
AttachmentState, Error, MAX_STREAMS, Result, find_stream, message_key, part_key, part_keys,
stream_keys,
};
use bakashrot_proto::limits::{
ATTACHMENT_PART_SIZE, MAX_ATTACHMENT_SIZE, MAX_MESSAGE_ID, attachment_part_len,
};
use bakashrot_proto::packets::ReplicatedMessage;
use rusqlite::{Connection, OptionalExtension, Transaction, TransactionBehavior};
/// The connection that writes (one per database).
#[derive(Debug)]
pub struct Writer {
connection: Connection,
}
impl Writer {
pub(crate) fn new(connection: Connection) -> Writer {
Writer { connection }
}
/// Runs `write` in one transaction, committed if it returns `Ok`,
/// rolled back otherwise. Each operation of a [`Batch`] is all or
/// nothing on its own, so `write` may go on after one fails: many
/// pushes in one batch are a group commit, one disk flush for all.
pub fn batch<T>(&mut self, write: impl FnOnce(&mut Batch<'_>) -> Result<T>) -> Result<T> {
let mut batch = Batch {
transaction: self
.connection
.transaction_with_behavior(TransactionBehavior::Immediate)?,
};
let value = write(&mut batch)?;
batch.transaction.commit()?;
Ok(value)
}
/// Gives the space of deleted messages back to the disk: rewrites the
/// database (`VACUUM`), then empties the WAL. SQLite reuses that space
/// by itself; this only shrinks the file. Slow on a big database, and
/// every other write waits meanwhile: the old server's `vacuum`
/// command.
pub fn vacuum(&mut self) -> Result<()> {
self.connection.execute_batch("VACUUM")?;
self.connection
.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(()))?;
Ok(())
}
}
/// What's written in one transaction ([`Writer::batch`]). Names come
/// checked (`bakashrot_proto`'s decoding). Attachment ids are this
/// database's own, from [`Batch::start_upload`] or
/// [`Reader::attachment`](crate::Reader::attachment).
#[derive(Debug)]
pub struct Batch<'c> {
transaction: Transaction<'c>,
}
impl Batch<'_> {
/// Stores a pushed message: the next id of its topic and node (from 1),
/// which it returns. Without a savepoint, the hot path: a push that
/// fails leaves at most its topic and node's (empty) stream.
pub fn push(&mut self, topic: &str, node: &str, pushed_at: u64, data: &str) -> Result<u64> {
Ok(insert_pushed(&self.transaction, topic, node, pushed_at, data)?.0)
}
/// Stores a pushed message with its attachment, an upload all of whose
/// parts came ([`Batch::write_part`] said so) and whose SHA-256 the
/// caller checked: the attachment is then `ready`.
pub fn push_with_attachment(
&mut self,
upload: i64,
topic: &str,
node: &str,
pushed_at: u64,
data: &str,
) -> Result<u64> {
self.atomic(|db| {
let (state, size, received) = attachment(db, upload)?;
if state != AttachmentState::Uploading || received != size {
return Err(Error::Invalid(format!(
"attachment {upload} isn't a complete upload"
)));
}
let (id, key) = insert_pushed(db, topic, node, pushed_at, data)?;
set_attachment(db, upload, "message_key = ?2, state = 'ready'", key)?;
Ok(id)
})
}
/// Starts an upload: an attachment pushed with its message, whose parts
/// come next. Returns its id.
pub fn start_upload(&mut self, size: u64, sha256: &[u8; 32]) -> Result<i64> {
if !(1..=MAX_ATTACHMENT_SIZE).contains(&size) {
return Err(Error::TooBig(format!(
"an attachment of {size} bytes: 1 to {MAX_ATTACHMENT_SIZE}"
)));
}
self.atomic(|db| {
db.execute(
"INSERT INTO attachments (size, sha256, state) VALUES (?1, ?2, 'uploading')",
(size, sha256),
)?;
Ok(db.last_insert_rowid())
})
}
/// Stores the next part of an upload or of a replicated attachment: in
/// order, each of its exact size (`attachment_part_len`). Returns
/// whether that was the last one.
pub fn write_part(&mut self, attachment_id: i64, part: u64, data: &[u8]) -> Result<bool> {
self.atomic(|db| {
let (state, size, received) = attachment(db, attachment_id)?;
if state != AttachmentState::Uploading && state != AttachmentState::Replicating {
return Err(Error::Invalid(format!(
"attachment {attachment_id} is {state}, it takes no parts"
)));
}
// Every part but the last is whole: what came is whole parts.
let next = received / ATTACHMENT_PART_SIZE;
if received == size || part != next {
return Err(Error::Invalid(format!(
"part {part} of attachment {attachment_id}: part {next} is next"
)));
}
let expected = attachment_part_len(size, part);
if data.len() as u64 != expected {
return Err(Error::Invalid(format!(
"part {part} of attachment {attachment_id}: {} bytes, {expected} expected",
data.len()
)));
}
db.prepare_cached("INSERT INTO attachment_parts (key, part_data) VALUES (?1, ?2)")?
.execute((part_key(attachment_id, part), data))?;
set_attachment(db, attachment_id, "received = received + ?2", expected)?;
Ok(received + expected == size)
})
}
/// Drops an upload that won't be pushed: cut short, or not matching its
/// SHA-256.
pub fn cancel_upload(&mut self, upload: i64) -> Result<()> {
self.atomic(|db| {
if attachment(db, upload)?.0 != AttachmentState::Uploading {
return Err(Error::Invalid(format!(
"attachment {upload} isn't an upload"
)));
}
delete_attachment(db, upload)
})
}
/// Stores messages a peer sent for `topic` and `node`, with their own
/// ids, in order; ones already here are kept as they are. Their
/// attachments are noted, to be asked for (`replicating`), or never if
/// bigger than `max_attachment_size` (`too_big`). Returns the topic and
/// node's last id.
pub fn replicate(
&mut self,
topic: &str,
node: &str,
messages: &[ReplicatedMessage],
max_attachment_size: u64,
) -> Result<u64> {
self.atomic(|db| {
let (stream, mut last_id) = stream(db, topic, node)?;
let mut insert = db.prepare_cached(
"INSERT OR IGNORE INTO data (key, pushed_at, message_data) VALUES (?1, ?2, ?3)",
)?;
let mut attach = db.prepare_cached(
"INSERT INTO attachments (message_key, size, sha256, state) VALUES (?1, ?2, ?3, ?4)",
)?;
for message in messages {
if !(1..=MAX_MESSAGE_ID).contains(&message.id) {
return Err(Error::Invalid(format!("message id {}", message.id)));
}
let key = message_key(stream, message.id);
let stored = insert.execute((key, message.pushed_at, &message.data))? == 1;
if let (true, Some(attachment)) = (stored, &message.attachment) {
let state = if attachment.size > max_attachment_size {
AttachmentState::TooBig
} else {
AttachmentState::Replicating
};
attach.execute((key, attachment.size, &attachment.sha256, state))?;
}
// What the trigger keeps: one ignored was here, below it.
last_id = last_id.max(message.id);
}
Ok(last_id)
})
}
/// A replicated attachment all of whose parts came: `matches` its
/// SHA-256 (the caller checked), it's `ready`; otherwise its parts are
/// dropped and it's asked for again from the start.
pub fn finish_replicated(&mut self, attachment_id: i64, matches: bool) -> Result<()> {
self.atomic(|db| {
let (state, size, received) = attachment(db, attachment_id)?;
if state != AttachmentState::Replicating || received != size {
return Err(Error::Invalid(format!(
"attachment {attachment_id} isn't a complete replicated one"
)));
}
if matches {
set_attachment(db, attachment_id, "state = ?2", AttachmentState::Ready)
} else {
delete_parts(db, attachment_id, None)?;
set_attachment(db, attachment_id, "received = ?2", 0)
}
})
}
/// Retention: deletes `topic`'s messages pushed before `cutoff` (ms),
/// `limit` at most (call again while it returns `limit`). Each stream
/// is read from its oldest message and stops at the first one it keeps:
/// only what's deleted is read. So messages go in id order: one stamped
/// earlier than the one before it (a clock set back) waits for it.
pub fn delete_before(&mut self, topic: &str, cutoff: u64, limit: usize) -> Result<usize> {
self.atomic(|db| {
let streams: Vec<i64> = db
.prepare_cached("SELECT stream_id FROM streams WHERE topic = ?1")?
.query_map([topic], |row| row.get(0))?
.collect::<rusqlite::Result<_>>()?;
let mut oldest = db.prepare_cached(
"SELECT key, pushed_at FROM data WHERE key BETWEEN ?1 AND ?2 ORDER BY key",
)?;
let mut deleted = 0;
for stream in streams {
let (first, last) = stream_keys(stream);
let mut up_to = None;
let mut rows = oldest.query((first, last))?;
while deleted < limit {
let Some(row) = rows.next()? else { break };
if row.get::<_, u64>(1)? >= cutoff {
break;
}
up_to = Some(row.get::<_, i64>(0)?);
deleted += 1;
}
drop(rows);
if let Some(up_to) = up_to {
db.execute(
"DELETE FROM data WHERE key BETWEEN ?1 AND ?2",
(first, up_to),
)?;
}
if deleted == limit {
break;
}
}
Ok(deleted)
})
}
/// Deletes the parts of attachments whose message was deleted,
/// `max_parts` at most (call again while it returns `max_parts`), and
/// their rows once they have none left.
pub fn purge_attachments(&mut self, max_parts: usize) -> Result<usize> {
self.atomic(|db| {
let deleting: Vec<i64> = db
.prepare_cached(
"SELECT attachment_id FROM attachments WHERE state = 'deleting' \
ORDER BY attachment_id",
)?
.query_map([], |row| row.get(0))?
.collect::<rusqlite::Result<_>>()?;
let mut purged = 0;
for attachment_id in deleting {
purged += delete_parts(db, attachment_id, Some(max_parts - purged))?;
if purged == max_parts {
break;
}
db.execute(
"DELETE FROM attachments WHERE attachment_id = ?1",
[attachment_id],
)?;
}
Ok(purged)
})
}
/// Runs one operation all or nothing (a savepoint), so the batch can go
/// on after it fails.
fn atomic<T>(&mut self, operation: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {
let savepoint = self.transaction.savepoint()?;
let value = operation(&savepoint)?;
savepoint.commit()?;
Ok(value)
}
}
/// A topic and node's stream, made if new: its id and last id.
fn stream(db: &Connection, topic: &str, node: &str) -> Result<(i64, u64)> {
if let Some(found) = find_stream(db, topic, node)? {
return Ok(found);
}
let next: i64 = db.query_row(
"SELECT coalesce(max(stream_id), 0) + 1 FROM streams",
[],
|row| row.get(0),
)?;
if next > MAX_STREAMS {
return Err(Error::TooBig(format!(
"{topic}/{node}: this database has {MAX_STREAMS} topic and node pairs already"
)));
}
db.execute(
"INSERT INTO streams (stream_id, topic, node) VALUES (?1, ?2, ?3)",
(next, topic, node),
)?;
Ok((next, 0))
}
/// Inserts a pushed message with the next id of its stream: the id and the
/// message's key.
fn insert_pushed(
db: &Connection,
topic: &str,
node: &str,
pushed_at: u64,
data: &str,
) -> Result<(u64, i64)> {
let (stream, last_id) = stream(db, topic, node)?;
let id = last_id + 1;
if id > MAX_MESSAGE_ID {
return Err(Error::TooBig(format!("{topic}/{node}: no message id left")));
}
let key = message_key(stream, id);
db.prepare_cached("INSERT INTO data (key, pushed_at, message_data) VALUES (?1, ?2, ?3)")?
.execute((key, pushed_at, data))?;
Ok((id, key))
}
/// An attachment's state, size and bytes received.
fn attachment(db: &Connection, attachment_id: i64) -> Result<(AttachmentState, u64, u64)> {
db.prepare_cached("SELECT state, size, received FROM attachments WHERE attachment_id = ?1")?
.query_row([attachment_id], |row| {
Ok((row.get(0)?, row.get(1)?, row.get(2)?))
})
.optional()?
.ok_or_else(|| Error::NotFound(format!("no attachment {attachment_id}")))
}
/// `UPDATE attachments SET <set>` of one, `?2` being `value`.
fn set_attachment(
db: &Connection,
attachment_id: i64,
set: &str,
value: impl rusqlite::ToSql,
) -> Result<()> {
db.prepare_cached(&format!(
"UPDATE attachments SET {set} WHERE attachment_id = ?1"
))?
.execute((attachment_id, value))?;
Ok(())
}
/// Deletes an attachment's parts, `limit` at most: how many.
fn delete_parts(db: &Connection, attachment_id: i64, limit: Option<usize>) -> Result<usize> {
let (first, last) = part_keys(attachment_id);
let limit = limit.map_or(-1, |limit| limit as i64);
Ok(db
.prepare_cached(
"DELETE FROM attachment_parts WHERE key IN \
(SELECT key FROM attachment_parts WHERE key BETWEEN ?1 AND ?2 LIMIT ?3)",
)?
.execute((first, last, limit))?)
}
/// Deletes an attachment and its parts.
fn delete_attachment(db: &Connection, attachment_id: i64) -> Result<()> {
delete_parts(db, attachment_id, None)?;
db.execute(
"DELETE FROM attachments WHERE attachment_id = ?1",
[attachment_id],
)?;
Ok(())
}
/// Deletes every upload: at start, none of them can be pushed any more.
pub(crate) fn delete_uploads(db: &Connection) -> Result<()> {
let uploads: Vec<i64> = db
.prepare("SELECT attachment_id FROM attachments WHERE state = 'uploading'")?
.query_map([], |row| row.get(0))?
.collect::<rusqlite::Result<_>>()?;
for upload in uploads {
delete_attachment(db, upload)?;
}
Ok(())
}
@@ -0,0 +1,194 @@
//! Opening a database: making a new one, or checking and migrating one,
//! and the connections to it.
use crate::{Error, QueryRunner, Reader, Result, SCHEMA_VERSION, Writer};
use bakashrot_config::Synchronous;
use rusqlite::{Connection, OptionalExtension, TransactionBehavior};
use std::path::{Path, PathBuf};
use std::time::Duration;
/// `PRAGMA application_id` of a BakaShrot database: "BSHT".
const APPLICATION_ID: i64 = 0x4253_4854;
/// The schema, made in one go.
const SCHEMA: &str = include_str!("schema_v9.sql");
/// Migrations from v9 on: the version each makes, and its SQL. Applied in
/// order from the database's version, each in one transaction with
/// `schema_version` set. None yet.
const MIGRATIONS: &[(i64, &str)] = &[];
/// How long a connection waits for another's lock before failing.
const BUSY_TIMEOUT: Duration = Duration::from_secs(5);
/// The WAL's size, in pages, past which the writer checkpoints it itself
/// (SQLite's default is 1000): a backstop when the [`Checkpointer`] can't
/// keep up.
pub const WRITER_CHECKPOINT_PAGES: u32 = 10_000;
/// Copies the WAL into the database on a connection of its own, so the
/// writer doesn't do it in the middle of a commit (the old server's way:
/// `OldSource/Server/Storage/Writer.pbi`).
#[derive(Debug)]
pub struct Checkpointer {
connection: Connection,
}
impl Checkpointer {
/// Copies what it can without waiting for anyone (`PASSIVE`).
pub fn checkpoint(&self) -> Result<()> {
self.connection
.query_row("PRAGMA wal_checkpoint(PASSIVE)", [], |_| Ok(()))?;
Ok(())
}
}
/// A database, opened and checked once: hands out connections to it.
#[derive(Debug, Clone)]
pub struct Database {
path: PathBuf,
synchronous: Synchronous,
}
impl Database {
/// Opens the database at `path`: makes it if there's none (or it's an
/// empty file), migrates an older one, refuses one that isn't a
/// BakaShrot database of a version this one reads. Then deletes the
/// uploads left over (their pushes never finished).
pub fn open(path: &Path, synchronous: Synchronous) -> Result<Database> {
let database = Database {
path: path.to_owned(),
synchronous,
};
let mut connection = database.connect()?;
let transaction = connection.transaction_with_behavior(TransactionBehavior::Immediate)?;
let application_id: i64 =
transaction.query_row("PRAGMA application_id", [], |row| row.get(0))?;
let tables: i64 =
transaction.query_row("SELECT count(*) FROM sqlite_schema", [], |row| row.get(0))?;
if application_id == 0 && tables == 0 {
transaction.execute_batch(SCHEMA)?;
transaction.execute(
"INSERT INTO metadata (name, value) VALUES ('created_by', ?1)",
[concat!("bakashrot-storage ", env!("CARGO_PKG_VERSION"))],
)?;
} else if application_id != APPLICATION_ID {
return Err(Error::Unusable(unusable(&transaction, path)?));
}
let mut version = schema_version(&transaction)?;
if version > SCHEMA_VERSION {
return Err(Error::Unusable(format!(
"{}: schema v{version}, made by a newer version (this one reads v{SCHEMA_VERSION})",
path.display()
)));
}
for (made, sql) in MIGRATIONS {
if *made == version + 1 {
transaction.execute_batch(sql)?;
transaction.execute(
"UPDATE metadata SET value = ?1 WHERE name = 'schema_version'",
[made],
)?;
version = *made;
}
}
if version != SCHEMA_VERSION {
return Err(Error::Unusable(format!(
"{}: schema v{version}, which this version can't migrate",
path.display()
)));
}
crate::batch::delete_uploads(&transaction)?;
transaction.commit()?;
Ok(database)
}
/// The connection that writes. Only one at a time should: a second
/// waits for the first's transactions (up to 5 s, then fails). It only
/// checkpoints the WAL itself past [`WRITER_CHECKPOINT_PAGES`]: a
/// [`Checkpointer`] keeps that off its way.
pub fn writer(&self) -> Result<Writer> {
let connection = self.connect()?;
connection.pragma_update(None, "wal_autocheckpoint", WRITER_CHECKPOINT_PAGES)?;
Ok(Writer::new(connection))
}
/// A connection that copies the WAL into the database, off the
/// writer's way: call [`Checkpointer::checkpoint`] every second or so.
pub fn checkpointer(&self) -> Result<Checkpointer> {
Ok(Checkpointer {
connection: self.connect()?,
})
}
/// A connection that reads, as many as needed.
pub fn reader(&self) -> Result<Reader> {
Ok(Reader::new(self.connect()?))
}
/// A connection for clients' queries: read-only (`query_only`).
pub fn query_runner(&self) -> Result<QueryRunner> {
let connection = self.connect()?;
connection.pragma_update(None, "query_only", true)?;
Ok(QueryRunner::new(connection))
}
/// A connection with this database's settings: WAL, `synchronous`, the
/// busy timeout.
fn connect(&self) -> Result<Connection> {
let connection = Connection::open(&self.path)?;
connection.busy_timeout(BUSY_TIMEOUT)?;
let mode: String =
connection.query_row("PRAGMA journal_mode = WAL", [], |row| row.get(0))?;
if !mode.eq_ignore_ascii_case("wal") {
return Err(Error::Unusable(format!(
"{}: can't be put in WAL mode (it's in {mode})",
self.path.display()
)));
}
let synchronous = match self.synchronous {
Synchronous::Full => "FULL",
Synchronous::Normal => "NORMAL",
};
connection.pragma_update(None, "synchronous", synchronous)?;
Ok(connection)
}
}
/// `metadata`'s `schema_version`.
fn schema_version(connection: &Connection) -> Result<i64> {
let has_metadata: bool = connection.query_row(
"SELECT count(*) > 0 FROM sqlite_schema WHERE type = 'table' AND name = 'metadata'",
[],
|row| row.get(0),
)?;
let version = if has_metadata {
connection
.query_row(
"SELECT value FROM metadata WHERE name = 'schema_version'",
[],
|row| row.get(0),
)
.optional()?
} else {
None
};
version.ok_or_else(|| Error::Unusable("a BakaShrot database without its schema version".into()))
}
/// Why a database that isn't ours can't be opened, in words.
fn unusable(connection: &Connection, path: &Path) -> Result<String> {
let old: bool = connection.query_row(
"SELECT count(*) > 0 FROM sqlite_schema WHERE type = 'table' AND name = 'node_heads'",
[],
|row| row.get(0),
)?;
Ok(if old {
format!(
"{}: made by the old server (schema v8), which this one doesn't read: start a new database",
path.display()
)
} else {
format!("{}: not a BakaShrot database", path.display())
})
}
+265
View File
@@ -0,0 +1,265 @@
//! BakaShrot's database: SQLite, schema v9 (`schema_v9.sql`).
//!
//! - [`Database`]: opens one (creating it, or checking it's a v9 one),
//! and hands out connections.
//! - [`Writer`]: the one connection that writes. Everything is written in
//! a [`Batch`], one transaction: pushes, replication, attachments,
//! retention. Many pushes in one batch is a group commit. And
//! [`Writer::vacuum`], to shrink the file.
//! - [`Reader`]: as many as needed, reading while the writer writes (WAL).
//! - [`QueryRunner`]: clients' read-only SQL, on a read-only connection.
//!
//! **Everything is by name:** topics, nodes, message ids, times, as on the
//! wire. Streams (one node's messages in one topic) and the packed keys
//! that store them stay inside this crate: `Source/docs/storage.md`.
//!
//! **Blocking:** SQLite is. The server runs these on threads of their own
//! (the writer on one, readers on a pool), not on its async tasks.
mod batch;
mod database;
mod query;
mod reader;
pub use batch::{Batch, Writer};
pub use database::{Checkpointer, Database, WRITER_CHECKPOINT_PAGES};
pub use query::{MAX_QUERY_BYTES, MAX_QUERY_ROWS, QueryRunner};
pub use reader::{Attachment, MESSAGES_BYTES, Reader};
use bakashrot_proto::limits::{MAX_ATTACHMENT_PARTS, MAX_MESSAGE_ID};
use rusqlite::types::{FromSql, FromSqlError, FromSqlResult, ToSql, ToSqlOutput, ValueRef};
use rusqlite::{Connection, OptionalExtension};
use std::fmt;
/// The schema version this crate makes and reads.
pub const SCHEMA_VERSION: i64 = 9;
/// The most streams (topic and node pairs) a database holds: 2^20 - 1.
pub const MAX_STREAMS: i64 = (1 << STREAM_BITS) - 1;
/// What went wrong. The server answers each with its own refusal code.
#[derive(Debug)]
pub enum Error {
/// SQLite failed (the disk, a lock held too long...): `ServerError`.
Sqlite(rusqlite::Error),
/// A database this version doesn't open: another program's, the old
/// server's, a newer schema's. Said at start.
Unusable(String),
/// A request that doesn't fit what's stored: a part out of order or of
/// the wrong size, an attachment in the wrong state: `InvalidRequest`.
Invalid(String),
/// No such attachment: `NotFound`.
NotFound(String),
/// A node without any message, in any topic: `UnknownName`.
UnknownName(String),
/// Over a limit: streams, message ids, a query's result: `TooBig`.
TooBig(String),
/// A client's query that failed or isn't read-only: `QueryFailed`.
Query(String),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Sqlite(error) => write!(f, "database: {error}"),
Error::Unusable(what)
| Error::Invalid(what)
| Error::NotFound(what)
| Error::UnknownName(what)
| Error::TooBig(what)
| Error::Query(what) => f.write_str(what),
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Error::Sqlite(error) => Some(error),
_ => None,
}
}
}
impl From<rusqlite::Error> for Error {
fn from(error: rusqlite::Error) -> Self {
Error::Sqlite(error)
}
}
/// A result of this crate.
pub type Result<T> = std::result::Result<T, Error>;
/// Where an attachment is at (`Source/docs/storage.md`, "Attachments").
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AttachmentState {
/// Pushed, its parts coming, no message yet.
Uploading,
/// Its message came from a peer, its parts come after.
Replicating,
/// All here, checked.
Ready,
/// Bigger than this server keeps: never asked for.
TooBig,
/// Its message was deleted, its parts go in the background.
Deleting,
}
impl AttachmentState {
const ALL: [AttachmentState; 5] = [
AttachmentState::Uploading,
AttachmentState::Replicating,
AttachmentState::Ready,
AttachmentState::TooBig,
AttachmentState::Deleting,
];
/// As the database writes it.
pub fn as_str(self) -> &'static str {
match self {
AttachmentState::Uploading => "uploading",
AttachmentState::Replicating => "replicating",
AttachmentState::Ready => "ready",
AttachmentState::TooBig => "too_big",
AttachmentState::Deleting => "deleting",
}
}
}
impl fmt::Display for AttachmentState {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl ToSql for AttachmentState {
fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
Ok(self.as_str().into())
}
}
impl FromSql for AttachmentState {
fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
let text = value.as_str()?;
Self::ALL
.into_iter()
.find(|state| state.as_str() == text)
.ok_or(FromSqlError::InvalidType)
}
}
/// A topic and node's stream, if it has one: its id and last id.
fn find_stream(db: &Connection, topic: &str, node: &str) -> rusqlite::Result<Option<(i64, u64)>> {
db.prepare_cached("SELECT stream_id, last_id FROM streams WHERE topic = ?1 AND node = ?2")?
.query_row((topic, node), |row| Ok((row.get(0)?, row.get(1)?)))
.optional()
}
// The packed keys (storage.md, "Keys"). Only these know the layout (and
// the schema's generated columns, which a test checks against them).
/// Bits of a message id in `data.key`, below the stream's.
const ID_BITS: u32 = 43;
/// Bits of a stream id above them: 43 + 20 = 63, a positive i64.
const STREAM_BITS: u32 = 20;
/// Bits of a part's index in `attachment_parts.key`.
const PART_BITS: u32 = 20;
const ID_MASK: i64 = (1 << ID_BITS) - 1;
const _: () = assert!(MAX_MESSAGE_ID == ID_MASK as u64, "ids fill their bits");
const _: () = assert!(MAX_ATTACHMENT_PARTS == 1 << PART_BITS, "parts fill theirs");
/// `data.key` of a stream's message.
fn message_key(stream: i64, id: u64) -> i64 {
(stream << ID_BITS) | id as i64
}
/// The message id in a `data.key`.
fn message_id(key: i64) -> u64 {
(key & ID_MASK) as u64
}
/// The first and last `data.key` a stream can have.
fn stream_keys(stream: i64) -> (i64, i64) {
(message_key(stream, 1), message_key(stream, MAX_MESSAGE_ID))
}
/// `attachment_parts.key` of an attachment's part.
fn part_key(attachment: i64, part: u64) -> i64 {
(attachment << PART_BITS) | part as i64
}
/// The first and last `attachment_parts.key` an attachment can have.
fn part_keys(attachment: i64) -> (i64, i64) {
(
part_key(attachment, 0),
part_key(attachment, MAX_ATTACHMENT_PARTS - 1),
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn keys() {
let key = message_key(MAX_STREAMS, MAX_MESSAGE_ID);
assert_eq!(key, i64::MAX);
assert_eq!(message_id(key), MAX_MESSAGE_ID);
assert_eq!(key >> ID_BITS, MAX_STREAMS);
assert_eq!(message_id(message_key(5, 42)), 42);
let (first, last) = stream_keys(2);
assert!(stream_keys(1).1 < first && last < stream_keys(3).0);
let (first, last) = part_keys(7);
assert_eq!(last - first + 1, MAX_ATTACHMENT_PARTS as i64);
assert!(part_keys(6).1 < first);
}
#[test]
fn the_schema_unpacks_keys_the_same() {
let db = Connection::open_in_memory().unwrap();
db.execute_batch(include_str!("schema_v9.sql")).unwrap();
db.execute(
"INSERT INTO streams (stream_id, topic, node) VALUES (?1, 't', 'n')",
[MAX_STREAMS],
)
.unwrap();
for (stream, id) in [(1, 1), (MAX_STREAMS, MAX_MESSAGE_ID), (77, 123_456_789)] {
let key = message_key(stream, id);
db.execute(
"INSERT INTO data (key, pushed_at, message_data) VALUES (?1, 1, '')",
[key],
)
.unwrap();
let (sql_stream, sql_id): (i64, u64) = db
.query_row(
"SELECT stream_id, message_id FROM data WHERE key = ?1",
[key],
|r| Ok((r.get(0)?, r.get(1)?)),
)
.unwrap();
assert_eq!((sql_stream, sql_id), (stream, id));
}
// The trigger reads the same id.
let last: u64 = db
.query_row(
"SELECT last_id FROM streams WHERE stream_id = ?1",
[MAX_STREAMS],
|r| r.get(0),
)
.unwrap();
assert_eq!(last, MAX_MESSAGE_ID);
}
#[test]
fn states_round_trip() {
let db = Connection::open_in_memory().unwrap();
for state in AttachmentState::ALL {
let back: AttachmentState = db.query_row("SELECT ?1", [state], |r| r.get(0)).unwrap();
assert_eq!(back, state);
}
let wrong: rusqlite::Result<AttachmentState> =
db.query_row("SELECT 'lost'", [], |r| r.get(0));
assert!(wrong.is_err());
}
}
@@ -0,0 +1,95 @@
//! Clients' read-only SQL (`Query`), as the old server ran it.
//!
//! Read-only three ways: the connection has `query_only` on (SQLite
//! refuses any write), the statement must be one SQLite says only reads
//! (`sqlite3_stmt_readonly`), and only one statement runs (more is an
//! error, not ignored). The result is JSON, every value a string or null
//! (as in protocol 6): `{"columns":[...],"rows":[[...],...]}`.
use crate::{Error, Result};
use bakashrot_proto::limits::MAX_MESSAGE_SIZE;
use rusqlite::Connection;
use rusqlite::types::ValueRef;
use serde_json::Value;
/// The most rows a query returns, as before.
pub const MAX_QUERY_ROWS: usize = 10_000;
/// The biggest result, in bytes of JSON: what a packet carries.
pub const MAX_QUERY_BYTES: usize = MAX_MESSAGE_SIZE;
/// A read-only connection for clients' queries.
#[derive(Debug)]
pub struct QueryRunner {
connection: Connection,
}
impl QueryRunner {
pub(crate) fn new(connection: Connection) -> QueryRunner {
QueryRunner { connection }
}
/// Runs one read-only statement: its result as JSON. Refused
/// ([`Error::Query`]) if it isn't one, or fails (SQLite's message, a
/// failing row included: never a partial result); [`Error::TooBig`]
/// past [`MAX_QUERY_ROWS`] or [`MAX_QUERY_BYTES`].
pub fn run(&self, sql: &str) -> Result<String> {
let failed = |error: rusqlite::Error| Error::Query(explain(error.to_string()));
let mut statement = self.connection.prepare(sql).map_err(failed)?;
if !statement.readonly() || statement.column_count() == 0 {
return Err(Error::Query("only queries that read are allowed".into()));
}
let columns: Vec<String> = statement.column_names().map(str::to_owned).collect();
let width = columns.len();
let mut rows: Vec<Vec<Value>> = Vec::new();
let mut bytes = 0;
let mut results = statement.query([]).map_err(failed)?;
while let Some(row) = results.next().map_err(failed)? {
if rows.len() == MAX_QUERY_ROWS {
return Err(Error::TooBig(format!(
"more than {MAX_QUERY_ROWS} rows: narrow the query (LIMIT)"
)));
}
let mut values = Vec::with_capacity(width);
for column in 0..width {
let value = text(row.get_ref(column).map_err(failed)?);
// Its JSON's size, about: quotes, escapes aside.
bytes += value.as_str().map_or(5, |text| text.len() + 3);
values.push(value);
}
if bytes > MAX_QUERY_BYTES {
return Err(Error::TooBig(format!(
"a result over {MAX_QUERY_BYTES} bytes: narrow the query"
)));
}
rows.push(values);
}
let json = serde_json::json!({ "columns": columns, "rows": rows }).to_string();
if json.len() > MAX_QUERY_BYTES {
return Err(Error::TooBig(format!(
"a result over {MAX_QUERY_BYTES} bytes: narrow the query"
)));
}
Ok(json)
}
}
/// SQLite's error, with a hint where the old server gave one.
fn explain(why: String) -> String {
if why.contains("malformed JSON") {
format!("{why} (a row isn't JSON: add is_json = 1 to the WHERE)")
} else {
why
}
}
/// A value as text, or null: numbers as SQLite writes them, blobs in hex.
fn text(value: ValueRef<'_>) -> Value {
match value {
ValueRef::Null => Value::Null,
ValueRef::Integer(number) => Value::String(number.to_string()),
ValueRef::Real(number) => Value::String(format!("{number:?}")),
ValueRef::Text(text) => Value::String(String::from_utf8_lossy(text).into_owned()),
ValueRef::Blob(bytes) => Value::String(bytes.iter().map(|b| format!("{b:02x}")).collect()),
}
}
@@ -0,0 +1,225 @@
//! Reading: messages, names, what replication compares, attachments.
//! Answers are the protocol's own types where it has them.
use crate::{
AttachmentState, Error, Result, find_stream, message_id, message_key, part_key, stream_keys,
};
use bakashrot_proto::limits::{ATTACHMENT_PART_SIZE, MAX_MESSAGE_ID};
use bakashrot_proto::packets::{Head, MessageEntry, Messages, MissingAttachment, StoredAttachment};
use rusqlite::{Connection, OptionalExtension, Row};
/// About how many bytes of messages one answer carries: past it, the rest
/// is left for the next request (`more`). A bigger message goes alone.
pub const MESSAGES_BYTES: usize = 1024 * 1024;
/// A stream's messages after a key, in order (`?1` that key, `?2` the
/// stream's last possible one), with their attachments.
const AFTER: &str = "SELECT d.key, d.pushed_at, d.message_data, a.size, a.state \
FROM data d LEFT JOIN attachments a ON a.message_key = d.key \
WHERE d.key > ?1 AND d.key <= ?2 ORDER BY d.key LIMIT ?3";
/// A stream's last messages, newest first (`?1`, `?2`: its key range).
const LATEST: &str = "SELECT d.key, d.pushed_at, d.message_data, a.size, a.state \
FROM data d LEFT JOIN attachments a ON a.message_key = d.key \
WHERE d.key >= ?1 AND d.key <= ?2 ORDER BY d.key DESC LIMIT ?3";
/// A connection that reads.
#[derive(Debug)]
pub struct Reader {
connection: Connection,
}
/// A message's attachment, as stored.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Attachment {
/// Its id in this database, for [`Reader::read_part`] and the writer.
pub id: i64,
/// Its size.
pub size: u64,
/// Its SHA-256.
pub sha256: [u8; 32],
/// The bytes of it here so far.
pub received: u64,
/// Where it's at.
pub state: AttachmentState,
}
impl Reader {
pub(crate) fn new(connection: Connection) -> Reader {
Reader { connection }
}
/// A topic and node's messages: `after` an id (0 for the first ones),
/// in order, or the last ones (`None`); `limit` at most, about
/// [`MESSAGES_BYTES`] at most. `more` if others follow (asking `after`
/// the last one gets them). None for a topic and node without any,
/// [`Error::UnknownName`] for a node without any in every topic.
pub fn messages(
&self,
topic: &str,
node: &str,
after: Option<u64>,
limit: u32,
) -> Result<Messages> {
let mut answer = Messages {
more: false,
messages: Vec::new(),
};
let Some((stream, _)) = find_stream(&self.connection, topic, node)? else {
return match self.has_node(node)? {
true => Ok(answer),
false => Err(Error::UnknownName(format!("unknown node '{node}'"))),
};
};
let (first, last) = stream_keys(stream);
let (sql, from) = match after {
Some(after) => (AFTER, message_key(stream, after.min(MAX_MESSAGE_ID))),
None => (LATEST, first),
};
let mut statement = self.connection.prepare_cached(sql)?;
// One more than asked: whether more follow.
let mut rows = statement.query((from, last, i64::from(limit) + 1))?;
let mut bytes = 0;
while let Some(row) = rows.next()? {
let message = entry(row)?;
let full = answer.messages.len() == limit as usize
|| (!answer.messages.is_empty() && bytes + message.data.len() > MESSAGES_BYTES);
if full {
answer.more = after.is_some();
break;
}
bytes += message.data.len();
answer.messages.push(message);
}
if after.is_none() {
answer.messages.reverse();
}
Ok(answer)
}
/// Every topic with messages (or that had some), in order.
pub fn topics(&self) -> Result<Vec<String>> {
self.strings("SELECT DISTINCT topic FROM streams ORDER BY topic")
}
/// Every node with messages (or that had some), in order.
pub fn nodes(&self) -> Result<Vec<String>> {
self.strings("SELECT DISTINCT node FROM streams ORDER BY node")
}
/// Whether `node` has messages in any topic (or had some).
fn has_node(&self, node: &str) -> Result<bool> {
self.connection
.prepare_cached("SELECT EXISTS (SELECT 1 FROM streams WHERE node = ?1)")?
.query_row([node], |row| row.get(0))
.map_err(Error::from)
}
/// Every topic and node's last id: what `SyncState` compares.
pub fn heads(&self) -> Result<Vec<Head>> {
self.connection
.prepare_cached("SELECT topic, node, last_id FROM streams ORDER BY topic, node")?
.query_map([], |row| {
Ok(Head {
topic: row.get(0)?,
node: row.get(1)?,
last_id: row.get(2)?,
})
})?
.collect::<rusqlite::Result<_>>()
.map_err(Error::from)
}
/// A topic and node's last id: 0 if it has none.
pub fn last_id(&self, topic: &str, node: &str) -> Result<u64> {
Ok(find_stream(&self.connection, topic, node)?.map_or(0, |(_, last_id)| last_id))
}
/// The replicated attachments not all here yet, oldest first, `limit`
/// at most: what `SyncState` asks for, and from which part.
pub fn missing_attachments(&self, limit: usize) -> Result<Vec<MissingAttachment>> {
self.connection
.prepare_cached(
"SELECT s.topic, s.node, d.message_id, a.received FROM attachments a \
JOIN data d ON d.key = a.message_key \
JOIN streams s ON s.stream_id = d.stream_id \
WHERE a.state = 'replicating' ORDER BY a.attachment_id LIMIT ?1",
)?
.query_map([limit as i64], |row| {
Ok(MissingAttachment {
topic: row.get(0)?,
node: row.get(1)?,
message_id: row.get(2)?,
next_part: row.get::<_, u64>(3)? / ATTACHMENT_PART_SIZE,
})
})?
.collect::<rusqlite::Result<_>>()
.map_err(Error::from)
}
/// A message's attachment, if it has one (none once the message was
/// deleted).
pub fn attachment(
&self,
topic: &str,
node: &str,
message_id: u64,
) -> Result<Option<Attachment>> {
let Some((stream, _)) = find_stream(&self.connection, topic, node)? else {
return Ok(None);
};
self.connection
.prepare_cached(
"SELECT attachment_id, size, sha256, received, state FROM attachments \
WHERE message_key = ?1 AND state <> 'deleting'",
)?
.query_row(
[message_key(stream, message_id.min(MAX_MESSAGE_ID))],
|row| {
Ok(Attachment {
id: row.get(0)?,
size: row.get(1)?,
sha256: row.get(2)?,
received: row.get(3)?,
state: row.get(4)?,
})
},
)
.optional()
.map_err(Error::from)
}
/// One part of an attachment, if it's here.
pub fn read_part(&self, attachment_id: i64, part: u64) -> Result<Vec<u8>> {
self.connection
.prepare_cached("SELECT part_data FROM attachment_parts WHERE key = ?1")?
.query_row([part_key(attachment_id, part)], |row| row.get(0))
.optional()?
.ok_or_else(|| Error::NotFound(format!("part {part} of attachment {attachment_id}")))
}
fn strings(&self, sql: &str) -> Result<Vec<String>> {
self.connection
.prepare_cached(sql)?
.query_map([], |row| row.get(0))?
.collect::<rusqlite::Result<_>>()
.map_err(Error::from)
}
}
/// A row of `messages()`'s query, as the protocol carries it.
fn entry(row: &Row<'_>) -> rusqlite::Result<MessageEntry> {
let attachment = match row.get::<_, Option<u64>>(3)? {
Some(size) => Some(StoredAttachment {
size,
ready: row.get::<_, AttachmentState>(4)? == AttachmentState::Ready,
}),
None => None,
};
Ok(MessageEntry {
id: message_id(row.get(0)?),
pushed_at: row.get(1)?,
data: row.get(2)?,
attachment,
})
}
@@ -0,0 +1,146 @@
-- BakaShrot's database, schema v9. Read Source/docs/storage.md first: the
-- keys below are packed integers, on purpose, and only bakashrot-storage
-- packs and unpacks them.
--
-- Not compatible with v8 (OldSource/Server/Storage/db_schema_v8.dbml): a
-- database of the old server isn't opened, its data isn't carried over.
-- Needs SQLite 3.38+ (JSON functions, ->>), bundled with the crate.
--
-- Run once, in one transaction, on an empty database (Database::open).
-- Every connection then sets journal_mode = WAL, synchronous (the
-- config's) and busy_timeout. No foreign keys: one writer keeps the tables
-- consistent, the CHECKs keep the values valid.
--
-- Packed keys (storage.md, "Keys"):
-- data.key = stream_id << 43 | message_id
-- attachment_parts.key = attachment_id << 20 | part
-- 8796093022207 below is 2^43 - 1, a message id's mask.
PRAGMA application_id = 1112754260; -- 'BSHT': a BakaShrot database
-- About the database itself. schema_version drives migrations: a database
-- without it, or of a version the server doesn't know, is refused; an older
-- one is migrated a version at a time, each step in one transaction that
-- also sets schema_version.
CREATE TABLE metadata (
name TEXT PRIMARY KEY,
value ANY NOT NULL
) WITHOUT ROWID;
INSERT INTO metadata (name, value) VALUES
('schema_version', 9),
('created_at', CAST(strftime('%s', 'now') AS INTEGER) * 1000);
-- Database::open adds ('created_by', 'bakashrot-storage <version>').
-- A stream: one node's messages in one topic. Message ids count per
-- stream, replication compares streams' last ids, GetMessages reads one.
-- Topics and nodes are only names here: a topic's streams are its rows.
-- last_id is the highest id the stream ever had: deleting messages
-- (retention) leaves it, so ids never go back. Kept by trg_data_last_id.
CREATE TABLE streams (
stream_id INTEGER PRIMARY KEY CHECK (stream_id BETWEEN 1 AND 1048575),
topic TEXT NOT NULL COLLATE NOCASE CHECK (length(topic) BETWEEN 1 AND 64),
node TEXT NOT NULL COLLATE NOCASE CHECK (length(node) BETWEEN 1 AND 64),
last_id INTEGER NOT NULL DEFAULT 0,
UNIQUE (topic, node)
);
-- The messages, in ONE b-tree ordered by (stream, message id): key packs
-- both. A stream's messages sit together, a range of them is a range of
-- keys; no other index to write at every push. stream_id, message_id and
-- is_json are computed when read, never stored. pushed_at: ms since
-- 1970-01-01 UTC, stamped by the server it was pushed to, kept by
-- replication.
CREATE TABLE data (
key INTEGER PRIMARY KEY,
pushed_at INTEGER NOT NULL,
message_data TEXT NOT NULL,
stream_id INTEGER GENERATED ALWAYS AS (key >> 43) VIRTUAL,
message_id INTEGER GENERATED ALWAYS AS (key & 8796093022207) VIRTUAL,
is_json INTEGER GENERATED ALWAYS AS (json_valid(message_data)) VIRTUAL,
CHECK (key & 8796093022207 >= 1)
);
-- A message's attachment (one at most), or one being pushed (no message
-- yet). The states (storage.md, "Attachments"):
-- uploading pushed, its parts coming; message_key is NULL until all
-- came and the message is stored with it, in one
-- transaction. Cut short: deleted, and at every start.
-- replicating its message came from a peer, its parts come after
-- (asked from part received / 1 MiB on).
-- ready all here, its SHA-256 checked.
-- too_big bigger than max_attachment_size: its message is kept,
-- its parts never asked for.
-- deleting its message was deleted: its parts go in the background,
-- then the row.
CREATE TABLE attachments (
attachment_id INTEGER PRIMARY KEY,
message_key INTEGER, -- data.key of its message, NULL while uploading
size INTEGER NOT NULL CHECK (size BETWEEN 1 AND 1099511627776),
sha256 BLOB NOT NULL CHECK (length(sha256) = 32),
received INTEGER NOT NULL DEFAULT 0 CHECK (received BETWEEN 0 AND size),
state TEXT NOT NULL
CHECK (state IN ('uploading', 'replicating', 'ready', 'too_big', 'deleting')),
CHECK ((message_key IS NULL) = (state = 'uploading'))
);
-- A message's attachment, by its message.
CREATE UNIQUE INDEX attachments_message ON attachments (message_key)
WHERE message_key IS NOT NULL;
-- What's left to do: uploads to clean up, parts to ask for, parts to delete.
CREATE INDEX attachments_state ON attachments (state) WHERE state <> 'ready';
-- Its parts, 1 MiB each (ATTACHMENT_PART_SIZE), the last one what's left,
-- in ONE b-tree: key packs the attachment and the part (2^20 parts of
-- 1 MiB is exactly the 1 TiB limit). An attachment's parts are a range of
-- keys, in order.
CREATE TABLE attachment_parts (
key INTEGER PRIMARY KEY,
part_data BLOB NOT NULL
);
-- A stored message moves its stream's last_id (pushes and replication
-- alike).
CREATE TRIGGER trg_data_last_id AFTER INSERT ON data BEGIN
UPDATE streams SET last_id = max(last_id, NEW.key & 8796093022207)
WHERE stream_id = NEW.key >> 43;
END;
-- A deleted message's attachment goes too, in the background.
CREATE TRIGGER trg_data_attachment AFTER DELETE ON data BEGIN
UPDATE attachments SET state = 'deleting' WHERE message_key = OLD.key;
END;
-- What queries read (Query, read-only): the messages by name, no keys.
-- Joined by key range: a topic's or a node's messages are ranges of the
-- table, read in order (storage.md, "The query surface").
-- SELECT * FROM messages WHERE topic = 'logs' AND node = 'kitchen'
CREATE VIEW messages AS
SELECT s.topic,
s.node,
d.message_id,
d.message_data,
d.is_json,
d.pushed_at,
strftime('%Y-%m-%dT%H:%M:%fZ', d.pushed_at / 1000.0, 'unixepoch') AS pushed_utc,
a.size AS attachment_size,
a.state AS attachment_state
FROM streams s
JOIN data d ON d.key BETWEEN (s.stream_id << 43) AND (s.stream_id << 43) + 8796093022207
LEFT JOIN attachments a ON a.message_key = d.key;
-- What to browse with a database tool (v8's): set topic, and node or NULL
-- for all, in its one row, open browse_messages. Never written by the
-- server.
CREATE TABLE browse (
id INTEGER PRIMARY KEY CHECK (id = 1),
topic TEXT COLLATE NOCASE,
node TEXT COLLATE NOCASE
);
CREATE VIEW browse_messages AS
SELECT m.node, m.message_id, m.pushed_utc, m.message_data, m.is_json,
m.attachment_size, m.topic
FROM browse b
JOIN messages m ON m.topic = b.topic
WHERE b.id = 1 AND (b.node IS NULL OR m.node = b.node)
ORDER BY m.pushed_at DESC, m.node, m.message_id DESC;
@@ -0,0 +1,848 @@
//! The storage, end to end on database files: every request's SQL, the
//! limits, refused databases, and readers and writers at once.
use bakashrot_config::Synchronous;
use bakashrot_proto::limits::{ATTACHMENT_PART_SIZE, MAX_MESSAGE_ID};
use bakashrot_proto::packets::{Attachment as Sent, ReplicatedMessage};
use bakashrot_storage::{AttachmentState, Database, Error, MAX_QUERY_ROWS, MAX_STREAMS};
use std::path::PathBuf;
use std::sync::atomic::{AtomicUsize, Ordering};
const PART: usize = ATTACHMENT_PART_SIZE as usize;
/// A fresh database file of its own (in target/, not the temp folder).
fn path(name: &str) -> PathBuf {
static COUNT: AtomicUsize = AtomicUsize::new(0);
let folder = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(format!(
"storage-{}-{}-{name}",
std::process::id(),
COUNT.fetch_add(1, Ordering::Relaxed)
));
let _ = std::fs::remove_dir_all(&folder);
std::fs::create_dir_all(&folder).unwrap();
folder.join("bakashrot.sqlite")
}
fn open(name: &str) -> (Database, PathBuf) {
let path = path(name);
(Database::open(&path, Synchronous::Normal).unwrap(), path)
}
fn ids(messages: &bakashrot_proto::packets::Messages) -> Vec<u64> {
messages.messages.iter().map(|m| m.id).collect()
}
fn replicated(id: u64, pushed_at: u64, attachment: Option<(u64, [u8; 32])>) -> ReplicatedMessage {
ReplicatedMessage {
id,
pushed_at,
data: format!("r{id}"),
attachment: attachment.map(|(size, sha256)| Sent { size, sha256 }),
}
}
#[test]
fn opening() {
let (database, path) = open("opening");
let raw = rusqlite::Connection::open(&path).unwrap();
let meta = |name: &str| -> String {
raw.query_row(
"SELECT CAST(value AS TEXT) FROM metadata WHERE name = ?1",
[name],
|r| r.get(0),
)
.unwrap()
};
assert_eq!(meta("schema_version"), "9");
assert!(meta("created_by").starts_with("bakashrot-storage "));
assert!(meta("created_at").parse::<u64>().unwrap() > 1_700_000_000_000);
let mode: String = raw
.query_row("PRAGMA journal_mode", [], |r| r.get(0))
.unwrap();
assert_eq!(mode, "wal");
drop(database);
// Opened again as it is.
Database::open(&path, Synchronous::Full).unwrap();
// An empty file is made a database.
let empty = self::path("empty");
std::fs::write(&empty, b"").unwrap();
Database::open(&empty, Synchronous::Full).unwrap();
}
#[test]
fn refused_databases() {
let refused = |setup: &str, expected: &str| {
let path = path("refused");
rusqlite::Connection::open(&path)
.unwrap()
.execute_batch(setup)
.unwrap();
match Database::open(&path, Synchronous::Full) {
Err(Error::Unusable(why)) => assert!(why.contains(expected), "{why}"),
other => panic!("{setup}: {other:?}"),
}
};
refused("CREATE TABLE other (x);", "not a BakaShrot database");
refused(
"CREATE TABLE data (x); CREATE TABLE node_heads (y);",
"made by the old server (schema v8)",
);
refused(
"PRAGMA application_id = 1112754260; CREATE TABLE x (y);",
"without its schema version",
);
// A newer version's.
let (database, path) = open("newer");
drop(database);
rusqlite::Connection::open(&path)
.unwrap()
.execute(
"UPDATE metadata SET value = 10 WHERE name = 'schema_version'",
[],
)
.unwrap();
match Database::open(&path, Synchronous::Full) {
Err(Error::Unusable(why)) => assert!(why.contains("schema v10, made by a newer"), "{why}"),
other => panic!("{other:?}"),
}
}
#[test]
fn pushing_and_reading() {
let (database, _) = open("push");
let mut writer = database.writer().unwrap();
let reader = database.reader().unwrap();
// A group commit: ids per topic and node, names without case.
let ids_pushed = writer
.batch(|batch| {
Ok(vec![
batch.push("logs", "kitchen", 1000, "{\"t\":1}")?,
batch.push("logs", "kitchen", 1001, "not json")?,
batch.push("LOGS", "Kitchen", 1002, "{}")?,
batch.push("logs", "garage", 1003, "{}")?,
batch.push("sensors", "kitchen", 1004, "{}")?,
])
})
.unwrap();
assert_eq!(ids_pushed, [1, 2, 3, 1, 1]);
let all = reader.messages("logs", "kitchen", Some(0), 100).unwrap();
assert_eq!(ids(&all), [1, 2, 3]);
assert!(!all.more);
assert_eq!(all.messages[1].data, "not json");
assert_eq!(all.messages[0].pushed_at, 1000);
assert!(all.messages[0].attachment.is_none());
// after, limit, more; the latest ones, in order.
let some = reader.messages("logs", "kitchen", Some(1), 1).unwrap();
assert_eq!((ids(&some), some.more), (vec![2], true));
let latest = reader.messages("Logs", "KITCHEN", None, 2).unwrap();
assert_eq!((ids(&latest), latest.more), (vec![2, 3], false));
assert!(
reader
.messages("logs", "kitchen", Some(3), 10)
.unwrap()
.messages
.is_empty()
);
// A node without any message, in any topic: unknown.
assert!(matches!(
reader.messages("logs", "nobody", None, 10),
Err(Error::UnknownName(_))
));
assert!(
reader
.messages("logs", "kitchen", Some(MAX_MESSAGE_ID), 10)
.unwrap()
.messages
.is_empty()
);
// Names, heads.
assert_eq!(reader.topics().unwrap(), ["logs", "sensors"]);
assert_eq!(reader.nodes().unwrap(), ["garage", "kitchen"]);
let heads: Vec<_> = reader
.heads()
.unwrap()
.into_iter()
.map(|h| (h.topic, h.node, h.last_id))
.collect();
assert_eq!(
heads,
[
("logs".into(), "garage".into(), 1),
("logs".into(), "kitchen".into(), 3),
("sensors".into(), "kitchen".into(), 1)
]
);
assert_eq!(reader.last_id("logs", "kitchen").unwrap(), 3);
assert_eq!(reader.last_id("nope", "kitchen").unwrap(), 0);
}
#[test]
fn answers_stop_at_about_a_megabyte() {
let (database, _) = open("bytes");
let mut writer = database.writer().unwrap();
let big = "x".repeat(400 * 1024);
writer
.batch(|batch| {
for _ in 0..5 {
batch.push("logs", "kitchen", 1, &big)?;
}
batch.push("logs", "kitchen", 1, &"y".repeat(3 * 1024 * 1024))?;
Ok(())
})
.unwrap();
let reader = database.reader().unwrap();
let first = reader.messages("logs", "kitchen", Some(0), 100).unwrap();
assert_eq!((ids(&first), first.more), (vec![1, 2], true));
let next = reader.messages("logs", "kitchen", Some(4), 100).unwrap();
assert_eq!((ids(&next), next.more), (vec![5], true));
// A bigger message goes alone.
let alone = reader.messages("logs", "kitchen", Some(5), 100).unwrap();
assert_eq!((ids(&alone), alone.more), (vec![6], false));
}
#[test]
fn uploads() {
let (database, path) = open("uploads");
let mut writer = database.writer().unwrap();
let size = (2 * PART + 10) as u64;
let sha = [7; 32];
let upload = writer.batch(|b| b.start_upload(size, &sha)).unwrap();
let part = |n: usize| vec![n as u8; if n == 2 { 10 } else { PART }];
// Only in order, each its size.
assert!(matches!(
writer.batch(|b| b.write_part(upload, 1, &part(1))),
Err(Error::Invalid(_))
));
assert!(matches!(
writer.batch(|b| b.write_part(upload, 0, &[0; 10])),
Err(Error::Invalid(_))
));
assert!(!writer.batch(|b| b.write_part(upload, 0, &part(0))).unwrap());
assert!(!writer.batch(|b| b.write_part(upload, 1, &part(1))).unwrap());
// Not complete: no push with it, and the batch goes on after.
let pushed = writer
.batch(|b| {
assert!(matches!(
b.push_with_attachment(upload, "logs", "kitchen", 1, "{}"),
Err(Error::Invalid(_))
));
b.push("logs", "kitchen", 1, "without")
})
.unwrap();
assert_eq!(pushed, 1);
assert!(writer.batch(|b| b.write_part(upload, 2, &part(2))).unwrap());
assert!(matches!(
writer.batch(|b| b.write_part(upload, 3, &[1])),
Err(Error::Invalid(_))
));
let id = writer
.batch(|b| b.push_with_attachment(upload, "logs", "kitchen", 2, "with"))
.unwrap();
assert_eq!(id, 2);
let reader = database.reader().unwrap();
let message = &reader
.messages("logs", "kitchen", Some(1), 1)
.unwrap()
.messages[0];
let stored = message.attachment.as_ref().unwrap();
assert_eq!((stored.size, stored.ready), (size, true));
let attachment = reader.attachment("logs", "kitchen", 2).unwrap().unwrap();
assert_eq!(
(attachment.state, attachment.sha256, attachment.received),
(AttachmentState::Ready, sha, size)
);
assert_eq!(reader.read_part(attachment.id, 1).unwrap(), part(1));
assert_eq!(reader.read_part(attachment.id, 2).unwrap(), part(2));
assert!(matches!(
reader.read_part(attachment.id, 3),
Err(Error::NotFound(_))
));
assert!(reader.attachment("logs", "kitchen", 1).unwrap().is_none());
// Cancelled, or left over at a restart: gone with their parts.
let cancelled = writer.batch(|b| b.start_upload(5, &sha)).unwrap();
writer
.batch(|b| b.write_part(cancelled, 0, &[1; 5]))
.unwrap();
writer.batch(|b| b.cancel_upload(cancelled)).unwrap();
assert!(matches!(
writer.batch(|b| b.cancel_upload(cancelled)),
Err(Error::NotFound(_))
));
let left = writer.batch(|b| b.start_upload(5, &sha)).unwrap();
writer.batch(|b| b.write_part(left, 0, &[1; 5])).unwrap();
drop((writer, reader, database));
Database::open(&path, Synchronous::Normal).unwrap();
let raw = rusqlite::Connection::open(&path).unwrap();
let count = |sql: &str| raw.query_row(sql, [], |r| r.get::<_, i64>(0)).unwrap();
assert_eq!(count("SELECT count(*) FROM attachments"), 1);
assert_eq!(count("SELECT count(*) FROM attachment_parts"), 3);
// Sizes.
let database = Database::open(&path, Synchronous::Normal).unwrap();
let mut writer = database.writer().unwrap();
assert!(matches!(
writer.batch(|b| b.start_upload(0, &sha)),
Err(Error::TooBig(_))
));
assert!(matches!(
writer.batch(|b| b.start_upload((1 << 40) + 1, &sha)),
Err(Error::TooBig(_))
));
}
#[test]
fn replication() {
let (database, _) = open("replication");
let mut writer = database.writer().unwrap();
let reader = database.reader().unwrap();
let sha = [3; 32];
let last = writer
.batch(|b| {
b.replicate(
"logs",
"kitchen",
&[
replicated(5, 100, None),
replicated(9, 200, Some((PART as u64 + 1, sha))),
replicated(12, 300, Some((50, sha))),
],
1000,
)
})
.unwrap();
assert_eq!(last, 12);
// Ones already here are kept as they are; the head never goes back.
let again = writer
.batch(|b| {
b.replicate(
"logs",
"kitchen",
&[ReplicatedMessage {
data: "other".into(),
..replicated(5, 1, None)
}],
1000,
)
})
.unwrap();
assert_eq!(again, 12);
let stored = reader.messages("logs", "kitchen", Some(0), 10).unwrap();
assert_eq!(ids(&stored), [5, 9, 12]);
assert_eq!(stored.messages[0].data, "r5");
// A push goes on after the replicated ids.
assert_eq!(
writer
.batch(|b| b.push("logs", "kitchen", 400, "{}"))
.unwrap(),
13
);
// Attachments: too big here, or to ask for.
let big = reader.attachment("logs", "kitchen", 9).unwrap().unwrap();
assert_eq!(big.state, AttachmentState::TooBig);
assert!(!stored.messages[1].attachment.as_ref().unwrap().ready);
let missing = reader.missing_attachments(256).unwrap();
assert_eq!(missing.len(), 1);
assert_eq!((missing[0].message_id, missing[0].next_part), (12, 0));
// Its parts; a mismatch starts it over; a match makes it ready.
let small = reader.attachment("logs", "kitchen", 12).unwrap().unwrap();
assert!(
writer
.batch(|b| b.write_part(small.id, 0, &[1; 50]))
.unwrap()
);
writer
.batch(|b| b.finish_replicated(small.id, false))
.unwrap();
assert_eq!(
reader
.attachment("logs", "kitchen", 12)
.unwrap()
.unwrap()
.received,
0
);
assert_eq!(reader.missing_attachments(256).unwrap()[0].next_part, 0);
assert!(
writer
.batch(|b| b.write_part(small.id, 0, &[2; 50]))
.unwrap()
);
writer
.batch(|b| b.finish_replicated(small.id, true))
.unwrap();
assert_eq!(
reader
.attachment("logs", "kitchen", 12)
.unwrap()
.unwrap()
.state,
AttachmentState::Ready
);
assert!(reader.missing_attachments(256).unwrap().is_empty());
assert!(matches!(
writer.batch(|b| b.finish_replicated(small.id, true)),
Err(Error::Invalid(_))
));
assert!(matches!(
writer.batch(|b| b.write_part(big.id, 0, &[0; PART])),
Err(Error::Invalid(_))
));
// A resumed one: next_part follows what came.
writer
.batch(|b| {
b.replicate(
"logs",
"garage",
&[replicated(1, 1, Some((2 * PART as u64, sha)))],
u64::MAX,
)
})
.unwrap();
let resumed = reader.attachment("logs", "garage", 1).unwrap().unwrap();
writer
.batch(|b| b.write_part(resumed.id, 0, &[0; PART]))
.unwrap();
let missing = reader.missing_attachments(256).unwrap();
assert_eq!(
(missing[0].node.as_str(), missing[0].next_part),
("garage", 1)
);
// Ids out of range.
assert!(matches!(
writer.batch(|b| b.replicate("logs", "kitchen", &[replicated(0, 1, None)], 0)),
Err(Error::Invalid(_))
));
}
#[test]
fn retention() {
let (database, _) = open("retention");
let mut writer = database.writer().unwrap();
let reader = database.reader().unwrap();
writer
.batch(|b| {
for at in 1..=10 {
b.push("logs", "kitchen", at * 100, "{}")?;
b.push("logs", "garage", at * 100 + 50, "{}")?;
b.push("sensors", "kitchen", at * 100, "{}")?;
}
Ok(())
})
.unwrap();
// An attachment on an old message.
let upload = writer
.batch(|b| b.start_upload(3 * PART as u64, &[1; 32]))
.unwrap();
for part in 0..3 {
writer
.batch(|b| b.write_part(upload, part, &[0; PART]))
.unwrap();
}
writer
.batch(|b| b.push_with_attachment(upload, "logs", "kitchen", 120, "{}"))
.unwrap();
// Before 500: kitchen 1-4 and 11 (pushed at 120, after 4: in id order, it
// waits for 5-10), garage 1-4. A limit, then the rest.
assert_eq!(
writer.batch(|b| b.delete_before("logs", 500, 5)).unwrap(),
5
);
assert_eq!(
writer.batch(|b| b.delete_before("logs", 500, 100)).unwrap(),
3
);
assert_eq!(
writer.batch(|b| b.delete_before("logs", 500, 100)).unwrap(),
0
);
assert_eq!(
ids(&reader.messages("logs", "kitchen", Some(0), 100).unwrap()),
[5, 6, 7, 8, 9, 10, 11]
);
assert_eq!(
ids(&reader.messages("logs", "garage", Some(0), 100).unwrap()).len(),
6
);
assert_eq!(
ids(&reader.messages("sensors", "kitchen", Some(0), 100).unwrap()).len(),
10
);
// Everything: the heads stay, ids go on.
assert_eq!(
writer
.batch(|b| b.delete_before("logs", u64::MAX, 1000))
.unwrap(),
13
);
assert_eq!(reader.last_id("logs", "kitchen").unwrap(), 11);
assert_eq!(
writer
.batch(|b| b.push("logs", "kitchen", 2000, "{}"))
.unwrap(),
12
);
// The attachment's parts go in batches, then its row.
assert_eq!(reader.attachment("logs", "kitchen", 11).unwrap(), None);
assert_eq!(writer.batch(|b| b.purge_attachments(2)).unwrap(), 2);
assert_eq!(writer.batch(|b| b.purge_attachments(2)).unwrap(), 1);
assert_eq!(writer.batch(|b| b.purge_attachments(2)).unwrap(), 0);
assert!(matches!(
reader.read_part(upload, 2),
Err(Error::NotFound(_))
));
}
#[test]
fn vacuum() {
let (database, path) = open("vacuum");
let mut writer = database.writer().unwrap();
let big = "x".repeat(10_000);
writer
.batch(|b| {
for _ in 0..1000 {
b.push("logs", "kitchen", 1, &big)?;
}
Ok(())
})
.unwrap();
writer.vacuum().unwrap();
let full = std::fs::metadata(&path).unwrap().len();
writer
.batch(|b| b.delete_before("logs", u64::MAX, 10_000))
.unwrap();
writer.vacuum().unwrap();
let emptied = std::fs::metadata(&path).unwrap().len();
assert!(emptied * 10 < full, "{full} -> {emptied}");
// Still the same database: ids go on.
assert_eq!(
writer
.batch(|b| b.push("logs", "kitchen", 2, "{}"))
.unwrap(),
1001
);
}
#[test]
fn limits() {
let (database, path) = open("limits");
let mut writer = database.writer().unwrap();
writer
.batch(|b| b.push("logs", "kitchen", 1, "{}"))
.unwrap();
let raw = rusqlite::Connection::open(&path).unwrap();
// A topic and node with no id left.
raw.execute("UPDATE streams SET last_id = ?1", [MAX_MESSAGE_ID as i64])
.unwrap();
assert!(matches!(
writer.batch(|b| b.push("logs", "kitchen", 1, "{}")),
Err(Error::TooBig(_))
));
// No stream left.
raw.execute(
"INSERT INTO streams (stream_id, topic, node) VALUES (?1, 'x', 'y')",
[MAX_STREAMS],
)
.unwrap();
assert!(matches!(
writer.batch(|b| b.push("new", "kitchen", 1, "{}")),
Err(Error::TooBig(_))
));
// The highest key there is.
raw.execute(
"UPDATE streams SET last_id = ?1 - 1 WHERE topic = 'x'",
[MAX_MESSAGE_ID as i64],
)
.unwrap();
assert_eq!(
writer.batch(|b| b.push("x", "y", 1, "last")).unwrap(),
MAX_MESSAGE_ID
);
let reader = database.reader().unwrap();
let last = reader.messages("x", "y", None, 1).unwrap();
assert_eq!(
(last.messages[0].id, last.messages[0].data.as_str()),
(MAX_MESSAGE_ID, "last")
);
}
#[test]
fn queries() {
let (database, _) = open("queries");
let mut writer = database.writer().unwrap();
writer
.batch(|b| {
b.push("logs", "kitchen", 1_700_000_000_000, "{\"t\": 21.5}")?;
b.push("logs", "kitchen", 1_700_000_000_001, "not json")?;
b.push("logs", "garage", 1_700_000_000_002, "{\"t\": 3}")
})
.unwrap();
let runner = database.query_runner().unwrap();
let json = |sql: &str| -> serde_json::Value {
serde_json::from_str(&runner.run(sql).unwrap()).unwrap()
};
let result = json(
"SELECT topic, node, message_id, is_json, pushed_utc, message_data ->> '$.t' AS t, \
attachment_size FROM messages WHERE topic = 'logs' AND node = 'kitchen' AND is_json = 1",
);
assert_eq!(
result,
serde_json::json!({
"columns": ["topic", "node", "message_id", "is_json", "pushed_utc", "t", "attachment_size"],
"rows": [["logs", "kitchen", "1", "1", "2023-11-14T22:13:20.000Z", "21.5", null]]
})
);
assert_eq!(
json("SELECT x'00ff', 1.0, NULL")["rows"],
serde_json::json!([["00ff", "1.0", null]])
);
assert_eq!(
json("SELECT count(*) FROM messages")["rows"],
serde_json::json!([["3"]])
);
// Refused: writes, whatever their form, more than one statement, no rows to give.
for sql in [
"DELETE FROM data",
"WITH x AS (SELECT 1) DELETE FROM data",
"INSERT INTO browse VALUES (1, 'logs', NULL)",
"PRAGMA query_only = 0",
"SELECT 1; DELETE FROM data",
"CREATE TABLE t (x)",
"ATTACH 'other.sqlite' AS other",
"SELEKT 1",
] {
assert!(matches!(runner.run(sql), Err(Error::Query(_))), "{sql}");
}
// A failing row fails it all, with SQLite's message.
match runner.run("SELECT message_data ->> '$.t' FROM messages") {
Err(Error::Query(why)) => assert!(why.contains("malformed JSON"), "{why}"),
other => panic!("{other:?}"),
}
// Too big.
let rows = format!(
"WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i <= {MAX_QUERY_ROWS}) SELECT i FROM n"
);
assert!(matches!(runner.run(&rows), Err(Error::TooBig(_))));
assert!(matches!(
runner.run("WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 20) SELECT zeroblob(1000000) FROM n"),
Err(Error::TooBig(_))
));
// Still nothing written.
assert_eq!(
json("SELECT count(*) FROM data")["rows"],
serde_json::json!([["3"]])
);
}
#[test]
fn the_view_reads_by_key_range() {
let (database, path) = open("plans");
drop(database);
let raw = rusqlite::Connection::open(&path).unwrap();
for sql in [
"SELECT * FROM messages WHERE topic = 'logs' AND node = 'kitchen'",
"SELECT * FROM messages WHERE topic = 'logs' AND pushed_at > 5",
"SELECT * FROM messages WHERE topic = 'logs' AND node = 'kitchen' ORDER BY message_id DESC LIMIT 5",
] {
let plan: Vec<String> = raw
.prepare(&format!("EXPLAIN QUERY PLAN {sql}"))
.unwrap()
.query_map([], |r| r.get(3))
.unwrap()
.collect::<Result<_, _>>()
.unwrap();
let plan = plan.join(" | ");
assert!(
plan.contains("INTEGER PRIMARY KEY (rowid>? AND rowid<?)"),
"{sql}: {plan}"
);
assert!(!plan.contains("SCAN d"), "{sql}: {plan}");
}
}
#[test]
fn readers_while_writing() {
let (database, _) = open("concurrent");
let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let readers: Vec<_> = (0..3)
.map(|_| {
let database = database.clone();
let stop = stop.clone();
std::thread::spawn(move || {
let reader = database.reader().unwrap();
let mut seen = 0;
let mut reads = 0;
while !stop.load(Ordering::Relaxed) {
let latest = match reader.messages("logs", "kitchen", None, 10) {
// Not pushed to yet.
Err(Error::UnknownName(_)) => continue,
latest => latest.unwrap(),
};
let ids = ids(&latest);
assert!(ids.windows(2).all(|w| w[1] == w[0] + 1), "{ids:?}");
let last = ids.last().copied().unwrap_or(0);
assert!(last >= seen, "went back: {last} < {seen}");
seen = last;
reads += 1;
}
reads
})
})
.collect();
// Two writers at once: the second waits for the first's transactions.
let writers: Vec<_> = ["kitchen", "garage"]
.into_iter()
.map(|node| {
let database = database.clone();
std::thread::spawn(move || {
let mut writer = database.writer().unwrap();
for batch in 0..100 {
writer
.batch(|b| {
for i in 0..20 {
b.push("logs", node, batch * 20 + i, "{}")?;
}
Ok(())
})
.unwrap();
}
})
})
.collect();
for writer in writers {
writer.join().unwrap();
}
stop.store(true, Ordering::Relaxed);
for reader in readers {
assert!(reader.join().unwrap() > 0);
}
let reader = database.reader().unwrap();
assert_eq!(reader.last_id("logs", "kitchen").unwrap(), 2000);
assert_eq!(reader.last_id("logs", "garage").unwrap(), 2000);
}
/// The same workload as the old storage's benchmark
/// (`OldSource\Build\Bench\StorageBenchOld.exe`), to compare them: pushes
/// over 100 topics x 5 nodes (an LCG picks them), 100 per batch, 200-byte
/// JSON; 2000 latest-message reads, 500 reads of 1000 messages after the
/// middle id, the file's size, retention of 10% of one topic. Not run by
/// default: `PUSHES=1000000 SYNC=normal cargo test --release -p
/// bakashrot-storage -- --ignored --nocapture`.
#[test]
#[ignore]
fn compare_with_old() {
use std::time::Instant;
let count: u64 = std::env::var("PUSHES").map_or(1_000_000, |n| n.parse().unwrap());
let sync = std::env::var("SYNC").unwrap_or_else(|_| "normal".into());
let synchronous = if sync == "full" {
Synchronous::Full
} else {
Synchronous::Normal
};
let path = path("compare");
let database = Database::open(&path, synchronous).unwrap();
let mut writer = database.writer().unwrap();
let prefix = r#"{"kind":"temp","value":21.37,"ts":1700000000,"pad":""#;
let json = format!("{prefix}{}\"}}", "x".repeat(200 - prefix.len() - 2));
assert_eq!(json.len(), 200);
let topics: Vec<String> = (0..100).map(|t| format!("topic{t}")).collect();
let nodes: Vec<String> = (0..5).map(|n| format!("node{n}")).collect();
// Checkpoints every second on their own connection, as the server's
// (and the old server's) thread does.
let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let checkpoints = {
let checkpointer = database.checkpointer().unwrap();
let stop = stop.clone();
std::thread::spawn(move || {
while !stop.load(Ordering::Relaxed) {
std::thread::sleep(std::time::Duration::from_secs(1));
checkpointer.checkpoint().unwrap();
}
})
};
let mut state: u64 = 1;
let start = Instant::now();
for batch in 0..count / 100 {
writer
.batch(|b| {
for i in 0..100 {
state = state
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407);
let x = (state >> 33) & 0x7FFF_FFFF;
let at = 1_700_000_000_000 + (batch * 100 + i) * 10;
b.push(
&topics[(x % 100) as usize],
&nodes[(x / 100 % 5) as usize],
at,
&json,
)?;
}
Ok(())
})
.unwrap();
}
let pushing = start.elapsed().as_secs_f64();
stop.store(true, Ordering::Relaxed);
checkpoints.join().unwrap();
let reader = database.reader().unwrap();
let pick = |i: usize| (&topics[i * 37 % 100], &nodes[i * 3 % 5]);
let middle: Vec<u64> = (0..500)
.map(|i| reader.last_id(pick(i).0, pick(i).1).unwrap() / 2)
.collect();
let start = Instant::now();
for i in 0..2000 {
reader.messages(pick(i).0, pick(i).1, None, 1).unwrap();
}
let latest = start.elapsed().as_secs_f64() * 1000.0 / 2000.0;
let start = Instant::now();
let mut read = 0;
for (i, after) in middle.iter().enumerate() {
read += reader
.messages(pick(i).0, pick(i).1, Some(*after), 1000)
.unwrap()
.messages
.len();
}
let after = start.elapsed().as_secs_f64() * 1000.0 / 500.0;
rusqlite::Connection::open(&path)
.unwrap()
.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(()))
.unwrap();
let size = std::fs::metadata(&path).unwrap().len();
let start = Instant::now();
let cutoff = 1_700_000_000_000 + count / 10 * 10;
let deleted = writer
.batch(|b| b.delete_before("topic0", cutoff, 100_000_000))
.unwrap();
let retention = start.elapsed().as_secs_f64() * 1000.0;
println!(
"new {sync}: {count} pushes in {pushing:.1} s = {:.0}/s | file {:.0} MB | latest {latest:.3} ms | 1000 after {after:.3} ms ({read} read) | retention {deleted} in {retention:.0} ms",
count as f64 / pushing,
size as f64 / 1e6
);
}
+34
View File
@@ -0,0 +1,34 @@
[package]
name = "bakashrot-tools"
description = "BakaShrot's command-line tools: bakashrot pushes and reads messages, bakashrot-cert issues certificates and revokes them."
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
authors.workspace = true
repository.workspace = true
publish.workspace = true
# No API to document, and its name is the DLL's library's (cargo doc would
# collide).
[[bin]]
name = "bakashrot"
doc = false
[dependencies]
bakashrot-client = { path = "../bakashrot-client" }
bakashrot-pki = { path = "../bakashrot-pki" }
bakashrot-proto = { path = "../bakashrot-proto" }
clap = { version = "4", features = ["derive"] }
serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.154"
time = "0.3.55"
toml = { version = "1.2.1", default-features = false, features = ["std", "parse", "serde"] }
[dev-dependencies]
bakashrot-config = { path = "../bakashrot-config" }
bakashrot-server = { path = "../bakashrot-server" }
tokio = { version = "1.54.1", features = ["rt-multi-thread", "net"] }
[lints]
workspace = true
@@ -0,0 +1,241 @@
//! `bakashrot-cert`: makes a CA, issues certificates, revokes them, shows
//! them. Every file is PEM; keys are written once, never over an existing
//! file. See `Source/docs/certificates.md`.
use bakashrot_pki::{
CA_DAYS, CERTIFICATE_DAYS, Ca, IDENTITY_OID_IS_PLACEHOLDER, Identity, Revocations, Usage,
summarize,
};
use clap::{Parser, Subcommand};
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::ExitCode;
#[derive(Parser)]
#[command(
name = "bakashrot-cert",
version,
about = "Issues and revokes BakaShrot's certificates"
)]
struct Cli {
#[command(subcommand)]
command: Command,
}
#[derive(Subcommand)]
enum Command {
/// Makes a new CA: ca.crt and ca.key in --out. Keep ca.key off the
/// servers: whoever has it can make any identity.
Ca {
/// The CA's name (its certificate's CN).
#[arg(long)]
name: String,
/// How long it's valid, in days.
#[arg(long, default_value_t = CA_DAYS)]
days: u32,
/// Where to write ca.crt and ca.key.
#[arg(long, default_value = ".")]
out: PathBuf,
},
/// Issues a certificate for a node: NAME.crt and NAME.key in --out
/// (or --file's).
Issue {
/// The node's name.
#[arg(long)]
name: String,
/// A role, any number of times (the server's config says what each
/// may do).
#[arg(long = "role")]
roles: Vec<String>,
/// A server's certificate (clients and peers connect to it), not a
/// client's.
#[arg(long)]
server: bool,
/// How long it's valid, in days.
#[arg(long, default_value_t = CERTIFICATE_DAYS)]
days: u32,
/// The folder of ca.crt and ca.key.
#[arg(long, default_value = ".")]
ca: PathBuf,
/// Where to write the certificate and its key.
#[arg(long, default_value = ".")]
out: PathBuf,
/// The files' name, without .crt and .key (the node's name by
/// default): another certificate for the same name, beside the
/// first one (two servers of the same name, a new one before the
/// old one is revoked).
#[arg(long)]
file: Option<String>,
},
/// Revokes certificates: (re)writes ca.crl in --ca, with every one
/// revoked before. Push it to the servers' folders.
Revoke {
/// The certificates to revoke.
#[arg(required = true)]
certificates: Vec<PathBuf>,
/// The folder of ca.crt, ca.key and ca.crl.
#[arg(long, default_value = ".")]
ca: PathBuf,
/// When to expect the next CRL, in days.
#[arg(long, default_value_t = CERTIFICATE_DAYS)]
days: u32,
},
/// Shows what a certificate says.
Show {
/// The certificate.
certificate: PathBuf,
},
}
fn main() -> ExitCode {
match run(Cli::parse().command) {
Ok(()) => ExitCode::SUCCESS,
Err(error) => {
eprintln!("bakashrot-cert: {error}");
ExitCode::FAILURE
}
}
}
/// Said whenever a certificate is made while the OID is the placeholder.
const PLACEHOLDER_WARNING: &str = "warning: the identity extension's OID is still a placeholder \
(Source/docs/oid.md): fine for tests, not for certificates in use";
fn run(command: Command) -> Result<(), String> {
if IDENTITY_OID_IS_PLACEHOLDER && matches!(command, Command::Ca { .. } | Command::Issue { .. })
{
eprintln!("{PLACEHOLDER_WARNING}");
}
match command {
Command::Ca { name, days, out } => {
let ca = Ca::create(&name, days).map_err(|e| e.to_string())?;
write_new(&out.join("ca.crt"), &ca.certificate, false)?;
write_new(&out.join("ca.key"), &ca.key, true)?;
}
Command::Issue {
name,
roles,
server,
days,
ca,
out,
file,
} => {
let roles: Vec<&str> = roles.iter().map(String::as_str).collect();
let identity = Identity::new(&name, &roles).map_err(|e| e.to_string())?;
let usage = if server { Usage::Server } else { Usage::Client };
let issued = load_ca(&ca)?
.issue(&identity, usage, days)
.map_err(|e| e.to_string())?;
let file = file.unwrap_or(name);
write_new(&out.join(format!("{file}.crt")), &issued.certificate, false)?;
write_new(&out.join(format!("{file}.key")), &issued.key, true)?;
}
Command::Revoke {
certificates,
ca: folder,
days,
} => revoke(&folder, &certificates, days)?,
Command::Show { certificate } => show(&certificate)?,
}
Ok(())
}
fn read(path: &Path) -> Result<String, String> {
fs::read_to_string(path).map_err(|error| format!("{}: {error}", path.display()))
}
fn load_ca(folder: &Path) -> Result<Ca, String> {
Ca::load(
&read(&folder.join("ca.crt"))?,
&read(&folder.join("ca.key"))?,
)
.map_err(|error| format!("the CA in {}: {error}", folder.display()))
}
/// Writes a new file, never over an existing one; a key readable by its
/// owner only (on Unix).
fn write_new(path: &Path, text: &str, private: bool) -> Result<(), String> {
let mut options = fs::OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
if private {
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
#[cfg(not(unix))]
let _ = private;
let mut file = options
.open(path)
.map_err(|error| format!("{}: {error}", path.display()))?;
file.write_all(text.as_bytes())
.map_err(|error| format!("{}: {error}", path.display()))?;
println!("Wrote {}", path.display());
Ok(())
}
fn revoke(folder: &Path, certificates: &[PathBuf], days: u32) -> Result<(), String> {
let ca = load_ca(folder)?;
let ca_certificate = read(&folder.join("ca.crt"))?;
let crl_path = folder.join("ca.crl");
// Those revoked before stay revoked.
let mut serials: Vec<Vec<u8>> = if crl_path.exists() {
Revocations::load(&read(&crl_path)?, &ca_certificate)
.map_err(|error| format!("{}: {error}", crl_path.display()))?
.serials()
.map(<[u8]>::to_vec)
.collect()
} else {
Vec::new()
};
for path in certificates {
let certificate = read(path)?;
if !ca
.issued(&certificate)
.map_err(|e| format!("{}: {e}", path.display()))?
{
return Err(format!("{}: not issued by this CA", path.display()));
}
let summary = summarize(&certificate).map_err(|e| format!("{}: {e}", path.display()))?;
if !serials.contains(&summary.serial) {
serials.push(summary.serial);
}
println!("Revoked {} ({})", path.display(), summary.subject);
}
// Written aside then moved: a server reading it never sees half of it.
let crl = ca
.revocation_list(&serials, days)
.map_err(|e| e.to_string())?;
let temporary = folder.join("ca.crl.new");
fs::write(&temporary, crl).map_err(|error| format!("{}: {error}", temporary.display()))?;
fs::rename(&temporary, &crl_path)
.map_err(|error| format!("{}: {error}", crl_path.display()))?;
println!("Wrote {} ({} revoked)", crl_path.display(), serials.len());
Ok(())
}
fn show(path: &Path) -> Result<(), String> {
let summary = summarize(&read(path)?).map_err(|e| format!("{}: {e}", path.display()))?;
println!("{}", path.display());
match &summary.identity {
Some(identity) => {
println!(" name: {}", identity.name);
println!(" roles: {}", identity.roles.join(", "));
}
None => println!(" subject: {}", summary.subject),
}
let usage = match (summary.is_ca, summary.usage) {
(true, _) => "CA",
(false, Some(Usage::Server)) => "server",
(false, Some(Usage::Client)) => "client",
(false, None) => "other",
};
println!(" usage: {usage}");
println!(" issuer: {}", summary.issuer);
println!(" valid: {} to {}", summary.not_before, summary.not_after);
println!(" serial: {}", summary.serial_hex());
Ok(())
}
@@ -0,0 +1,388 @@
//! `bakashrot`: pushes messages, reads them and their attachments, runs
//! queries and lists names from the command line, connecting with a
//! `client.toml`. The old `BakaShrot*` tools in one program; see
//! `Source/docs/client.md`, "The tools".
use bakashrot_client::{Client, Error, Settings};
use bakashrot_proto::error::{code_name, is_refusal_code};
use bakashrot_proto::limits::MAX_MESSAGES_PER_PACKET;
use bakashrot_proto::packets::{MessageEntry, NameKind};
use clap::{Parser, Subcommand, ValueEnum};
use serde::Deserialize;
use std::fs;
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::time::Duration;
#[derive(Parser)]
#[command(
name = "bakashrot",
version,
about = "Pushes and reads BakaShrot's messages",
after_help = "Exits with 0 on success, 1 on a failure, 2 on bad arguments."
)]
struct Cli {
/// The client's settings: the server, the CA's certificate, this
/// client's certificate and key, the CRL.
#[arg(short, long, global = true, default_value = "client.toml")]
config: PathBuf,
#[command(subcommand)]
command: Command,
}
#[derive(Subcommand)]
enum Command {
/// Pushes a message as this client's node, prints its id.
Push {
/// The topic to push to.
topic: String,
/// The message (JSON or any text), @FILE for a file's, - for the
/// standard input's (PowerShell before 7.3 drops the double quotes
/// inside arguments: use @FILE or - there).
message: String,
/// A file to attach (1 byte and up, as much as the server takes):
/// the message is stored once all of it came.
#[arg(short, long)]
attachment: Option<PathBuf>,
},
/// Prints a topic and node's latest message: its id, when it was pushed
/// (UTC), its attachment if it has one, then its data.
Latest {
/// The topic.
topic: String,
/// The node that pushed it.
node: String,
},
/// Saves a message's attachment as FILE (replaced), checked with its
/// SHA-256, and prints its size. A failed one leaves no file.
Attachment {
/// The topic.
topic: String,
/// The node that pushed it.
node: String,
/// The message's id.
id: u64,
/// Where to save it.
file: PathBuf,
},
/// Prints a topic and node's messages in order, a line each: its id, a
/// tab, its data as stored (a line break in it spans lines).
Messages {
/// The topic.
topic: String,
/// The node that pushed them.
node: String,
/// Starts after this message id: 0 from the first one, "latest"
/// after the latest one (only new ones, with --follow).
#[arg(long, default_value = "0", value_parser = after)]
after: After,
/// Stops after this many, 0 for no limit [default: 100, none with
/// --follow].
#[arg(long)]
limit: Option<u64>,
/// Keeps going once caught up, checking every --interval, until
/// stopped (Ctrl+C) or the connection fails.
#[arg(short, long)]
follow: bool,
/// How often --follow checks, in milliseconds.
#[arg(long, default_value_t = 500, value_parser = clap::value_parser!(u64).range(10..=3_600_000))]
interval: u64,
/// Also prints when each was pushed (UTC), between its id and its
/// data.
#[arg(short, long)]
time: bool,
},
/// Runs read-only SQL on the server, prints its result as JSON:
/// {"columns":[...],"rows":[[...],...]}. The client's roles must allow
/// queries.
Query {
/// One SELECT (or WITH ... SELECT), @FILE for a file's, - for the
/// standard input's.
sql: String,
},
/// Lists the topics this client may use (every one if it may query) and
/// the nodes with messages.
List {
/// What to list.
#[arg(value_enum, default_value_t = What::All)]
what: What,
/// Prints JSON, a line per list: {"kind":...,"names":[...],"truncated":...}.
#[arg(long)]
json: bool,
},
}
/// Where `messages` starts.
#[derive(Clone, Copy)]
enum After {
Id(u64),
Latest,
}
fn after(text: &str) -> Result<After, String> {
if text.eq_ignore_ascii_case("latest") {
return Ok(After::Latest);
}
text.parse()
.map(After::Id)
.map_err(|_| "a message id or \"latest\"".to_owned())
}
#[derive(Clone, Copy, ValueEnum)]
enum What {
Topics,
Nodes,
All,
}
/// `client.toml`: paths are relative to its folder.
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct ClientToml {
server: String,
ca: PathBuf,
certificate: PathBuf,
key: PathBuf,
crl: Option<PathBuf>,
}
fn main() -> ExitCode {
let cli = Cli::parse();
match run(&cli.config, cli.command) {
Ok(()) => ExitCode::SUCCESS,
Err(message) => {
eprintln!("{message}");
ExitCode::FAILURE
}
}
}
fn run(config: &Path, command: Command) -> Result<(), String> {
match command {
Command::Push {
topic,
message,
attachment,
} => {
let message = input(&message)?;
let Some(path) = attachment else {
let id = connect(config)?.push(&topic, &message).map_err(failed)?;
println!("Pushed as message #{id}");
return Ok(());
};
let mut file = fs::File::open(&path)
.map_err(|error| format!("Can't read {}: {error}", path.display()))?;
let id = connect(config)?
.push_with_attachment(&topic, &message, &mut file)
.map_err(failed)?;
let size = file.metadata().map_or(0, |metadata| metadata.len());
println!("Pushed as message #{id}, with an attachment of {size} bytes");
}
Command::Attachment {
topic,
node,
id,
file,
} => {
let size = connect(config)?
.save_attachment(&topic, &node, id, &file)
.map_err(failed)?;
println!("Saved {size} bytes as {}", file.display());
}
Command::Latest { topic, node } => {
let message = latest(&mut connect(config)?, &topic, &node)?
.ok_or_else(|| format!("No message yet in {topic}:{node}"))?;
println!(
"Message {topic}:{node}#{}, pushed {}",
message.id,
utc(message.pushed_at)
);
if let Some(attachment) = &message.attachment {
let here = if attachment.ready {
""
} else {
", not on this server yet"
};
println!("Attachment: {} bytes{here}", attachment.size);
}
println!("{}", message.data);
}
Command::Messages {
topic,
node,
after,
limit,
follow,
interval,
time,
} => {
let mut client = connect(config)?;
let mut after = match after {
After::Id(id) => id,
After::Latest => latest(&mut client, &topic, &node)?.map_or(0, |m| m.id),
};
let limit = limit.unwrap_or(if follow { 0 } else { 100 });
let mut printed = 0;
let mut out = io::BufWriter::new(io::stdout().lock());
loop {
let left = if limit > 0 { limit - printed } else { u64::MAX };
let asked = left.min(u64::from(MAX_MESSAGES_PER_PACKET)) as u32;
let batch = client
.get_messages(&topic, &node, Some(after), asked)
.map_err(failed)?;
for message in &batch.messages {
after = message.id;
let written = if time {
let at = utc(message.pushed_at);
writeln!(out, "{after}\t{at}\t{}", message.data)
} else {
writeln!(out, "{after}\t{}", message.data)
};
written.map_err(cant_write)?;
}
out.flush().map_err(cant_write)?;
printed += batch.messages.len() as u64;
if (limit > 0 && printed >= limit) || (!batch.more && !follow) {
break;
}
if !batch.more {
std::thread::sleep(Duration::from_millis(interval));
}
}
}
Command::Query { sql } => {
let sql = input(&sql)?;
println!("{}", connect(config)?.query(&sql).map_err(failed)?);
}
Command::List { what, json } => {
let mut client = connect(config)?;
let kinds = [
(NameKind::Topic, "topic", "Topics"),
(NameKind::Node, "node", "Nodes"),
];
for (kind, name, label) in kinds {
if matches!(
(what, kind),
(What::Topics, NameKind::Node) | (What::Nodes, NameKind::Topic)
) {
continue;
}
let list = client.list_names(kind).map_err(failed)?;
if json {
let json = serde_json::json!({
"kind": name,
"names": list.names,
"truncated": list.truncated,
});
println!("{json}");
continue;
}
println!("{label} ({}):", list.names.len());
for name in &list.names {
println!(" {name}");
}
if list.truncated {
println!(" ... more than fit in one answer");
}
}
}
}
Ok(())
}
/// A topic and node's latest message, if any.
fn latest(client: &mut Client, topic: &str, node: &str) -> Result<Option<MessageEntry>, String> {
let latest = client.get_messages(topic, node, None, 1).map_err(failed)?;
Ok(latest.messages.into_iter().next_back())
}
/// Connects with the settings in `config`.
fn connect(config: &Path) -> Result<Client, String> {
let text = fs::read_to_string(config).map_err(|error| {
format!(
"Can't read {}: {error} (the client's settings, see --help)",
config.display()
)
})?;
let settings: ClientToml =
toml::from_str(&text).map_err(|error| format!("{}: {error}", config.display()))?;
let folder = config.parent().unwrap_or(Path::new(""));
let pem = |what: &str, path: &Path| {
let path = folder.join(path);
fs::read_to_string(&path)
.map_err(|error| format!("Can't read the {what} {}: {error}", path.display()))
};
let ca = pem("CA's certificate", &settings.ca)?;
let certificate = pem("certificate", &settings.certificate)?;
let key = pem("key", &settings.key)?;
let crl = settings
.crl
.as_deref()
.map(|path| pem("CRL", path))
.transpose()?;
let pems = Settings {
ca: &ca,
certificate: &certificate,
key: &key,
crl: crl.as_deref(),
};
Client::connect(&settings.server, &pems).map_err(|error| {
format!(
"Failed to connect to {} ({}): {}",
settings.server,
code_name(error.code()),
error.message()
)
})
}
/// A message or SQL from the command line: as is, `@FILE` for a file's,
/// `-` for the standard input's (a UTF-8 BOM dropped).
fn input(text: &str) -> Result<String, String> {
let read = if text == "-" {
let mut read = String::new();
io::stdin()
.read_to_string(&mut read)
.map_err(|error| format!("Can't read the standard input: {error}"))?;
read
} else if let Some(path) = text.strip_prefix('@') {
fs::read_to_string(path).map_err(|error| format!("Can't read {path}: {error}"))?
} else {
return Ok(text.to_owned());
};
Ok(match read.strip_prefix('\u{feff}') {
Some(rest) => rest.to_owned(),
None => read,
})
}
fn failed(error: Error) -> String {
let what = if is_refusal_code(error.code()) {
"Refused by the server"
} else {
"Failed"
};
format!("{what} ({}): {}", code_name(error.code()), error.message())
}
fn cant_write(error: io::Error) -> String {
format!("Can't write the output: {error}")
}
/// Milliseconds since 1970 as "2026-11-08T14:03:59.123Z".
fn utc(ms: u64) -> String {
match time::OffsetDateTime::from_unix_timestamp_nanos(i128::from(ms) * 1_000_000) {
Ok(t) => format!(
"{:04}-{:02}-{:02}T{:02}:{:02}:{:02}.{:03}Z",
t.year(),
u8::from(t.month()),
t.day(),
t.hour(),
t.minute(),
t.second(),
t.millisecond()
),
Err(_) => format!("{ms} ms"),
}
}
@@ -0,0 +1,556 @@
//! `bakashrot` end to end against a server on a free port: the old suites'
//! tool checks (GetMessages, Names, BigMessages).
use bakashrot_client::{Client, Settings};
use bakashrot_config::Config;
use bakashrot_pki::{Ca, Identity, Usage};
use bakashrot_server::Server;
use std::fs;
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::mpsc;
use std::time::{Duration, Instant};
const CONFIG: &str = r#"
[server]
listen = "127.0.0.1:0"
ca = "ca.crt"
certificate = "server.crt"
key = "server.key"
topics = ["logs", "secret"]
synchronous = "normal"
[roles.home]
push_topics = ["logs", "secret"]
read_topics = ["*"]
query = true
[roles.lounge]
read_topics = ["logs"]
"#;
/// A server in a folder of its own, with `kitchen` (home) and `lounge`
/// (lounge) issued: `<name>.crt`, `.key` and `.toml`.
struct Running {
folder: PathBuf,
port: u16,
runtime: Option<tokio::runtime::Runtime>,
}
impl Running {
fn start(name: &str) -> Running {
let folder = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(format!("tool-{name}"));
let _ = fs::remove_dir_all(&folder);
fs::create_dir_all(&folder).unwrap();
let issued = Ca::create("Test CA", 10).unwrap();
let ca = Ca::load(&issued.certificate, &issued.key).unwrap();
let server = ca
.issue(
&Identity::new("server-1", &["peer"]).unwrap(),
Usage::Server,
10,
)
.unwrap();
fs::write(folder.join("ca.crt"), &issued.certificate).unwrap();
fs::write(folder.join("server.crt"), &server.certificate).unwrap();
fs::write(folder.join("server.key"), &server.key).unwrap();
fs::write(folder.join("server.toml"), CONFIG).unwrap();
let server = Server::start(Config::load(&folder.join("server.toml")).unwrap()).unwrap();
let runtime = tokio::runtime::Runtime::new().unwrap();
let listener = runtime
.block_on(tokio::net::TcpListener::bind("127.0.0.1:0"))
.unwrap();
let port = listener.local_addr().unwrap().port();
runtime.spawn(async move { server.serve(listener).await });
for (name, role) in [("kitchen", "home"), ("lounge", "lounge")] {
let issued = ca
.issue(&Identity::new(name, &[role]).unwrap(), Usage::Client, 10)
.unwrap();
fs::write(folder.join(format!("{name}.crt")), &issued.certificate).unwrap();
fs::write(folder.join(format!("{name}.key")), &issued.key).unwrap();
let toml = format!(
"server = \"127.0.0.1:{port}\"\nca = \"ca.crt\"\ncertificate = \"{name}.crt\"\nkey = \"{name}.key\"\n"
);
fs::write(folder.join(format!("{name}.toml")), toml).unwrap();
}
Running {
folder,
port,
runtime: Some(runtime),
}
}
/// Runs the tool as `who` (`kitchen`, `lounge`).
fn tool(&self, who: &str, args: &[&str]) -> Run {
run(&self.folder, who, args, None)
}
/// A client of the library's, as kitchen: pushing many is quicker.
fn client(&self) -> Client {
let read = |name: &str| fs::read_to_string(self.folder.join(name)).unwrap();
let (ca, certificate, key) = (read("ca.crt"), read("kitchen.crt"), read("kitchen.key"));
let settings = Settings {
ca: &ca,
certificate: &certificate,
key: &key,
crl: None,
};
Client::connect(&format!("127.0.0.1:{}", self.port), &settings).unwrap()
}
/// Stops the server: its connections close.
fn stop(&mut self) {
if let Some(runtime) = self.runtime.take() {
runtime.shutdown_background();
}
}
}
/// What a run printed, and its exit code.
#[derive(Debug)]
struct Run {
code: i32,
out: String,
err: String,
}
impl Run {
fn lines(&self) -> Vec<&str> {
self.out.lines().collect()
}
/// The ids `messages` printed.
fn ids(&self) -> Vec<u64> {
self.lines()
.iter()
.filter_map(|line| line.split('\t').next()?.parse().ok())
.collect()
}
#[track_caller]
fn ok(&self) -> &Run {
assert_eq!(self.code, 0, "{self:?}");
self
}
#[track_caller]
fn fails(&self, code: i32, text: &str) {
assert_eq!(self.code, code, "{self:?}");
assert!(self.err.contains(text), "expected '{text}': {self:?}");
}
}
fn run(folder: &Path, who: &str, args: &[&str], stdin: Option<&str>) -> Run {
let mut child = Command::new(env!("CARGO_BIN_EXE_bakashrot"))
.args(["-c", &format!("{who}.toml")])
.args(args)
.current_dir(folder)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
let mut input = child.stdin.take().unwrap();
if let Some(text) = stdin {
input.write_all(text.as_bytes()).unwrap();
}
drop(input);
let output = child.wait_with_output().unwrap();
Run {
code: output.status.code().unwrap_or(-1),
out: String::from_utf8(output.stdout).unwrap(),
err: String::from_utf8(output.stderr).unwrap(),
}
}
fn range(from: u64, to: u64) -> Vec<u64> {
(from..=to).collect()
}
#[test]
fn pushes_and_latest() {
let server = Running::start("push");
let push = |args: &[&str]| server.tool("kitchen", &[&["push"], args].concat());
assert_eq!(
push(&["logs", r#"{"t":21,"room":"kitchen"}"#]).ok().out,
"Pushed as message #1\n"
);
fs::write(server.folder.join("m.json"), "\u{feff}{\"from\":\"file\"}").unwrap();
assert_eq!(
push(&["logs", "@m.json"]).ok().out,
"Pushed as message #2\n"
);
let piped = run(
&server.folder,
"kitchen",
&["push", "logs", "-"],
Some("piped\ntext"),
);
assert_eq!(piped.ok().out, "Pushed as message #3\n");
assert_eq!(push(&["secret", "{}"]).ok().out, "Pushed as message #1\n");
let latest = server.tool("kitchen", &["latest", "logs", "kitchen"]);
let lines = latest.ok().lines();
assert!(
lines[0].starts_with("Message logs:kitchen#3, pushed 20"),
"{lines:?}"
);
assert!(
lines[0].ends_with('Z')
&& lines[0].len() == "Message logs:kitchen#3, pushed 2026-11-08T14:03:59.123Z".len()
);
assert_eq!(lines[1..], ["piped", "text"]);
let messages = server.tool("kitchen", &["messages", "logs", "kitchen"]);
assert_eq!(
messages.ok().lines()[..2],
[r#"1 {"t":21,"room":"kitchen"}"#, r#"2 {"from":"file"}"#]
);
// Refusals, the client's own failures.
server
.tool("lounge", &["push", "logs", "{}"])
.fails(1, "Refused by the server (NotAllowed)");
push(&["nope", "{}"]).fails(1, "Refused by the server (UnknownName): ");
push(&["bad name!", "{}"]).fails(1, "Failed (InvalidArgument)");
push(&["logs", "@missing.json"]).fails(1, "Can't read missing.json");
let big = "x".repeat(bakashrot_proto::limits::MAX_MESSAGE_SIZE + 1);
fs::write(server.folder.join("big.txt"), big).unwrap();
push(&["logs", "@big.txt"]).fails(1, "Failed (");
server
.tool("lounge", &["latest", "logs", "lounge"])
.fails(1, "No message yet in logs:lounge");
server
.tool("lounge", &["latest", "secret", "kitchen"])
.fails(1, "(NotAllowed)");
server
.tool("kitchen", &["push", "logs"])
.fails(2, "MESSAGE");
}
#[test]
fn messages() {
let server = Running::start("messages");
assert!(
server
.tool("kitchen", &["messages", "logs", "kitchen"])
.ok()
.out
.is_empty()
);
assert!(
server
.tool(
"kitchen",
&["messages", "logs", "kitchen", "--after", "latest"]
)
.ok()
.out
.is_empty()
);
let mut client = server.client();
for i in 1..=120 {
client.push("logs", &format!(r#"{{"i":{i}}}"#)).unwrap();
}
let messages = |who: &str, args: &[&str]| server.tool(who, &[&["messages"], args].concat());
let first = messages("kitchen", &["logs", "kitchen"]);
assert_eq!(first.ok().ids(), range(1, 100), "the first 100 by default");
assert_eq!(first.lines()[0], r#"1 {"i":1}"#);
assert_eq!(first.lines()[99], r#"100 {"i":100}"#);
assert_eq!(
messages("kitchen", &["logs", "kitchen", "--limit", "0"])
.ok()
.ids(),
range(1, 120)
);
assert_eq!(
messages("kitchen", &["logs", "kitchen", "--after", "115"])
.ok()
.ids(),
range(116, 120)
);
assert_eq!(
messages(
"kitchen",
&["logs", "kitchen", "--after", "10", "--limit", "7"]
)
.ok()
.ids(),
range(11, 17)
);
assert!(
messages("kitchen", &["logs", "kitchen", "--after", "120"])
.ok()
.out
.is_empty()
);
assert!(
messages("kitchen", &["logs", "kitchen", "--after", "LATEST"])
.ok()
.out
.is_empty()
);
assert_eq!(
messages("kitchen", &["LOGS", "Kitchen", "--after", "118"])
.ok()
.ids(),
range(119, 120)
);
assert_eq!(
messages("lounge", &["logs", "kitchen", "--after", "100"])
.ok()
.ids(),
range(101, 120)
);
let timed = messages("kitchen", &["logs", "kitchen", "--after", "119", "--time"]);
let fields: Vec<&str> = timed.ok().out.trim_end().split('\t').collect();
assert_eq!(
(fields[0], fields[2], fields[1].len()),
("120", r#"{"i":120}"#, 24),
"{fields:?}"
);
client.push("secret", "{}").unwrap();
assert_eq!(messages("kitchen", &["secret", "kitchen"]).ok().ids(), [1]);
messages("lounge", &["secret", "kitchen"]).fails(1, "(NotAllowed)");
messages("kitchen", &["logs", "nobody"]).fails(1, "(UnknownName)");
messages("kitchen", &["nothing", "kitchen"]).fails(1, "(UnknownName)");
assert!(
messages("lounge", &["logs", "lounge"]).ok().out.is_empty(),
"its own node, none yet"
);
messages("kitchen", &["logs", "kitchen", "--after", "soon"])
.fails(2, "a message id or \"latest\"");
messages("kitchen", &["logs", "kitchen", "--nope"]).fails(2, "--nope");
messages("kitchen", &["logs", "kitchen", "--interval", "5"]).fails(2, "--interval");
// As stored: not JSON, a line break spanning lines; big ones over
// several answers.
client.push("logs", "plain\ntext").unwrap();
let big: Vec<String> = (0..5)
.map(|i| format!("{i}{}", "y".repeat(600_000)))
.collect();
for data in &big {
client.push("logs", data).unwrap();
}
let read = messages("kitchen", &["logs", "kitchen", "--after", "120"]);
let lines = read.ok().lines();
assert_eq!(lines[..2], ["121\tplain", "text"]);
for (i, data) in big.iter().enumerate() {
assert_eq!(lines[2 + i], format!("{}\t{data}", 122 + i));
}
assert_eq!(
messages(
"kitchen",
&["logs", "kitchen", "--after", "121", "--limit", "2"]
)
.ok()
.ids(),
[122, 123]
);
}
#[test]
fn follows() {
let mut server = Running::start("follow");
let mut client = server.client();
client.push("logs", "old").unwrap();
let mut follower = Command::new(env!("CARGO_BIN_EXE_bakashrot"))
.args([
"-c",
"lounge.toml",
"messages",
"logs",
"kitchen",
"-f",
"--after",
"latest",
"--interval",
"20",
])
.current_dir(&server.folder)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
let (lines, read) = mpsc::channel();
let stdout = follower.stdout.take().unwrap();
std::thread::spawn(move || {
for line in BufReader::new(stdout).lines() {
let _ = lines.send(line.unwrap());
}
});
std::thread::sleep(Duration::from_millis(300));
assert!(
follower.try_wait().unwrap().is_none(),
"keeps running once caught up"
);
for i in 1..=3 {
client.push("logs", &format!("new {i}")).unwrap();
}
let got: Vec<String> = (0..3)
.map(|_| read.recv_timeout(Duration::from_secs(10)).unwrap())
.collect();
assert_eq!(
got,
["2\tnew 1", "3\tnew 2", "4\tnew 3"],
"only the new ones"
);
drop(client);
server.stop();
let started = Instant::now();
let status = loop {
if let Some(status) = follower.try_wait().unwrap() {
break status;
}
assert!(
started.elapsed() < Duration::from_secs(20),
"still following"
);
std::thread::sleep(Duration::from_millis(50));
};
assert_eq!(status.code(), Some(1), "fails once the server is gone");
}
#[test]
fn queries_and_lists() {
let server = Running::start("query");
server.client().push("logs", r#"{"t":1}"#).unwrap();
let query = server.tool("kitchen", &["query", "SELECT 1 AS one"]);
assert_eq!(
query.ok().out,
"{\"columns\":[\"one\"],\"rows\":[[\"1\"]]}\n"
);
fs::write(server.folder.join("q.sql"), r#"SELECT "two" AS "a b""#).unwrap();
assert!(
server
.tool("kitchen", &["query", "@q.sql"])
.ok()
.out
.contains(r#""a b""#)
);
let piped = run(&server.folder, "kitchen", &["query", "-"], Some("SELECT 3"));
assert!(piped.ok().out.contains(r#"[["3"]]"#), "{piped:?}");
server
.tool("lounge", &["query", "SELECT 1"])
.fails(1, "(NotAllowed)");
server
.tool("kitchen", &["query", "DELETE FROM messages"])
.fails(1, "(QueryFailed)");
let all = server.tool("kitchen", &["list"]);
assert_eq!(
all.ok().out,
"Topics (2):\n logs\n secret\nNodes (1):\n kitchen\n"
);
assert_eq!(
server.tool("lounge", &["list", "topics"]).ok().out,
"Topics (1):\n logs\n"
);
let json = server.tool("kitchen", &["list", "nodes", "--json"]);
assert_eq!(
json.ok().out,
"{\"kind\":\"node\",\"names\":[\"kitchen\"],\"truncated\":false}\n"
);
server
.tool("kitchen", &["list", "everything"])
.fails(2, "everything");
}
#[test]
fn attachments() {
let server = Running::start("attachments");
let photo: Vec<u8> = (0..2_500_000u32).map(|i| (i % 253) as u8).collect();
fs::write(server.folder.join("photo.jpg"), &photo).unwrap();
let pushed = server.tool(
"kitchen",
&["push", "logs", r#"{"photo":1}"#, "-a", "photo.jpg"],
);
assert_eq!(
pushed.ok().out,
"Pushed as message #1, with an attachment of 2500000 bytes\n"
);
server.tool("kitchen", &["push", "logs", "{}"]).ok();
server
.tool(
"kitchen",
&["push", "logs", "{}", "--attachment", "missing.jpg"],
)
.fails(1, "Can't read missing.jpg");
let saved = server.tool(
"lounge",
&["attachment", "logs", "kitchen", "1", "copy.jpg"],
);
assert_eq!(saved.ok().out, "Saved 2500000 bytes as copy.jpg\n");
assert_eq!(fs::read(server.folder.join("copy.jpg")).unwrap(), photo);
server
.tool(
"lounge",
&["attachment", "logs", "kitchen", "2", "none.jpg"],
)
.fails(
1,
"Refused by the server (NotFound): no attachment for logs:kitchen#2",
);
assert!(
!server.folder.join("none.jpg").exists(),
"a refused one leaves no file"
);
let mut client = server.client();
client.push("logs", "{}").unwrap();
let mut tiny = std::io::Cursor::new(b"tiny".to_vec());
client
.push_with_attachment("logs", "last", &mut tiny)
.unwrap();
let latest = server.tool("kitchen", &["latest", "logs", "kitchen"]);
let lines = latest.ok().lines();
assert!(lines[0].starts_with("Message logs:kitchen#4,"), "{lines:?}");
assert_eq!(lines[1..], ["Attachment: 4 bytes", "last"]);
}
#[test]
fn settings() {
let server = Running::start("settings");
let folder = &server.folder;
run(folder, "nobody", &["list"], None).fails(1, "Can't read nobody.toml");
// Paths are relative to the file's folder, wherever it runs from.
fs::create_dir_all(folder.join("elsewhere")).unwrap();
let up = run(
&folder.join("elsewhere"),
"../kitchen",
&["list", "topics"],
None,
);
assert_eq!(up.ok().out, "Topics (2):\n logs\n secret\n");
let kitchen = fs::read_to_string(folder.join("kitchen.toml")).unwrap();
fs::write(
folder.join("typo.toml"),
kitchen.replace("certificate =", "certficate ="),
)
.unwrap();
run(folder, "typo", &["list"], None).fails(1, "certficate");
fs::write(
folder.join("crl.toml"),
format!("{kitchen}crl = \"none.crl\"\n"),
)
.unwrap();
run(folder, "crl", &["list"], None).fails(1, "Can't read the CRL");
let closed = kitchen.replace(&server.port.to_string(), "1");
fs::write(folder.join("closed.toml"), closed).unwrap();
run(folder, "closed", &["list"], None)
.fails(1, "Failed to connect to 127.0.0.1:1 (ConnectFailed)");
}
+149
View File
@@ -0,0 +1,149 @@
//! `bakashrot-cert` end to end, in a folder of the build's.
use bakashrot_pki::{Revocations, summarize};
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
fn folder(name: &str) -> PathBuf {
let folder = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(name);
let _ = fs::remove_dir_all(&folder);
fs::create_dir_all(&folder).unwrap();
folder
}
/// Runs the tool in `folder`: whether it succeeded, and what it printed.
fn cert(folder: &Path, args: &[&str]) -> (bool, String) {
let output = Command::new(env!("CARGO_BIN_EXE_bakashrot-cert"))
.args(args)
.current_dir(folder)
.output()
.unwrap();
let text = format!(
"{}{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
(output.status.success(), text)
}
fn read(folder: &Path, name: &str) -> String {
fs::read_to_string(folder.join(name)).unwrap()
}
#[test]
fn a_ca_issues_and_revokes() {
let folder = folder("cert-tool");
let (ok, text) = cert(&folder, &["ca", "--name", "Test CA"]);
assert!(ok, "{text}");
if bakashrot_pki::IDENTITY_OID_IS_PLACEHOLDER {
assert!(text.contains("OID is still a placeholder"), "{text}");
}
assert!(
cert(
&folder,
&[
"issue", "--name", "kitchen", "--role", "sensor", "--role", "reader"
]
)
.0
);
assert!(cert(&folder, &["issue", "--name", "garage"]).0);
assert!(
cert(
&folder,
&["issue", "--name", "server-1", "--role", "peer", "--server"]
)
.0
);
let (ok, text) = cert(&folder, &["show", "kitchen.crt"]);
assert!(ok, "{text}");
assert!(
text.contains("name: kitchen") && text.contains("roles: sensor, reader"),
"{text}"
);
assert!(
text.contains("usage: client") && text.contains("issuer: Test CA"),
"{text}"
);
let (_, text) = cert(&folder, &["show", "server-1.crt"]);
assert!(text.contains("usage: server"), "{text}");
let (_, text) = cert(&folder, &["show", "ca.crt"]);
assert!(text.contains("usage: CA"), "{text}");
// Revoking twice keeps the first.
assert!(cert(&folder, &["revoke", "kitchen.crt"]).0);
let (ok, text) = cert(&folder, &["revoke", "garage.crt", "kitchen.crt"]);
assert!(ok && text.contains("(2 revoked)"), "{text}");
let revocations =
Revocations::load(&read(&folder, "ca.crl"), &read(&folder, "ca.crt")).unwrap();
assert_eq!(revocations.len(), 2);
for (name, revoked) in [("kitchen", true), ("garage", true), ("server-1", false)] {
let serial = summarize(&read(&folder, &format!("{name}.crt")))
.unwrap()
.serial;
assert_eq!(
revocations.serials().any(|s| s == serial),
revoked,
"{name}"
);
}
assert!(!folder.join("ca.crl.new").exists());
}
#[test]
fn a_name_can_have_several_certificates() {
let folder = folder("cert-tool-same-name");
assert!(cert(&folder, &["ca", "--name", "Test CA"]).0);
let server = ["issue", "--name", "server-1", "--role", "peer", "--server"];
assert!(cert(&folder, &server).0);
assert!(!cert(&folder, &server).0, "server-1.crt is there already");
let (ok, text) = cert(&folder, &[&server[..], &["--file", "server-1b"]].concat());
assert!(ok, "{text}");
let first = summarize(&read(&folder, "server-1.crt")).unwrap();
let second = summarize(&read(&folder, "server-1b.crt")).unwrap();
assert_eq!(first.identity, second.identity);
assert_ne!(first.serial, second.serial);
// Revoking one leaves the other.
assert!(cert(&folder, &["revoke", "server-1b.crt"]).0);
let revocations =
Revocations::load(&read(&folder, "ca.crl"), &read(&folder, "ca.crt")).unwrap();
assert!(revocations.serials().any(|s| s == second.serial));
assert!(!revocations.serials().any(|s| s == first.serial));
}
#[test]
fn nothing_is_overwritten_or_mixed_up() {
let folder = folder("cert-tool-refusals");
assert!(cert(&folder, &["ca", "--name", "Test CA"]).0);
let key = read(&folder, "ca.key");
let (ok, text) = cert(&folder, &["ca", "--name", "Another"]);
assert!(!ok, "{text}");
assert_eq!(read(&folder, "ca.key"), key, "the CA's key is still there");
assert!(cert(&folder, &["issue", "--name", "kitchen"]).0);
assert!(
!cert(&folder, &["issue", "--name", "kitchen"]).0,
"already there"
);
assert!(!cert(&folder, &["issue", "--name", "12"]).0, "not a name");
assert!(
!cert(&folder, &["issue", "--name", "garage", "--role", "a b"]).0,
"not a role"
);
// A certificate of another CA isn't revoked by this one.
let other = folder.join("other");
fs::create_dir_all(&other).unwrap();
assert!(cert(&other, &["ca", "--name", "Other CA"]).0);
assert!(cert(&other, &["issue", "--name", "stranger"]).0);
let (ok, text) = cert(&folder, &["revoke", "other/stranger.crt"]);
assert!(!ok && text.contains("not issued by this CA"), "{text}");
assert!(!folder.join("ca.crl").exists());
let (ok, text) = cert(&folder, &["show", "missing.crt"]);
assert!(!ok && text.contains("missing.crt"), "{text}");
}
+135
View File
@@ -0,0 +1,135 @@
# Certificates
Who connects to whom, and how it's checked. The code is
`crates/bakashrot-pki` (the library) and `crates/bakashrot-tools`
(`bakashrot-cert`, the tool). Decided in `../../revamp.md`, "Decided".
## The idea
One CA per deployment. Every client and every server has a certificate
from it, saying who it is: a node's name and its roles. Servers trust the
CA, not lists of keys; clients trust the CA, not a server's key. Revoking
is a CRL file from the CA, pushed to the servers.
## Certificates
- **Keys:** ECDSA P-384, signatures SHA-384 (the strongest rustls checks).
- **The identity**, an extension of BakaShrot's own, non-critical (rustls
refuses critical extensions it doesn't know):
```
BakaShrotIdentity ::= SEQUENCE {
version INTEGER, -- 1
name UTF8String, -- the node: "kitchen"
roles SEQUENCE OF UTF8String -- free: "sensor", "peer"...
}
```
Names and roles follow the name rules (1-64 of `A-Z a-z 0-9 _ . -`, not
only digits), 64 roles at most. Roles mean nothing to the certificates:
the server's config says what each may do.
- **Its OID is a placeholder** (`IDENTITY_OID`, `1.3.6.1.4.1.32473.1.1`,
under the PEN RFC 5612 reserves for documentation; `bakashrot-cert`
warns while it is): it goes under NibblePoker's own PEN before
certificates are issued for real. Why, how to request it, what to change:
`oid.md`.
- **The CN is the name too**, for people (`openssl x509 -text`, logs). Only
the extension is trusted.
- **Clients' certificates** are for `clientAuth`. **Servers'** are for
`serverAuth` and `clientAuth` (a server is its peers' client), and have
one DNS name, `bakashrot-server` (`SERVER_NAME`): a label, not a host.
- **No host names or IPs:** a client connects to any address and asks for
`bakashrot-server`; rustls' own verifier then checks the server's
certificate is the CA's, valid, not revoked... and for servers. A
client's certificate can't pose as a server's: it isn't for `serverAuth`
and doesn't have the name.
- **Lifetimes:** the CA 10 years, the others 1 year, by default.
- **The CA's key stays off the servers:** whoever has it can make any
identity, peers included.
## TLS
`bakashrot_pki::tls`: TLS 1.3 only, through aws-lc, offering only the
strongest of everything (both ends are ours, nothing to negotiate down to):
- cipher suite `TLS13_AES_256_GCM_SHA384`;
- key exchange `X25519MLKEM768`, the X25519 + ML-KEM hybrid (holds against
quantum computers too);
- ALPN `bakashrot`: what isn't BakaShrot is refused in the handshake (the
protocol's version is checked right after, `protocol.md`);
- a certificate from the CA on both ends;
- randomness (keys, nonces) from the OS: aws-lc's generator seeded from
Windows' `ProcessPrng` or Linux's `getrandom`, plus RDRAND, as BoringSSL
and `ring` do. Built without its CPU Jitter Entropy
(`AWS_LC_SYS_NO_JITTER_ENTROPY`, `../.cargo/config.toml`), which only adds
a source and cost 25 ms in every process, at its first connection.
`server_config()` checks clients with rustls' verifier, `client_config()`
checks the server with rustls' verifier too (for `bakashrot-server`). Then
both check the certificate isn't revoked and has an identity. Once
connected, `peer_identity()` gives the other end's `Identity`.
## Revocation
- `bakashrot-cert revoke` writes `ca.crl`, signed by the CA, with every
certificate revoked before (written aside, then moved in place).
- A server reads it into `Revocations`, which its TLS setup shares
(`SharedRevocations`): replacing what's inside takes effect for the next
handshake, no new configuration needed. `Revocations::revokes()` tells
the server which open connections to drop.
- **Both ends check it:** `server_config()` and `client_config()` both take
the revocations (`Revocations::none()` without a CRL). A server dialing
its peer is the peer's client, with the same CRL: servers block each
other, whichever end dials.
- **Revoking is by certificate, not by name:** each certificate has its own
key and its own serial number (made from that key), so two of the same
name (two servers named alike, a new one before the old one goes) are
revoked one at a time.
- A CRL is only taken if it's the CA's: issued by it, its signature
checked. One that isn't is refused, the server keeps the previous one.
Its "next update" isn't held against it: CRLs are pushed by hand.
- The server watches the file (its time and size, every 5 s), reloads
it, and drops a revoked certificate's connection at its next request
(`server.md`).
## The tool
```
bakashrot-cert ca --name "Home CA" ca.crt, ca.key
bakashrot-cert issue --name kitchen --role sensor kitchen.crt, kitchen.key
bakashrot-cert issue --name server-1 --role peer --server
bakashrot-cert revoke kitchen.crt ca.crl
bakashrot-cert show kitchen.crt
```
`--ca` (the folder of `ca.crt` / `ca.key`, `.` by default), `--out` (where
to write), `--days`, `--file` (the files' name when it isn't the node's:
another certificate of the same name, `--file server-1b`). Files are PEM. Nothing is ever written over an
existing certificate or key; keys are readable by their owner only on
Unix. `revoke` only takes certificates the CA issued.
## Tests
- `bakashrot-pki/tests/tls.rs`: handshakes in memory. The strongest
settings negotiated, identities both ways, a server as its peer's
client; refused: a client or a server of another CA, a client's
certificate posing as a server's, a revoked client (and taken again once
the CRL changes, on the same configuration), a certificate without an
identity, another protocol; clients given the CRL refusing a revoked
server, servers blocking each other both ways, two servers of the same
name each with its own certificate, revoked one at a time.
- `bakashrot-pki/tests/ca.rs`: what certificates say, a CA's key that isn't
its own, CRLs revoking exactly what they list, another CA's or a
tampered CRL refused, and OpenSSL agreeing (`openssl verify` for clients
and servers, the CRL's signature, a revoked certificate; skipped without
OpenSSL, Git's is found).
- `bakashrot-tools/tests/cert.rs`: the tool end to end, two certificates
of the same name, and what it refuses (overwriting, bad names and roles,
another CA's certificate).
## For later
- **`AllowedServerNames`** in a client's config and for the peers a
server dials: the server names it accepts (any of the CA's servers
without it).
- NibblePoker's PEN, replacing the placeholder OID (`oid.md`).
+186
View File
@@ -0,0 +1,186 @@
# The clients
What apps connect with, in layers:
| Layer | Where | For |
|---|---|---|
| `bakashrot-client` | `crates/bakashrot-client` | Rust: blocking, one connection per `Client` |
| The DLL | `crates/bakashrot-capi`: `bakashrot.dll`, `libbakashrot.so` | C and anything that loads a DLL: the old `BakaShrot_*` exports, one connection per process |
| C header | `bindings/c/bakashrot.h` | generated from the DLL (cbindgen) |
| PureBasic | `bindings/purebasic/` | the prototypes and the error codes, as the old DLL's |
| Python | `bindings/python/bakashrot.py` | `Client` over the DLL (ctypes), standard library only |
| The tools | `crates/bakashrot-tools`: `bakashrot` | the command line, over `bakashrot-client` |
Decided in `../../revamp.md`, "Decided" (2026-11-13). What goes over the
wire: `protocol.md`; the server's side: `server.md`.
**Status:** steps 7 to 9: connecting, pushes, messages, attachments,
names, queries.
## Who connects: certificates
A client is its certificate, issued by the CA the servers trust
(`certificates.md`, `bakashrot-cert issue`): its name is its node, its
roles say what it may do on each server (`config.md`). It needs the CA's
certificate (to check the server's), its own certificate and key, and the
CA's CRL if there is one (servers it revokes are refused).
### `client.toml`
What Python's `Client.from_file()` and the tools read. Paths are relative
to the file's folder.
```toml
server = "10.0.0.2:7000" # host:port, [an IPv6 address]:port
ca = "ca.crt"
certificate = "kitchen.crt"
key = "kitchen.key"
crl = "ca.crl" # optional
```
## The DLL
The old DLL's conventions, kept:
- **One connection per process.** Calls from several threads wait for each
other.
- **`A` and `W` exports:** strings in and out as UTF-8 (`char*`) or UTF-16
(`uint16_t*`, `wchar_t*` on Windows; PureBasic uses these),
null-terminated. A null string is an empty one where that means
something (a message), refused otherwise (`InvalidArgument`).
- **Strings out** are copied into the caller's buffer of `BufferSize`
bytes: the getter returns the bytes needed, terminator included, and
copies nothing if they don't fit; a null buffer asks for the size.
- **Failures:** 0, or -1 where a count or an id is returned. Then
`BakaShrot_GetLastError()` gives the code (`../crates/bakashrot-proto/src/error.rs`:
1-99 a server's refusal, the connection still open; 100 and up the
client's own) and `BakaShrot_GetRefusalReason()` why, in words (now for
every failure, not only refusals). After `ConnectionLost` or
`ProtocolError` the connection is closed: connect again. Nothing
reconnects by itself; a push whose answer was lost may have been stored.
- **Inside:** every export catches panics (`Internal`); no threads, no
runtime, so it unloads cleanly; nothing allocated on one side is freed
on the other; the C runtime linked statically on Windows (the release
DLL imports system DLLs only).
| Exports | What |
|---|---|
| `SetCaCertificate`, `SetCertificate`, `SetPrivateKey`, `SetCrl` (`A`/`W`) | PEM text (starting with `-----BEGIN`), or the path of a file holding it; `SetCrl` null or empty for none. Before connecting (`AlreadyConnected`); a file that can't be read is `FileError` |
| `Connect(Host, Port)` (`A`/`W`) | TLS with those; refused: `AuthRejected` (the server refused the certificate), `ServerNotVerified` (this client refused the server's), `NotAllowed` (none of its roles is the server's), `VersionMismatch` |
| `IsConnected`, `Disconnect` | `IsConnected` notices a connection the server closed |
| `GetNode` (`A`/`W`) | the node the server says this client is |
| `PushMessageTo(Topic, Data)` (`A`/`W`) | the id, -1 on failure |
| `GetLatestMessageOf(Topic, Node)` (`A`/`W`) | 1, or 0 with `NotFound` when there's none yet |
| `GetMessages(Topic, Node, After, Limit)` (`A`/`W`) | how many (0 isn't a failure), -1 on failure; then `GetMessageCount`, `SelectMessage(Index)`, `HasMoreMessages` |
| `GetMessageId`, `GetMessagePushedAt`, `GetMessageAttachmentSize`, `IsMessageAttachmentReady`, `GetMessageData`/`Topic`/`Node` (`A`/`W`) | the selected message; topic and node as asked |
| `ListTopics`, `ListNodes`, then `GetNamesList` (`A`/`W`) | how many; `{"kind":"topic","names":[...],"truncated":false}` |
| `Query(Sql)`, then `GetQueryResult` (`A`/`W`) | `{"columns":[...],"rows":[[...],...]}` |
| `PushMessageWithFile(Topic, Data, FilePath)`, `PushMessageWithData(Topic, Data, *Data, Size)` (`A`/`W`) | the id, -1 on failure; the attachment 1 byte and up, as much as the server takes (`TooBig`); a file read twice (its SHA-256 first), one changed in between refused (`DataMismatch`) |
| `SaveAttachment(Topic, Node, MessageId, FilePath)` (`A`/`W`) | its size, -1 on failure (`NotFound`, `NotReady`, `AttachmentMismatch`); a failed one leaves no file |
| `LoadAttachment(Topic, Node, MessageId)` (`A`/`W`), then `GetAttachmentData(*Buffer, Size)`, `FreeAttachmentData()` | into memory, for small ones; the getter returns the size, copies nothing if it doesn't fit |
| `GetLastError`, `GetRefusalReason` (`A`/`W`) | why the last call failed |
The header has each one's comment. Every name starts with `BakaShrot_`.
### Changed from the PureBasic DLL
- **Connecting:** certificates instead of keys and a node:
`SetCaCertificate`, `SetCertificate`, `SetCrl` are new, `SetPrivateKey`
takes a PEM key; `SetPublicKey`, `SetServerPublicKey`, `SetNode`,
`SetNodeId` are gone. `GetNode` is new (the node comes from the
certificate).
- **No default topic:** `PushMessage(Data)` is gone, `PushMessageTo` names
its topic.
- **Attachments:** the same six, by names.
- **No ids:** `GetLatestMessage(TopicId, NodeId)`, `GetMessageTopicId`,
`GetMessageNodeId`, `ResolveTopic`, `ResolveNode`, `GetResolvedName` are
gone; `GetNamesList` lists names.
- **The file:** `bakashrot.dll` (`libbakashrot.so`), no libsodium next to
it.
## Python
`bindings/python/bakashrot.py`, the old module adapted: `Client(server, ca,
certificate, key, crl=None)` (PEM text or paths) or
`Client.from_file("client.toml")` (Python 3.11+, `tomllib`; the rest runs
on 3.8), `client.node` once connected, `push(data, topic,
attachment=None)` (the topic required; the attachment bytes or a path),
`latest()`, `get_messages()`, `iter_messages()`, `follow()`,
`get_attachment()` (bytes), `save_attachment()` (a file),
`list_topics()` / `list_nodes()` (names), `query()` / `query_raw()`.
Errors: `RefusedError`, `ConnectionLostError`, `AuthError` (a certificate
refused, either way, or no role allowed), `BakaShrotError`. The DLL is
looked for next to the module, or `BAKASHROT_DLL`. The wheel comes with the
release (step 12).
## PureBasic
`bindings/purebasic/BakaShrot_Client_Prototypes.pbi` (with
`BakaShrot_ErrorCodes.pbi`): `BakaShrot_LoadClient("bakashrot.dll")`, then
the `W` exports under the old names, `BakaShrot_*String()` helpers for the
getters. Run directly, it's an example: `ClientExample <DllPath> <CaFile>
<CertificateFile> <KeyFile> <Host> <Port>`, pushing a message and one
with an attachment, reading both back (checked by hand with 5.73 against
a server; not in CI, which has no PureBasic).
## The tools
`bakashrot`, the old `BakaShrot*` tools in one program (`bakashrot-cert`,
for the CA, is apart: `certificates.md`). Each command connects with
`-c <file>` (`client.toml` by default), does one thing and exits: 0, 1 on a
failure (why on stderr: `Refused by the server (NotAllowed): ...`,
`Failed to connect to ...`), 2 on bad arguments. `--help` on each.
```text
bakashrot push logs '{"t":21}' Pushed as message #42
bakashrot push logs @reading.json (- for the standard input)
bakashrot push logs '{"cam":1}' -a photo.jpg Pushed as message #43, with an attachment of 81234 bytes
bakashrot latest logs kitchen Message logs:kitchen#43, pushed 2026-11-14T09:12:03.120Z
Attachment: 81234 bytes
{"cam":1}
bakashrot attachment logs kitchen 43 copy.jpg Saved 81234 bytes as copy.jpg
bakashrot messages logs kitchen 1<TAB>{"t":20}, a line each
bakashrot messages logs kitchen -f --after latest --time
bakashrot query "SELECT topic, count(*) FROM messages GROUP BY topic"
bakashrot list Topics (2): ... Nodes (1): ...
bakashrot list nodes --json {"kind":"node","names":["kitchen"],"truncated":false}
```
- **`messages`:** the first 100 by default (`--limit 0` for all), `--after
<id>` or `latest`; data as stored, a line break in it spanning lines;
`--follow` checks every `--interval` ms (500) until stopped or the
connection fails (exit 1); `--time` adds the push time between the id and
the data.
- **Attachments:** `push -a <file>`; `attachment` replaces the file,
leaves none if it fails; `latest` says a message's (", not on this
server yet" for one on its way from a peer).
- **Messages and SQL:** inline, `@file` or `-` (a UTF-8 BOM dropped).
PowerShell before 7.3 drops the double quotes inside arguments: use a
file there.
- **Changed from the old tools:** one program; `-c` instead of the last
argument, `client.toml` instead of `client.ini`; `push` names its topic;
names only (no ids in the output, `ResolveIds` gone); errors on stderr;
`GetAttachment` is the `attachment` command.
- **Speed** (release, a local server, 2026-11-14): a command takes about
11 ms, connecting included (the old tools 8 ms); `messages --limit 0`
writes 200,000 messages to a file in 0.26 s (Python's `iter_messages()`:
1.5 s). Against the old ones: `server.md`, "Measured".
## Tests
`crates/bakashrot-capi/tests/`, each against a server on a free port:
- `exports.rs`: the exports as C calls them: certificates from files and
PEM, the `W` strings (and some `A`), the buffers (the size, too small,
unaligned), selecting messages, attachments (from a file and memory,
saved and loaded, the buffer, refused ones), every refusal and the
client's own errors, closing, another identity.
- `python.rs`: runs `bindings/python/check_bakashrot.py` (the old one,
ported: 52 checks) on the DLL; skipped, saying so, without Python 3.11+.
- `header.rs`: `bindings/c/bakashrot.h` matches the exports (rewritten
when it doesn't: check it in).
`crates/bakashrot-tools/tests/bakashrot.rs` runs the tool against a server:
the old GetMessages suite's checks (`--follow` too), the Names,
BigMessages and Attachments suites' tool checks, queries, lists,
`client.toml`.
+105
View File
@@ -0,0 +1,105 @@
# The server's config
One TOML file, read and checked at once by `crates/bakashrot-config`: a
config that's wrong is refused whole, saying where (the line, shown) and
why. Every value is checked as it's read (serde), so every refusal has its
line. Every key, with its default: `crates/bakashrot-config/example.toml`.
Decided in `../../revamp.md`, "Decided".
## What's in it
| Section | What |
|---|---|
| `[server]` | where it listens, the certificate files, the database, its topics, how pushes are flushed, attachments, retention's pace |
| `[retention]` | how long each topic's messages are kept |
| `[replication]` | the peers it dials, the topics replicated at all, retry and sync pace, batch size |
| `[roles.<name>]` | what certificates with that role may do |
Unknown keys are refused, so a typo or a key of the old ini is caught.
## Who's who: certificates, then roles
A connection's certificate (`certificates.md`) says its node (its name)
and its roles. The server looks its roles up in `[roles.*]`:
- **Everything its roles allow, each role on its own**: `sensor` and
`reader` push what `sensor` may push, read what `reader` may read. For
replication, a role's topics go with that role's nodes, they're not
mixed with another role's.
- **None of its roles has a section: refused.** Roles the server doesn't
know are ignored (a certificate may have roles for other servers).
- Roles compare without case, like names.
What a role gives:
| Key | Default | Allows |
|---|---|---|
| `push_topics` | none | pushing to these topics, always as its own node |
| `read_topics` | none | reading these topics' messages |
| `query` | `false` | read-only SQL, which reads every topic |
| `send_topics` | none | replication: these topics sent to it |
| `accept_topics` | none | replication: these topics taken from it |
| `send_nodes` | `["*"]` | replication: only these nodes' messages sent |
| `accept_nodes` | `["*"]` | replication: only these nodes' messages taken |
No `AllowRead` / `AllowWrite`: a list that's empty allows nothing. No
default topic: a push always names its topic (protocol 7 has none).
## Peers
Peers are roles too: a server whose certificate has a role with
`send_topics` or `accept_topics` replicates, whichever end dialed. The
config only lists where to dial (`[replication] peers`, `host:port`): a
certificate can't say where a server is. Each side applies its own roles
to the other, as before each side had its own peer section.
`[replication] replicated_topics`, optional, filters every peer's
replication whatever its roles say: an edge node that keeps some topics to
itself. Without it, no filter; `[]` replicates nothing. Pushing and reading
aren't filtered.
## Names and values
- **Names** (topics, nodes, roles): 1-64 of `A-Z a-z 0-9 _ . -`, not only
digits, compared without case. Lists of topics or nodes also take
patterns: `*` any characters, `?` one, `"*"` for all. `[server] topics`
takes names only.
- **Names with dots are quoted as keys:** `"sensors.kitchen" = "12h"`,
`[roles."site.reader"]`. Unquoted, TOML reads dots as tables: refused,
`[retention]` says to quote.
- **Durations:** numbers with a unit (`s m h d w`), added up: `"30s"`,
`"1d12h"`. Ages in `[retention]` can also be `"forever"`.
- **Sizes:** bytes, or `"500M"` with `K M G T` (1024-based), up to 1T.
- **Paths:** relative ones are from the config file's folder.
## Retention
A topic takes its name's line, else the first pattern matching it in the
file's order, else `"*"`'s line wherever it is; without any, it's kept
forever. Ages count from when a message was first pushed, on whichever
server; each server has its own.
## What changed from the old ini
| Old (`OldSource/Server/Config/schema.ini`) | Now |
|---|---|
| `PrivateKey`, `[BakaShrot] Node` | `ca`, `certificate`, `key`: the node is the certificate's name |
| `[BakaShrot.Client.*]`: keys, `Node`, `Allow*` | `[roles.*]`, the node and roles from the certificate |
| `[BakaShrot.Peer.*]`: `Host`, `Port`, `Node`, `PublicKey`, topic and node lists | `[replication] peers` (addresses), the lists in the peer's roles |
| `ReplicatingTopics` | each peer role's `send_topics` / `accept_topics`; `replicated_topics` filters them all |
| topic and node ids, pins, ranges, `[BakaShrot.Nodes]` | names only: ids are the database's |
| `DefaultTopic` | dropped: a push always names its topic |
| `Host` + `Port` | `listen` |
| seconds | durations (`"10s"`) |
| `NetThreadPoolSize` | gone (tokio) |
| `UploadTimeout` | gone: attachments are streamed in their push (protocol 7), nothing waits |
| `FULL` / `NORMAL` | `"full"` / `"normal"`; `off` still refused |
## Tests
`crates/bakashrot-config/tests/config.rs`: the example, the defaults,
every setting, retention's order, permissions (several roles, none known,
replication per role), `replicated_topics`, paths from the config's
folder, and the refusals, each with its line: TOML errors, unknown keys
(the old ini's too), every value that's wrong, names twice (without case),
unquoted dotted names.
+77
View File
@@ -0,0 +1,77 @@
# The identity extension's OID
**Open point:** the OID is a placeholder until NibblePoker has its own
Private Enterprise Number (PEN) from IANA. The owner's to request
(below), then a few lines to change here.
## Why it matters
Servers find a certificate's name and roles by its identity extension's
OID (`bakashrot_pki::IDENTITY_OID`). Changing the OID makes every
certificate issued before unreadable as a BakaShrot identity: all of them
would have to be issued again. So it's settled before certificates are in
use; what's inside the extension can still change (its `version` field)
without touching the OID.
Within a deployment, only the CA's certificates are read, so another
extension using the same OID somewhere else can't confuse a server. The OID
mostly needs to be stable, and properly ours.
## Now: a placeholder
- `IDENTITY_OID = 1.3.6.1.4.1.32473.1.1`: under PEN 32473, "Example
Enterprise Number for Documentation Use" (RFC 5612). It works, but isn't
meant for real use, and examples elsewhere use it too.
- `IDENTITY_OID_IS_PLACEHOLDER = true`: `bakashrot-cert` warns whenever it
makes a CA or issues a certificate.
- Fine for development and tests; not for certificates in use.
- `OldSource/`'s UUID arc (`2.25.2320...0981`) can't be used: `rcgen`
writes OID parts of 64 bits at most, a UUID is 128.
## Requesting a PEN
From IANA's application page (checked 2026-11-13):
1. **Check first** that NibblePoker doesn't have one: search the registry,
<https://www.iana.org/assignments/enterprise-numbers/> (it had none on
2026-11-13). An organization that has one hands out sub-numbers under
it instead of asking for another.
2. **Apply** at <https://pen.iana.org/pen/PenApplication.page>. It's free.
It asks for:
- the **assignee**, the organization (or person) the number is for:
name ("NibblePoker"), address, country, phone (optional);
- a **contact**, the person IANA and others write to with questions,
who may also request changes later: name, address, country, phone and
fax (optional), **email** (required).
3. **Confirm** the request from the email IANA sends to that address.
4. **Wait:** if nothing else is needed, the number comes within seven days
of that confirmation. Questions: iana-pen@iana.org.
**What's public:** the registry lists, for every number, the organization,
the contact's name and the contact's email address (written with `&` for
`@`). Use an address meant to be published (a role address, not a
personal one).
Ask for one number for NibblePoker as a whole, not one per project: every
project gets its own branch under it.
## Once the number is there
With `<PEN>` the number IANA gave:
1. **Plan the branches**, and record them in the table below; a number
once given is never reused:
| OID | What |
|---|---|
| `1.3.6.1.4.1.<PEN>` | NibblePoker |
| `1.3.6.1.4.1.<PEN>.1` | BakaShrot |
| `1.3.6.1.4.1.<PEN>.1.1` | BakaShrot's identity extension |
2. **In `crates/bakashrot-pki/src/lib.rs`:** `IDENTITY_OID` to
`[1, 3, 6, 1, 4, 1, <PEN>, 1, 1]`, `IDENTITY_OID_IS_PLACEHOLDER` to
`false`.
3. **Update** this file (the table, "Now"), `certificates.md` and the open
point in `../../revamp.md`.
4. **Issue again** any certificate made with the placeholder, and run
`check.ps1` (the tests issue their own, nothing to change there).
+183
View File
@@ -0,0 +1,183 @@
# Protocol 7
What goes over a connection between a client and a server, or two servers.
The code is `crates/bakashrot-proto`; this describes it. Protocol 6, the
PureBasic one, is `OldSource/Design/Packets.md`: what the requests do is
mostly the same, the transport, the encoding and the packets themselves
were simplified (see the end).
**Status (2026-11-13):** packets, frames, names and error codes are written
and tested (`bakashrot-proto`), so is the TLS setup (`bakashrot-pki`,
`certificates.md`). The server and the client speak it so far for
connecting, pushes and messages (`server.md`).
## Transport
- **TCP, then TLS 1.3**, both ends with a certificate from the deployment's
CA (mutual TLS, `revamp.md`, "Decided"), at the strongest settings
rustls has: ECDSA P-384 certificates, AES-256-GCM-SHA384, the X25519MLKEM768
key exchange, nothing else offered.
- **Identities:** a certificate's identity extension gives its node's name
and roles. The client's is who it is; the server's is checked by the
certificate alone (the CA's, valid, not revoked, for servers, the name
expected), no host names or IPs. Revoked certificates are in the CA's
CRL: servers check it, and so do clients given it (servers dialing their
peers too).
- **ALPN `bakashrot`** (`limits::ALPN`): both ends offer it, what isn't
BakaShrot doesn't get past the TLS handshake. It isn't versioned.
- **The versions, first:** right after TLS, each end sends its protocol
version, 4 bytes little-endian (`frame::write_version()`), and reads the
other's (`frame::check_version()`). Different versions: both ends
abandon the connection (the client's error is `VersionMismatch`). This
comes before any frame, so it holds whatever later versions change.
- **The server speaks next:** a `Welcome`, saying who the connection is.
Then the client sends requests. A certificate none of whose roles the
server has gets a `RequestRefused` (`NotAllowed`) instead, then the
connection closes.
- **Frames:** every packet is one frame, its size as a 4-byte
little-endian unsigned integer, then the packet (`frame`). A size of 0,
or over `MAX_PACKET_SIZE` (16 MiB), aborts the connection as soon as it
arrived. The blocking client reads and writes them with `frame::read()`
/ `write()`, the async server with `frame::codec()` (`tokio-util`).
## Packets
A packet is **a MessagePack array of two: its type, then its fields as an
array**, `[type, [field, ...]]`. A struct inside is an array of its fields,
an optional value nil or itself, bytes a binary. The structs in
`crates/bakashrot-proto/src/packets/` are the format: `serde` derives it
(`rmp-serde`'s compact form). Any MessagePack library reads it. For
example `PushMessage { topic: "logs", data: "{}", attachment: None }`:
```
92 array of 2
04 type 4, PushMessage
93 its 3 fields
a4 6c 6f 67 73 "logs"
a2 7b 7d "{}"
c0 nil: no attachment
```
**Decoding checks everything** (`Packet::decode`): the types and number
of fields, each packet's rules (ranges, names, ids in order), and that
nothing follows. Anything wrong is a `DecodeError`: the connection is
aborted. (A struct given as a map of its field names is taken too, a
leniency of `serde`'s derive: nothing writes it, it isn't part of the
format, its values are checked all the same.)
### Values
- **Topics and nodes are names**, everywhere: 1-64 of `A-Z a-z 0-9 _ . -`,
not only digits, compared without case (`names`). A name that isn't one
is malformed (the client libraries check before sending); one the server
doesn't have is refused (`UnknownName`). Ids are each server's own, in
its database, never on the wire.
- **Patterns** (in a `SyncState`): names with `*` (any characters, none
included) and `?` (one).
- **Message ids:** 1 to 2^43 - 1 (`MAX_MESSAGE_ID`), in their topic/node
pair: what a server stores (`storage.md`, "Keys").
- **Times:** milliseconds since 1970-01-01 00:00:00 UTC, 1 to
9999-12-31 23:59:59.999 (`MAX_TIMESTAMP`). Stamped by the server a
message is pushed to, kept by replication.
- **Attachments:** `[size, sha256]`, 1 B to 1 TiB, sent in parts of
1 MiB (`ATTACHMENT_PART_SIZE`), the last one what's left.
### Types
Direction: **C** client, **S** server, **P** peer (a server linked to
another, as its client). Ids are protocol 7's own (6 can't connect); a new
packet takes the next one, none is ever reused.
| Id | Packet | Dir | Fields | Answered by |
|---|---|---|---|---|
| 1 | Welcome | S→C, S→P | `server` name, `node` name (the connection's, from its certificate) | |
| 2 | RequestRefused | S→C, S→P | `code` 1-99 (`error`), `reason` str | |
| 3 | Continue | S→C, S→P | none: send the attachment's parts | |
| 4 | PushMessage | C→S | `topic` name, `data` str (up to `MAX_MESSAGE_SIZE` bytes), `attachment` or nil | MessagePushed / RequestRefused; with an attachment, Continue first |
| 5 | MessagePushed | S→C, S→P | `message_id` | |
| 6 | GetMessages | C→S | `topic`, `node`, `after` (an id, 0 for all) or nil (the last ones), `limit` 1-10000 | Messages / RequestRefused |
| 7 | Messages | S→C | `more` bool, `[[id, pushed_at, data, [size, ready] or nil]...]` (ids strictly increasing, 10000 at most) | |
| 8 | GetAttachment | C→S | `topic`, `node`, `message_id`, `from_part` | Attachment then its parts / RequestRefused |
| 9 | Attachment | S→C | `size`, `sha256` | |
| 10 | AttachmentPart | C→S, S→C, P→S | `data` bin, 1 B to 1 MiB | |
| 11 | ListNames | C→S | `kind` (1 topics, 2 nodes) | NamesList |
| 12 | NamesList | S→C | `kind`, `truncated` bool, `[name...]` (65536 at most) | |
| 13 | Query | C→S | `sql` str | QueryResult / RequestRefused |
| 14 | QueryResult | S→C | `json` str: `{"columns":[...],"rows":[[...],...]}` | |
| 15 | SyncStateRequest | P→S | none | SyncState / RequestRefused |
| 16 | SyncState | S→P | `[topic...]`, `[node...]` (names and patterns it takes from P), `[[topic, node, last_id]...]`, `[[topic, node, message_id, next_part]...]` (attachments it lacks, 256 at most) | |
| 17 | ReplicateMessages | P→S | `topic`, `node`, `[[id, pushed_at, data, [size, sha256] or nil]...]` (1-10000, ids strictly increasing) | MessagePushed (the last id) / RequestRefused |
| 18 | ReplicateAttachment | P→S | `topic`, `node`, `message_id`, `from_part` | Continue, then its parts, then MessagePushed / RequestRefused |
## Flows
```
Pushing C: PushMessage S: MessagePushed / RequestRefused
with an C: PushMessage(attachment) S: Continue / RequestRefused
attachment C: AttachmentPart x every part S: MessagePushed / RequestRefused (DataMismatch)
Reading C: GetMessages(after: id) S: Messages, `more` if others follow
the latest C: GetMessages(after: nil, 1) S: Messages (empty if none)
An attachment C: GetAttachment(from_part) S: Attachment, then AttachmentPart x the rest
/ RequestRefused (NotFound, NotReady)
Replicating P: SyncStateRequest S: SyncState
P: ReplicateMessages x the batches S: MessagePushed each / RequestRefused
P: ReplicateAttachment x missing S: Continue / RequestRefused
P: AttachmentPart x from next_part S: MessagePushed / RequestRefused
```
- **Parts are streamed:** no request or answer per part, TCP paces them.
A part's index follows from the order, its exact size from the
attachment's size (`Attachment::part_len()`); the receiver checks both,
and the SHA-256 once all came.
- **Once the server said `Continue`**, it reads every part even if storing
them failed, then refuses: the client never has to read while sending.
- **A server failing while it sends parts** closes the connection; the
client asks again `from_part` the next one it needs.
- **Replication:** `SyncState` is all a check-in needs. The peer compares
it with what it has, by name, sends the messages the server lacks in
batches of up to `PeerBatchSize` (about 64 KiB, a bigger
message alone), then the attachments it listed.
## Rules
The same as protocol 6:
- **One request at a time:** a client sends one, waits for its answer (the
parts of an attachment being part of its request or answer).
- **Refuse or abort:** valid but not allowed or not found (permissions,
unknown names, over a limit, a failed query) is a `RequestRefused` with a
code, the connection stays. Malformed or out of order (a bad frame, a
`DecodeError`, an unexpected packet) aborts it. Clients apply the same
to answers.
- **The identity is the connection's:** requests never say who sends them.
A push picks its topic, never its node.
- **Error codes** (`error`): 1-99 refusals, 100+ the client's own; the
numbers of protocol 6, never renumbered.
## What changed from protocol 6
- **TLS** instead of the sealed Hello, the signed key exchange and the own
cipher: the handshake packets are gone, `Welcome` is new, the identity
comes from the certificate.
- **The version is checked once**, sent by both ends before anything else:
packets lost their magic and version.
- **Names only:** no ids on the wire, no refs. `ResolveName` /
`NameResolved` are gone, answers don't echo ids, `NamesList` is names,
`SyncState` gives its heads by name.
- **No default topic:** a push always names its topic, `Welcome` doesn't
give one (`NoDefaultTopic`, 6, is never sent).
- **Fewer packets, 26 → 18:** `GetMessages` with `after: nil` replaces
`GetLatestMessage`, `Messages` replaces `LatestMessage`; `SyncState`
lists the missing attachments (no `MissingAttachmentsRequest` /
`MissingAttachments`); answers don't echo what was asked.
- **Attachments are streamed in their request:** no upload ids, no uploads
waiting for their push (and no `UploadTimeout`), no request or answer per
part (`UploadStart`, `UploadStarted`, `UploadChunk`, `ChunkStored`,
`AttachmentChunk`, `ReplicateAttachmentChunk` are gone). An upload cut
short starts over (none resumed in protocol 6 either); reads and
replication go on `from_part`.
- **Encoding:** derived with `serde`, `[type, [fields...]]`, booleans and
nil where they belong (were 0/1 and empty values). Nothing may follow a
packet (was ignored).
- **No 4 KB limit before authentication:** TLS has authenticated both ends
before any frame.
+218
View File
@@ -0,0 +1,218 @@
# The server and the client
`crates/bakashrot-server` (a library and the `bakashrot-server` program)
and `crates/bakashrot-client` (the blocking client library the C DLL will
wrap). Decided in `../../revamp.md`, "Decided" (2026-11-13). What goes over
the wire: `protocol.md`.
**Status:** steps 5, 6, 9 and 10: connecting, pushes and their
attachments, messages, attachments, names, queries, retention.
Replication (step 11) is refused
(`InvalidRequest`, "isn't answered yet") until its step.
## Running
```
bakashrot-server server.toml
```
The config (`config.md`) gives where to listen, the certificates, the CRL,
the database, the topics and the roles. Logs go to the console
(`tracing`); Ctrl+C stops it. Running as a service, console commands:
step 12.
## Inside the server
| What | Where | How |
|---|---|---|
| Connections | tokio, a task each | TLS (`tokio-rustls`, `bakashrot-pki`'s settings), the versions, the identity, then requests one at a time |
| Writes | one writer thread | a queue of every write (pushes, uploads and their parts, retention's deletes); the thread writes whatever is queued in one transaction (group commit, 1000 at most): the busier, the bigger the groups |
| Reads, queries | tokio's blocking threads | a pool of read connections and one of query connections (`query_only`), reused |
| WAL checkpoints | one thread, every second | its own connection, off the writer's way (`storage.md`) |
| The CRL file | a task, every 5 s | reloaded when its time or size changes; one that isn't the CA's is refused, the previous one stays |
| Retention | a task, at start then every `retention_interval` (1 min) | below |
## Retention
`[retention]` (`config.md`) says how long each topic's messages are kept.
At start, then every `retention_interval`, the server goes through every
topic in its database (one no longer in `topics` too) and deletes the
messages pushed before now minus its age, 10,000 per write, so pushes go
on between them. Then the parts of their attachments, 64 MB per write.
Each topic's count is logged ("deleted 3 messages of topic 'logs'").
- **In id order** (`storage.md`, "Retention"): a message stamped earlier
than the one before it (a clock set back) waits for that one.
- **Ids go on:** a stream's last id stays, the next push takes the next.
- **"May be" deleted past its age:** up to `retention_interval` later.
- **Each server its own:** a peer's ages are its own (step 11).
## A connection
1. **TLS:** the client's certificate must be the CA's, valid, not revoked,
with an identity (`certificates.md`).
2. **The versions:** each end sends its own; different ones, the
connection is dropped (the client says `VersionMismatch`).
3. **The roles:** none of the certificate's roles in the config, the
server answers `RequestRefused` (`NotAllowed`, saying which roles) and
closes; otherwise `Welcome` (the server's name, the client's node).
4. **Requests**, one at a time. Before each, the certificate is checked
against the current CRL: revoked since, the connection is dropped.
| Timeout | |
|---|---|
| TLS, versions, welcome | 10 s (the server); the client's connect too |
| Silence between requests | 5 min, then the server closes |
| An answer | 30 s (the client) |
| An attachment's next part | 30 s (the server), then it closes |
## Requests so far
- **`PushMessage`:** the topic must be one of the config's (`UnknownName`),
the roles must allow pushing to it (`NotAllowed`), the message at most
`MAX_MESSAGE_SIZE` (`TooBig`); stored under the client's node, stamped
with the server's time; answered `MessagePushed` once committed.
- **With an attachment:** also at most the config's `max_attachment_size`
(`TooBig`; 0 takes none). The server answers `Continue`, then reads
every part: each written while the next come (4 at most waiting for the
writer, so the client waits through TCP rather than the server holding
them), the SHA-256 computed as they come. All there and matching, the
message is stored with it, ready, in one transaction. A part of the
wrong size (`InvalidRequest`), a wrong SHA-256 (`DataMismatch`), a
failed write: refused once every part came, the connection kept. A
connection that closes, or sends anything else than the next part, is
dropped. Not pushed, the upload goes (`storage.md`, "Attachments").
- **`GetAttachment`:** the roles must allow reading the topic
(`NotAllowed`), the topic must be one of the config's (`UnknownName`).
A message without one, or none of that id: `NotFound`; one still on its
way from a peer: `NotReady`; one this server doesn't keep: `TooBig`.
Then `Attachment` (its size, its SHA-256) and the parts from
`from_part`. A part that can't be read closes the connection.
- **`GetMessages`:** the roles must allow reading the topic
(`NotAllowed`), the topic must be one of the config's and the node one
with messages in any topic, or the client's own (`UnknownName`); a known
topic and node without messages answer none. At most `limit` messages and about 1 MB
(`MESSAGES_BYTES`, a bigger message alone), `more` if others follow.
- **`ListNames`:** topics are the config's, those the roles may push to or
read (every one with `query`, which reads them all anyway); nodes are
every one with messages. `truncated` past 65,536.
- **`Query`:** the roles must allow it (`NotAllowed`); read-only SQL,
refused with SQLite's message (`QueryFailed`, with a hint to add
`is_json = 1` on "malformed JSON"), over 10,000 rows or 16 MB
(`TooBig`), never a partial result (`storage.md`, "The query surface").
- **Sizes:** frames up to 16 MB (`MAX_PACKET_SIZE`), a bigger one drops the
connection; messages up to `MAX_MESSAGE_SIZE` (16 MB less 4 KB), the
server refusing bigger ones (`TooBig`); the client refuses messages and
queries over it before sending (`InvalidArgument`).
## The client
`Client::connect(address, settings)` (`host:port`, the CA's certificate,
the client's certificate and key, the CRL if any), then `push(topic,
data)`, `get_messages(topic, node, after, limit)`, `list_names(kind)`,
`query(sql)`. Blocking, no runtime. The DLL and the bindings over it:
`client.md`.
Attachments: `push_with_attachment(topic, data, source)`, the source any
`Read + Seek` (a `File`, a `Cursor`), read twice: its SHA-256, then its
parts; `get_attachment(topic, node, id, out)` into any `Write`, checked
with its SHA-256 once all came; `save_attachment(topic, node, id, path)`,
written to `path` and `.download` then moved over `path`, so a failed one
leaves no file. A source or a part that fails half-way closes the
connection (the server can't be told to stop); a failing `out` doesn't
(the rest is read, then `FileError`).
Its errors are the protocol's codes: a server's refusal keeps its own
(1-99), the client's are 100 and up (`ConnectFailed`, `AuthRejected` when
the server refused its certificate, `ServerNotVerified` when it refused the
server's, `ConnectionLost`, `ProtocolError`, `InvalidArgument`,
`FileError`, `AttachmentMismatch`, `VersionMismatch`).
## Measured
`push_rate` (`tests/end_to_end.rs`, ignored by default): a whole server on
localhost, 10 clients each its own node (`CLIENTS`), one push at a time
each, 200-byte JSON, 20,000 pushes per client.
| `synchronous` | 10 clients | Slowest push | 1 client |
|---|---|---|---|
| `normal` | 40,400/s | 37 ms | 14,200/s |
| `full` | 9,229/s | 9 ms | 1,920/s |
- With `normal`, the server reaches the storage's own ceiling (about 37k/s
alone, `storage.md`, a slightly different load). Up from 36,000/s once
a connection's revocation check stopped reading its certificate at
every request (its serial is read once, at connect).
- One client waits for each answer: a round trip and a commit per push.
Through Python and the DLL, about 10,700 pushes/s (the old module did
about 9,000), and 140,000 messages/s read.
- With `full`, every group commit waits for the disk's flush (about 1 ms
here): 10 clients make groups of about 10. More clients, bigger groups.
- **Attachments** (release, the tool, `normal`): 200 MB up in 1.3 s and
down in 0.5 s, the tool's start and the client's hashing included.
### Against the old server (2026-11-14)
The same work on the same machine, release builds, one server on
localhost: the old one (`OldSource/Build/Bench/BenchServer.exe`, its DLL,
`bakashrot.py` and tools) and this one. Pushes and reads through each one's
Python module and DLL (10 clients: 10 processes, the same node), 200-byte
JSON; the rest through the tools.
| | Old, `full` | New, `full` | Old, `normal` | New, `normal` |
|---|---|---|---|---|
| One tool command, connecting included | 8 ms | 12 ms | 8 ms | 11 ms |
| Pushes, 1 client | 1,945/s | 1,954/s | 9,386/s | 11,600-13,100/s |
| Pushes, 10 clients | 9,006/s | 10,072/s | 25,419/s | 56,200-64,300/s |
| Reads, Python | 76,466/s | 130,861/s | 77,526/s | 146,368/s |
| The tool writing 120,000 messages to a file | | | 45.5 s | 0.14 s |
| A 200 MB attachment up, the tool | 3.49 s | 1.15 s | 2.84 s | 1.15 s |
| The same down | 1.57 s | 0.59 s | 1.62 s | 0.67 s |
- **`full`, one client:** both wait for the disk's flush at every push.
- **A command:** the TLS handshake's P-384 signatures and checks, both
ends, cost about 7 ms against the old handshake's X25519; aws-lc's CPU
Jitter Entropy seeding cost 25 ms more per process before it was turned
off (`certificates.md`, "TLS").
- **The old tool's read** printed a line at a time to the console API.
## Tests
`crates/bakashrot-server/tests/end_to_end.rs`, a server on a free port
each:
- pushes and reads back (ids, data, times, another connection);
- runs of messages (`OldSource/Tests/GetMessages-Test.ps1`, the server's
part): from the start, after an id, with a limit, `more`, the last ones,
nothing yet, unknown topics and nodes, names without case, data that
isn't one line of JSON;
- big messages (`BigMessages-Test.ps1`, one server's part): five of 600 KB
and one of the largest size, one per answer, read back whole; one byte
over refused; a query result over 16 MB refused;
- names: topics by role, nodes;
- attachments (`Attachments-Test.ps1`, one server's part): 100 KB, 5 MB +
123 bytes, exactly 2 MB, 1 byte, 1 MB, read back and saved; the
messages saying theirs; none, or no such message, refused leaving no
file; another reader, one not allowed; over the server's limit, 0 for
none, empty; the parts stored;
- attachment edges (`AttachmentEdges-Test.ps1`'s, through the client and
a raw connection): a source changed between its SHA-256 and its
sending, one failing half-way (the connection closed, the upload
dropped), a part of the wrong size, a wrong SHA-256, reading from a
part on, something else than a part (closed, dropped);
- queries (`BigMessages-Test.ps1`'s): not allowed, results, a non-JSON row
refused with the hint, errors, writes and two statements refused;
- refusals keeping the connection (not allowed, unknown topic, a bad name
the client catches);
- certificates refused (no known role, with why; another CA's client; a
client trusting another CA; nothing listening);
- revoked certificates (an open connection dropped at its next request, a
new one refused, others going on, a bad CRL refused);
- six connections pushing at once (one id stream per node, none lost or
doubled);
- retention (`Retention-Test.ps1`'s local part): a topic's messages and
their attachment deleted past its age, another topic kept forever, ids
going on, a younger message kept through a pass.
The old tests' tool parts (`--follow`, the output) are the tools' tests
(`client.md`), their replication parts come with step 11.
+285
View File
@@ -0,0 +1,285 @@
# Storage: schema v9
The server's database: one SQLite file. The code is
`crates/bakashrot-storage`; the schema is
`crates/bakashrot-storage/src/schema_v9.sql`, made in one go. Decided in
`../../revamp.md`, "Decided" (2026-11-13).
**Not compatible with v8:** a database of the old server isn't opened
(refused at start, saying so); its data isn't carried over.
## In short
- **By name outside, packed integers inside.** The rest of the code (the
server, the tools) only sees topics, nodes, message ids and times, as on
the wire. Inside, a topic and node pair is a *stream*, and a message's
key packs its stream and its id into one integer. Only this crate packs
and unpacks keys; the `messages` view shows plain columns.
- **One B-tree per kind of data:** messages, attachment parts. A push
writes its message's row and nothing else (no index): about 2.3 times
the pushes of v8's layout, 30% less disk (see "Measured").
- **One writer, many readers** (WAL). Writes go in batches, one
transaction each: a group commit.
## Streams
A **stream** is one node's messages in one topic: `logs` written by
`kitchen` is one, `logs` written by `garage` another. Everything works on
them:
- message ids count per stream, from 1;
- replication compares each stream's `last_id` (`SyncState`'s heads);
- `GetMessages` reads a range of one stream.
`streams` holds each one's id (1 to 2^20 - 1), its topic and node names
(compared without case), and `last_id`: the highest id it ever had.
Deleting messages leaves `last_id`, so ids never go back. A trigger keeps
it, for pushes and replication alike.
There are no `topics` or `nodes` tables: a topic's streams are its rows in
`streams`, the names are listed from there (`Reader::topics()`,
`nodes()`), and the config adds the topics it names.
## Keys
```
data.key = stream_id << 43 | message_id
[0][ stream: 20 bits ][ message id: 43 bits ]
attachment_parts.key = attachment_id << 20 | part
[0][ attachment: 43 bits ][ part: 20 bits ]
```
- `data.key` is the table's own key (`INTEGER PRIMARY KEY`): the messages
are stored ordered by stream, then id. A stream's messages sit together;
"after id 100", "the last 10" are ranges of keys, read in order. No
other index is written when a message is stored.
- **Limits:** 1,048,575 streams per database, message ids up to
2^43 - 1 (8,796,093,022,207) per stream: 278 years at 1,000 messages a
second. `MAX_MESSAGE_ID` (`bakashrot-proto`) is that, so the protocol
can't carry an id a server can't store. Past either, a push is refused
(`TooBig`).
- **Attachment parts** the same way: 2^20 parts of 1 MiB is exactly the
1 TiB limit, an attachment's parts are a range of keys.
- `data` also has `stream_id`, `message_id` and `is_json` as **virtual
columns**: computed when read, never stored (a test checks the schema
unpacks keys as the code does).
Why not v8's three columns with an index? A second B-tree to write at every
push, and reads going through the index then to the row. Measured below.
## Writing
`Database::writer()` gives the one connection that writes;
`Writer::batch(|batch| ...)` runs a closure in one transaction. Every
operation of a `Batch` is all or nothing on its own (a savepoint), so a
batch goes on after one fails: the server queues pushes and stores them
together, one disk flush for all.
| Operation | What |
|---|---|
| `push(topic, node, pushed_at, data)` | the next id of its stream, which it returns; the stream is made if new |
| `start_upload(size, sha256)`, `write_part(id, part, data)`, `push_with_attachment(id, ...)`, `cancel_upload(id)` | a push with an attachment: its parts first, then the message with it |
| `replicate(topic, node, messages, max_attachment_size)` | a peer's messages, with their ids; ones already here are kept |
| `write_part`, `finish_replicated(id, matches)` | a replicated attachment's parts, then ready (or started over) |
| `delete_before(topic, cutoff, limit)` | retention |
| `purge_attachments(max_parts)` | deleted messages' attachments |
| `Writer::vacuum()` (outside a batch) | the file shrunk to what it holds: the old server's `vacuum` command |
| `Checkpointer::checkpoint()` (its own connection) | the WAL copied into the database, every second, off the writer's way |
**SHA-256s are the caller's to check:** the server hashes the parts as they
stream by, nothing is read back from the disk. A resumed replicated
attachment's first parts are read back (`Reader::read_part`) to finish its
hash.
## Reading
`Database::reader()` gives a connection that reads, as many as needed; they
read while the writer writes. Answers are the protocol's own types:
| Reader | Gives | How |
|---|---|---|
| `messages(topic, node, after, limit)` | `Messages`: after an id in order, or the last ones; about 1 MiB at most (a bigger message alone), `more` if others follow | a range of keys |
| `topics()`, `nodes()` | the names with messages | `streams` |
| `heads()`, `last_id(topic, node)` | each stream's last id: `SyncState` | `streams` |
| `missing_attachments(limit)` | replicated attachments not all here, from which part | `attachments` (index on states) |
| `attachment(topic, node, id)`, `read_part(id, part)` | an attachment, its parts | the message's key; a part's key |
A topic and node with no messages read as none, unless the node has none
in any topic: `Error::UnknownName`, as the old server refused unknown
nodes. Whether a topic is known is the server's (the config's topics).
## Attachments
One table, a state each:
| State | Meaning | Next |
|---|---|---|
| `uploading` | a push's attachment, parts coming, no message yet (`message_key` NULL) | all parts and the SHA-256 match: the message is stored and the attachment `ready`, one transaction. Cut short: deleted with its parts (and every one left at start) |
| `replicating` | its message came from a peer with its size and SHA-256; parts come after | asked from part `received / 1 MiB` on; all came and match: `ready`, else started over |
| `ready` | all here, checked | readable |
| `too_big` | bigger than this server's `max_attachment_size` | never asked for; its message is kept |
| `deleting` | its message was deleted (a trigger) | parts deleted in batches, then the row |
Readers never see a message whose pushed attachment is missing: the
message is only stored with its complete attachment. A replicated message
can be here before its attachment: `Messages` says `ready: false`.
## Retention
`delete_before(topic, cutoff, limit)` reads each of the topic's streams from
its oldest message and stops at the first it keeps: only what it deletes is
read, nothing indexes `pushed_at`. So messages go **in id order**: one
stamped earlier than the one before it (a server's clock set back) waits for
that one. `last_id` stays. The parts of deleted messages' attachments go
afterwards, `purge_attachments(max_parts)` a batch at a time.
## The query surface
Clients' `Query` runs on `Database::query_runner()`, read-only three ways:
the connection is `query_only`, the statement must be one SQLite says only
reads, and one statement only (more is refused, not ignored). The result is
`{"columns":[...],"rows":[[...]]}`, every value a string or null (blobs in
hex), 10,000 rows and 16 MB at most (`TooBig`). A failing row fails it all,
with SQLite's message: never a partial result. "malformed JSON" (a JSON
function on a row that isn't) gets the old server's hint: add
`is_json = 1` to the WHERE.
The `messages` view, by name:
| Column | |
|---|---|
| `topic`, `node` | names |
| `message_id`, `message_data`, `is_json`, `pushed_at`, `pushed_utc` | as in v8 |
| `attachment_size`, `attachment_state` | NULL without one |
```sql
SELECT * FROM messages WHERE topic = 'logs' AND node = 'kitchen'
SELECT message_data ->> '$.temp' FROM messages WHERE topic = 'sensors' AND is_json = 1
```
- **By topic, or topic and node:** ranges of the table, read in order (a
test checks the plans).
- **Filters on `pushed_at` or `message_id`** read the streams they're in,
whole: a millisecond or two for 10,000 messages per stream, growing with
them (see "Measured"). If that gets slow, a time index is one migration
away ("For later").
- `browse` / `browse_messages`: v8's, for database tools (set `browse`'s
one row, open the view); no dropdowns any more.
## The file
- `PRAGMA application_id` = "BSHT": a BakaShrot database.
- `metadata`: `schema_version` (9), `created_at`, `created_by` (this crate
and its version).
- **Opening** (`Database::open`): an empty file is made a v9 database; a
v9 one is opened; an older one is migrated, a version at a time, each
step one transaction that also sets `schema_version` (none yet); a newer
one, the old server's, or another program's is refused, saying which.
- Every connection: WAL, `synchronous` from the config (`full`: every
commit flushed; `normal`: about once a second), a 5 s busy timeout. No
foreign keys: one writer keeps the tables consistent, `CHECK`s keep the
values valid.
- SQLite is compiled in (`rusqlite`'s `bundled`): the same version
everywhere, no system library.
## Measured
Python's `sqlite3` (SQLite 3.50), 5,000,000 small JSON messages pushed to
500 streams (100 topics x 5 nodes) at random, 100 per transaction, WAL,
`synchronous = NORMAL`, 16 MB page cache:
| | v9 (this) | v9 + a time index | the first draft (v8's layout) |
|---|---|---|---|
| Pushes/s | **23k** | 9-10k | 9k |
| File | **330 MB** | 457 MB | 484 MB |
| Latest 100 of a stream | 0.05 ms | 0.05 ms | 0.19 ms |
| 1000 after an id | 0.53 ms | 0.53 ms | 3.04 ms |
| Retention, 10% of a topic | 5.5 ms | 6.4 ms | 241 ms |
| Query: a node's last hour | 1.65 ms | 0.90 ms | 3.29 ms |
| Query: a topic's last hour | 8.4 ms | 4.7 ms | 16.0 ms |
- A push dirties its stream's page: with pushes spread over many streams,
each costs about a page written to the WAL. Any index per stream (v8's,
a time index) doubles that, and a bigger cache doesn't help (it's writes,
not reads).
- Bigger batches over fewer streams share pages: the server's group commit
helps most when many pushes come at once.
### Against the old storage (2026-11-13)
The same workload on both, each storage layer alone (no network): pushes
over 500 streams picked at random, 100 per transaction, 200-byte JSON;
2000 latest-message reads; 500 reads of 1000 messages after a stream's
middle id; retention of 10% of one topic. The new side is
`compare_with_old` (`tests/storage.rs`, ignored by default:
`PUSHES=1000000 SYNC=normal cargo test --release -p bakashrot-storage --
--ignored --nocapture`). The old side calls `OldSource`'s writer
(`BakaShrot_Writer_WriteJobs()`, its group commit, PureBasic 5.73, SQLite
3.54.1 from `sqlite3.dll`), from a program built outside `OldSource`.
Same machine, NVMe, one run each.
| | Old, 1M | New, 1M | Old, 1M `full` | New, 1M `full` | Old, 5M | New, 5M |
|---|---|---|---|---|---|---|
| Pushes/s, first | **25,874** | 13,803 | **19,976** | 13,205 | **19,558** | 12,184 |
| Pushes/s, step 5's writer | 25,874 | **37,332** | 19,976 | **29,952** | 19,558 | **29,363** |
| File | 276 MB | 249 MB | 276 MB | 249 MB | 1,380 MB | 1,239 MB |
| Latest message | 0.013 ms | 0.017 ms | 0.013 ms | 0.017 ms | 0.014 ms | 0.017 ms |
| 1000 after an id | 4.26 ms | **0.43 ms** | 4.28 ms | **0.43 ms** | 4.32 ms | **0.45 ms** |
| Retention, 10% of a topic | 20 ms | **7 ms** | 23 ms | **9 ms** | 98 ms | **8 ms** |
`normal` unless said. At first, the old writer pushed faster, from code the
new one didn't have, not from the schema; step 5 brought two of them over
(the second row, about 1.5 times the old):
- **checkpoints off the push path:** `Database::checkpointer()`, every
second on its own connection (the server's thread), the writer only
checkpointing itself past 10,000 pages (`WRITER_CHECKPOINT_PAGES`,
SQLite's default is 1,000): 13.8k to 34.7k pushes/s;
- **no savepoint around a push** (a failed one leaves at most its empty
stream): 37.3k;
- **next ids in memory**, left out: an indexed read of the stream's row per
push, not where the time goes.
The new layout reads ranges 10 times faster, deletes faster (and keeps
doing so as the database grows), loses less push speed from 1M to 5M (-12%
against -24%), and makes a file 10% smaller with 200-byte messages (30%
with 45-byte ones: its saving is the indexes, a fixed cost per message).
## Tests
`crates/bakashrot-storage/tests/storage.rs`, on database files in
`target/`: opening (made, reopened, an empty file), refused databases
(another program's, v8, a newer version, no version), pushes and reads
(ids per stream, names without case, after/latest/limit/more, the 1 MiB
cut), uploads (parts in order and of their size, incomplete refused, a
failed operation not spoiling its batch, cancelled and left-over ones
deleted), replication (own ids, kept ones, attachments to ask for, too big,
started over, resumed), retention (limits, id order, heads kept, ids going
on, attachments purged in batches), vacuum (the file shrinks, ids go on),
the limits (no stream, no id left, the highest key), queries (results, every write refused, failing rows, too
big), the view's plans, and readers with two writers at once. In
`src/lib.rs`: the keys, the schema unpacking them the same, the states.
## For later
- **A time index**, if time queries over big streams get slow: a v10
migration adding an index on `(stream_id, pushed_at)` and joining the
view on it too (measured above: twice the write cost).
- **Interrupting long queries** (a time limit): the server's, with
SQLite's interrupt.
- **Attachments as files** next to the database instead of in it, if their
size calls for it.
## What changed from v8
| v8 | v9 |
|---|---|
| `data(topic_id, node_id, message_id, ...)` + 3 indexes | `data(key, pushed_at, message_data)`, no index |
| `topics`, `nodes` with ids and origins | names in `streams` |
| `node_heads` | `streams.last_id` |
| `attachments` + `blobs` (two sets of states), `blob_chunks` | `attachments` (five states), `attachment_parts` |
| uploads waiting for their message, `UploadTimeout` | uploads inside their push |
| `is_json` stored | computed when read |
| no version in the file | `metadata` with `schema_version`; `application_id` |
| foreign keys declared, not checked | none, `CHECK`s |
+6
View File
@@ -0,0 +1,6 @@
# The toolchain every build and CI run uses: bump it on purpose, in its own
# commit, once everything passes with the new one.
[toolchain]
channel = "1.100.0"
components = ["rustfmt", "clippy"]
profile = "minimal"