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