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
+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}");
}