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:
@@ -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
|
||||
}
|
||||
@@ -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
Reference in New Issue
Block a user