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,30 @@
|
||||
[package]
|
||||
name = "bakashrot-capi"
|
||||
description = "BakaShrot's C DLL: the BakaShrot_* exports over bakashrot-client, one connection per process."
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
repository.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
# bakashrot.dll / libbakashrot.so; the rlib for the tests.
|
||||
[lib]
|
||||
name = "bakashrot"
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[dependencies]
|
||||
bakashrot-client = { path = "../bakashrot-client" }
|
||||
bakashrot-proto = { path = "../bakashrot-proto" }
|
||||
serde_json = "1.0.154"
|
||||
|
||||
[dev-dependencies]
|
||||
bakashrot-config = { path = "../bakashrot-config" }
|
||||
bakashrot-pki = { path = "../bakashrot-pki" }
|
||||
bakashrot-server = { path = "../bakashrot-server" }
|
||||
cbindgen = { version = "0.29.4", default-features = false }
|
||||
tokio = { version = "1.54.1", features = ["rt-multi-thread", "net"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,13 @@
|
||||
# bindings/c/bakashrot.h, generated from src/lib.rs by tests/header.rs
|
||||
# (which rewrites it when the exports change: check it in then).
|
||||
language = "C"
|
||||
header = """/*
|
||||
* BakaShrot's client DLL: bakashrot.dll (Windows), libbakashrot.so (Linux).
|
||||
* Generated by cbindgen from Source/crates/bakashrot-capi: don't edit.
|
||||
* Source/docs/client.md has the conventions and the whole API.
|
||||
*/"""
|
||||
include_guard = "BAKASHROT_H"
|
||||
cpp_compat = true
|
||||
documentation = true
|
||||
line_endings = "LF"
|
||||
usize_is_size_t = true
|
||||
@@ -0,0 +1,928 @@
|
||||
//! BakaShrot's C DLL (`bakashrot.dll`, `libbakashrot.so`): the old
|
||||
//! `BakaShrot_*` exports over [`bakashrot_client`], for C, PureBasic,
|
||||
//! Python (ctypes) and anything that loads a DLL. `Source/docs/client.md`
|
||||
//! has the whole API; `bindings/c/bakashrot.h` is generated from this file.
|
||||
//!
|
||||
//! The conventions, the old DLL's:
|
||||
//!
|
||||
//! - **One connection per process:** set the certificates, connect, send
|
||||
//! requests, one at a time (calls from several threads wait for each
|
||||
//! other).
|
||||
//! - **`A` and `W` exports:** strings in and out as UTF-8 (`char*`) or
|
||||
//! UTF-16 (`uint16_t*`, `wchar_t*` on Windows), null-terminated.
|
||||
//! - **Strings out** are copied into the caller's buffer of `BufferSize`
|
||||
//! bytes: the getter returns the bytes needed, terminator included, and
|
||||
//! copies nothing if they don't fit (a null buffer asks for the size).
|
||||
//! - **Failures:** 0 (or -1 where a count or an id is returned), then
|
||||
//! `BakaShrot_GetLastError()` gives the code (1-99 a server's refusal, the
|
||||
//! connection still open; 100 and up the client's own) and
|
||||
//! `BakaShrot_GetRefusalReason()` why, in words. After `ConnectionLost`
|
||||
//! or `ProtocolError` the connection is closed: connect again.
|
||||
//! - **Safety:** pointers are null or valid for what's said, strings
|
||||
//! terminated, buffers writable for their size. A panic inside is caught
|
||||
//! and reported as `Internal`; nothing allocated here is freed by the
|
||||
//! caller, or the other way.
|
||||
|
||||
#![allow(unsafe_code, non_snake_case, clippy::missing_safety_doc)]
|
||||
|
||||
mod text;
|
||||
|
||||
use bakashrot_client::{Client, Error, Settings};
|
||||
use bakashrot_proto::ErrorCode;
|
||||
use bakashrot_proto::packets::{MessageEntry, NameKind};
|
||||
use std::ffi::{c_char, c_void};
|
||||
use std::fs::File;
|
||||
use std::io::Cursor;
|
||||
use std::panic::{AssertUnwindSafe, catch_unwind};
|
||||
use std::path::Path;
|
||||
use std::sync::{Mutex, MutexGuard, PoisonError};
|
||||
use text::{Text, Utf8, Utf16};
|
||||
|
||||
type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
/// Everything the DLL holds: its one connection, its settings, the last
|
||||
/// answers.
|
||||
static STATE: Mutex<State> = Mutex::new(State::new());
|
||||
|
||||
struct State {
|
||||
ca: Option<String>,
|
||||
certificate: Option<String>,
|
||||
key: Option<String>,
|
||||
crl: Option<String>,
|
||||
client: Option<Client>,
|
||||
/// The last call's error code, 0 if it succeeded.
|
||||
last_error: u32,
|
||||
/// Why it failed.
|
||||
reason: String,
|
||||
/// The last `GetMessages` or `GetLatestMessageOf`.
|
||||
topic: String,
|
||||
node: String,
|
||||
messages: Vec<MessageEntry>,
|
||||
selected: usize,
|
||||
more: bool,
|
||||
/// The last `ListTopics` / `ListNodes`, as JSON.
|
||||
names: String,
|
||||
/// The last `Query`'s result.
|
||||
query: String,
|
||||
/// The last `LoadAttachment`'s attachment.
|
||||
attachment: Vec<u8>,
|
||||
}
|
||||
|
||||
impl State {
|
||||
const fn new() -> State {
|
||||
State {
|
||||
ca: None,
|
||||
certificate: None,
|
||||
key: None,
|
||||
crl: None,
|
||||
client: None,
|
||||
last_error: 0,
|
||||
reason: String::new(),
|
||||
topic: String::new(),
|
||||
node: String::new(),
|
||||
messages: Vec::new(),
|
||||
selected: 0,
|
||||
more: false,
|
||||
names: String::new(),
|
||||
query: String::new(),
|
||||
attachment: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn fail(&mut self, error: Error) {
|
||||
self.last_error = error.code();
|
||||
self.reason = error.message().to_owned();
|
||||
let closed = [ErrorCode::ConnectionLost, ErrorCode::ProtocolError]
|
||||
.iter()
|
||||
.any(|code| code.code() == error.code());
|
||||
if closed {
|
||||
self.client = None;
|
||||
}
|
||||
}
|
||||
|
||||
fn client(&mut self) -> Result<&mut Client> {
|
||||
self.client.as_mut().ok_or_else(|| {
|
||||
Error::new(
|
||||
ErrorCode::NotConnected,
|
||||
"not connected: BakaShrot_Connect() first",
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// The selected message of the last answer.
|
||||
fn message(&self) -> Option<&MessageEntry> {
|
||||
self.messages.get(self.selected)
|
||||
}
|
||||
|
||||
/// Forgets the last answer's messages.
|
||||
fn clear_messages(&mut self, topic: &str, node: &str) {
|
||||
self.topic = topic.to_owned();
|
||||
self.node = node.to_owned();
|
||||
self.messages.clear();
|
||||
self.selected = 0;
|
||||
self.more = false;
|
||||
}
|
||||
}
|
||||
|
||||
fn state() -> MutexGuard<'static, State> {
|
||||
STATE.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// Runs a call that can fail: the last error reset, then set if it fails
|
||||
/// (or panics), `failed` returned then.
|
||||
fn call<T>(failed: T, run: impl FnOnce(&mut State) -> Result<T>) -> T {
|
||||
let outcome = catch_unwind(AssertUnwindSafe(|| {
|
||||
let mut state = state();
|
||||
state.last_error = 0;
|
||||
state.reason.clear();
|
||||
let outcome = run(&mut state);
|
||||
outcome.map_err(|error| state.fail(error))
|
||||
}));
|
||||
match outcome {
|
||||
Ok(Ok(value)) => value,
|
||||
Ok(Err(())) => failed,
|
||||
Err(_) => {
|
||||
state().fail(Error::new(ErrorCode::Internal, "the DLL panicked"));
|
||||
failed
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs a getter: the last error stays as it is.
|
||||
fn get<T>(default: T, read: impl FnOnce(&State) -> T) -> T {
|
||||
catch_unwind(AssertUnwindSafe(|| read(&state()))).unwrap_or(default)
|
||||
}
|
||||
|
||||
/// Copies a string of the state into the caller's buffer.
|
||||
unsafe fn get_text<T: Text>(buffer: *mut T::Unit, size: isize, text: fn(&State) -> &str) -> isize {
|
||||
get(0, |state| unsafe {
|
||||
text::copy::<T>(text(state), buffer, size)
|
||||
})
|
||||
}
|
||||
|
||||
fn invalid(why: impl Into<String>) -> Error {
|
||||
Error::new(ErrorCode::InvalidArgument, why)
|
||||
}
|
||||
|
||||
fn required(value: Option<String>, what: &str) -> Result<String> {
|
||||
value.ok_or_else(|| invalid(format!("no {what} (a null pointer)")))
|
||||
}
|
||||
|
||||
fn bool_result(ok: bool) -> isize {
|
||||
isize::from(ok)
|
||||
}
|
||||
|
||||
// --- Errors ------------------------------------------------------------------
|
||||
|
||||
/// Why the last call failed: a protocol error code (1-99 a server's
|
||||
/// refusal, the connection still open; 100 and up the client's own), 0 if
|
||||
/// it succeeded. Getters don't change it.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn BakaShrot_GetLastError() -> i32 {
|
||||
get(ErrorCode::Internal.code() as i32, |state| {
|
||||
state.last_error as i32
|
||||
})
|
||||
}
|
||||
|
||||
/// Why the last call failed, in words: the server's reason for a refusal,
|
||||
/// the client's otherwise. Empty if it succeeded.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_GetRefusalReasonA(buffer: *mut c_char, size: isize) -> isize {
|
||||
unsafe { get_text::<Utf8>(buffer.cast(), size, |state| &state.reason) }
|
||||
}
|
||||
|
||||
/// The same as `BakaShrot_GetRefusalReasonA`, in UTF-16.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_GetRefusalReasonW(buffer: *mut u16, size: isize) -> isize {
|
||||
unsafe { get_text::<Utf16>(buffer, size, |state| &state.reason) }
|
||||
}
|
||||
|
||||
// --- Settings ----------------------------------------------------------------
|
||||
|
||||
/// A setting's PEM: the text itself if it starts with `-----BEGIN`, a
|
||||
/// file's path otherwise. `None` (null or empty) only if `optional`.
|
||||
fn pem_or_file(value: Option<String>, what: &str, optional: bool) -> Result<Option<String>> {
|
||||
let Some(value) = value.filter(|value| !value.trim().is_empty()) else {
|
||||
return match optional {
|
||||
true => Ok(None),
|
||||
false => Err(invalid(format!("no {what}"))),
|
||||
};
|
||||
};
|
||||
if value.trim_start().starts_with("-----BEGIN") {
|
||||
return Ok(Some(value));
|
||||
}
|
||||
std::fs::read_to_string(&value)
|
||||
.map(Some)
|
||||
.map_err(|error| Error::new(ErrorCode::FileError, format!("{what} '{value}': {error}")))
|
||||
}
|
||||
|
||||
/// Sets one of the certificates' settings, before connecting.
|
||||
unsafe fn set<T: Text>(
|
||||
value: *const T::Unit,
|
||||
what: &str,
|
||||
optional: bool,
|
||||
slot: fn(&mut State) -> &mut Option<String>,
|
||||
) -> isize {
|
||||
call(0, |state| {
|
||||
if state.client.is_some() {
|
||||
return Err(Error::new(
|
||||
ErrorCode::AlreadyConnected,
|
||||
"already connected: disconnect first",
|
||||
));
|
||||
}
|
||||
let value = unsafe { text::read::<T>(value, what)? };
|
||||
*slot(state) = pem_or_file(value, what, optional)?;
|
||||
Ok(1)
|
||||
})
|
||||
}
|
||||
|
||||
/// Sets the CA's certificate, which the server's must be issued by: PEM
|
||||
/// text, or the path of a file holding it. Before connecting.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_SetCaCertificateA(certificate: *const c_char) -> isize {
|
||||
unsafe {
|
||||
set::<Utf8>(certificate.cast(), "CA certificate", false, |state| {
|
||||
&mut state.ca
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The same as `BakaShrot_SetCaCertificateA`, in UTF-16.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_SetCaCertificateW(certificate: *const u16) -> isize {
|
||||
unsafe { set::<Utf16>(certificate, "CA certificate", false, |state| &mut state.ca) }
|
||||
}
|
||||
|
||||
/// Sets this client's certificate, which says its node and its roles: PEM
|
||||
/// text, or the path of a file holding it. Before connecting.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_SetCertificateA(certificate: *const c_char) -> isize {
|
||||
unsafe {
|
||||
set::<Utf8>(certificate.cast(), "certificate", false, |state| {
|
||||
&mut state.certificate
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The same as `BakaShrot_SetCertificateA`, in UTF-16.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_SetCertificateW(certificate: *const u16) -> isize {
|
||||
unsafe {
|
||||
set::<Utf16>(certificate, "certificate", false, |state| {
|
||||
&mut state.certificate
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets this client's private key, its certificate's: PEM text, or the path
|
||||
/// of a file holding it. Before connecting.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_SetPrivateKeyA(key: *const c_char) -> isize {
|
||||
unsafe { set::<Utf8>(key.cast(), "private key", false, |state| &mut state.key) }
|
||||
}
|
||||
|
||||
/// The same as `BakaShrot_SetPrivateKeyA`, in UTF-16.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_SetPrivateKeyW(key: *const u16) -> isize {
|
||||
unsafe { set::<Utf16>(key, "private key", false, |state| &mut state.key) }
|
||||
}
|
||||
|
||||
/// Sets the CA's CRL, optional: servers it revokes are refused. PEM text,
|
||||
/// or the path of a file holding it; null or empty for none. Before
|
||||
/// connecting.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_SetCrlA(crl: *const c_char) -> isize {
|
||||
unsafe { set::<Utf8>(crl.cast(), "CRL", true, |state| &mut state.crl) }
|
||||
}
|
||||
|
||||
/// The same as `BakaShrot_SetCrlA`, in UTF-16.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_SetCrlW(crl: *const u16) -> isize {
|
||||
unsafe { set::<Utf16>(crl, "CRL", true, |state| &mut state.crl) }
|
||||
}
|
||||
|
||||
// --- The connection ----------------------------------------------------------
|
||||
|
||||
unsafe fn connect<T: Text>(host: *const T::Unit, port: i32) -> isize {
|
||||
call(0, |state| {
|
||||
if state.client.is_some() {
|
||||
return Err(Error::new(
|
||||
ErrorCode::AlreadyConnected,
|
||||
"already connected: disconnect first",
|
||||
));
|
||||
}
|
||||
let host = required(unsafe { text::read::<T>(host, "host")? }, "host")?;
|
||||
let port = u16::try_from(port)
|
||||
.ok()
|
||||
.filter(|port| *port != 0)
|
||||
.ok_or_else(|| invalid(format!("port {port}: 1 to 65535")))?;
|
||||
let missing = |what: &str, setter: &str| invalid(format!("no {what}: {setter}() first"));
|
||||
let settings = Settings {
|
||||
ca: state
|
||||
.ca
|
||||
.as_deref()
|
||||
.ok_or_else(|| missing("CA certificate", "BakaShrot_SetCaCertificate"))?,
|
||||
certificate: state
|
||||
.certificate
|
||||
.as_deref()
|
||||
.ok_or_else(|| missing("certificate", "BakaShrot_SetCertificate"))?,
|
||||
key: state
|
||||
.key
|
||||
.as_deref()
|
||||
.ok_or_else(|| missing("private key", "BakaShrot_SetPrivateKey"))?,
|
||||
crl: state.crl.as_deref(),
|
||||
};
|
||||
// An IPv6 address goes in brackets before its port.
|
||||
let address = match host.contains(':') && !host.starts_with('[') {
|
||||
true => format!("[{host}]:{port}"),
|
||||
false => format!("{host}:{port}"),
|
||||
};
|
||||
let client = Client::connect(&address, &settings)?;
|
||||
state.client = Some(client);
|
||||
Ok(1)
|
||||
})
|
||||
}
|
||||
|
||||
/// Connects to the server at `host` (a name or an address) and `port`:
|
||||
/// TLS with the certificates set, then the server says who this client is
|
||||
/// (`BakaShrot_GetNode()`). Refused: the code says by whom (`AuthRejected`
|
||||
/// the server refused the certificate, `ServerNotVerified` this client
|
||||
/// refused the server's, `NotAllowed` none of its roles is the server's).
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_ConnectA(host: *const c_char, port: i32) -> isize {
|
||||
unsafe { connect::<Utf8>(host.cast(), port) }
|
||||
}
|
||||
|
||||
/// The same as `BakaShrot_ConnectA`, in UTF-16.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_ConnectW(host: *const u16, port: i32) -> isize {
|
||||
unsafe { connect::<Utf16>(host, port) }
|
||||
}
|
||||
|
||||
/// 1 while connected: notices when the server closed the connection
|
||||
/// (forgotten then: connect again).
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn BakaShrot_IsConnected() -> isize {
|
||||
let open = catch_unwind(AssertUnwindSafe(|| {
|
||||
let mut state = state();
|
||||
let open = state.client.as_ref().is_some_and(Client::is_open);
|
||||
if !open {
|
||||
state.client = None;
|
||||
}
|
||||
open
|
||||
}));
|
||||
bool_result(open.unwrap_or(false))
|
||||
}
|
||||
|
||||
/// Closes the connection: 0 if there was none. The settings stay.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn BakaShrot_Disconnect() -> isize {
|
||||
let closed = catch_unwind(AssertUnwindSafe(|| state().client.take().is_some()));
|
||||
bool_result(closed.unwrap_or(false))
|
||||
}
|
||||
|
||||
/// The node this client is, as the server said when connecting: its
|
||||
/// certificate's name. Empty when not connected.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_GetNodeA(buffer: *mut c_char, size: isize) -> isize {
|
||||
unsafe {
|
||||
get_text::<Utf8>(buffer.cast(), size, |state| {
|
||||
state.client.as_ref().map_or("", Client::node)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The same as `BakaShrot_GetNodeA`, in UTF-16.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_GetNodeW(buffer: *mut u16, size: isize) -> isize {
|
||||
unsafe {
|
||||
get_text::<Utf16>(buffer, size, |state| {
|
||||
state.client.as_ref().map_or("", Client::node)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// --- Pushing -----------------------------------------------------------------
|
||||
|
||||
/// A push's topic and message, as arguments: a null message is an empty
|
||||
/// one (PureBasic passes "" as null).
|
||||
unsafe fn topic_and_data<T: Text>(
|
||||
topic: *const T::Unit,
|
||||
data: *const T::Unit,
|
||||
) -> Result<(String, String)> {
|
||||
let topic = required(unsafe { text::read::<T>(topic, "topic")? }, "topic")?;
|
||||
let data = unsafe { text::read::<T>(data, "the message")? }.unwrap_or_default();
|
||||
Ok((topic, data))
|
||||
}
|
||||
|
||||
unsafe fn push_to<T: Text>(topic: *const T::Unit, data: *const T::Unit) -> i64 {
|
||||
call(-1, |state| {
|
||||
let (topic, data) = unsafe { topic_and_data::<T>(topic, data)? };
|
||||
let id = state.client()?.push(&topic, &data)?;
|
||||
Ok(id as i64)
|
||||
})
|
||||
}
|
||||
|
||||
/// Pushes a message (JSON or not) to `topic`, as this client's node: its
|
||||
/// id (1 and up), -1 on failure. A push whose answer was lost
|
||||
/// (`ConnectionLost`) may have been stored all the same.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_PushMessageToA(
|
||||
topic: *const c_char,
|
||||
data: *const c_char,
|
||||
) -> i64 {
|
||||
unsafe { push_to::<Utf8>(topic.cast(), data.cast()) }
|
||||
}
|
||||
|
||||
/// The same as `BakaShrot_PushMessageToA`, in UTF-16.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_PushMessageToW(topic: *const u16, data: *const u16) -> i64 {
|
||||
unsafe { push_to::<Utf16>(topic, data) }
|
||||
}
|
||||
|
||||
// --- Reading -----------------------------------------------------------------
|
||||
|
||||
/// A topic and node, as arguments.
|
||||
unsafe fn topic_and_node<T: Text>(
|
||||
topic: *const T::Unit,
|
||||
node: *const T::Unit,
|
||||
) -> Result<(String, String)> {
|
||||
let topic = required(unsafe { text::read::<T>(topic, "topic")? }, "topic")?;
|
||||
let node = required(unsafe { text::read::<T>(node, "node")? }, "node")?;
|
||||
Ok((topic, node))
|
||||
}
|
||||
|
||||
unsafe fn latest_of<T: Text>(topic: *const T::Unit, node: *const T::Unit) -> isize {
|
||||
call(0, |state| {
|
||||
let (topic, node) = unsafe { topic_and_node::<T>(topic, node)? };
|
||||
state.clear_messages(&topic, &node);
|
||||
let answer = state.client()?.get_messages(&topic, &node, None, 1)?;
|
||||
if answer.messages.is_empty() {
|
||||
return Err(Error::new(
|
||||
ErrorCode::NotFound,
|
||||
format!("no message in {topic}/{node} yet"),
|
||||
));
|
||||
}
|
||||
state.messages = answer.messages;
|
||||
Ok(1)
|
||||
})
|
||||
}
|
||||
|
||||
/// Gets the latest message of `topic` and `node`, then read with the
|
||||
/// `BakaShrot_GetMessage*()` getters. `NotFound` if there's none yet.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_GetLatestMessageOfA(
|
||||
topic: *const c_char,
|
||||
node: *const c_char,
|
||||
) -> isize {
|
||||
unsafe { latest_of::<Utf8>(topic.cast(), node.cast()) }
|
||||
}
|
||||
|
||||
/// The same as `BakaShrot_GetLatestMessageOfA`, in UTF-16.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_GetLatestMessageOfW(
|
||||
topic: *const u16,
|
||||
node: *const u16,
|
||||
) -> isize {
|
||||
unsafe { latest_of::<Utf16>(topic, node) }
|
||||
}
|
||||
|
||||
unsafe fn messages<T: Text>(
|
||||
topic: *const T::Unit,
|
||||
node: *const T::Unit,
|
||||
after: i64,
|
||||
limit: i32,
|
||||
) -> i32 {
|
||||
call(-1, |state| {
|
||||
let (topic, node) = unsafe { topic_and_node::<T>(topic, node)? };
|
||||
state.clear_messages(&topic, &node);
|
||||
let after =
|
||||
u64::try_from(after).map_err(|_| invalid(format!("after {after}: 0 or more")))?;
|
||||
let limit = u32::try_from(limit).map_err(|_| invalid(format!("a limit of {limit}")))?;
|
||||
let answer = state
|
||||
.client()?
|
||||
.get_messages(&topic, &node, Some(after), limit)?;
|
||||
state.more = answer.more;
|
||||
state.messages = answer.messages;
|
||||
Ok(state.messages.len() as i32)
|
||||
})
|
||||
}
|
||||
|
||||
/// Gets the messages of `topic` and `node` after id `after` (0 for the
|
||||
/// first ones), in order: `limit` at most (1-10000), fewer past about
|
||||
/// 1 MB. Returns how many came (none isn't a failure), -1 on failure. The
|
||||
/// first is selected; `BakaShrot_SelectMessage()` selects the others,
|
||||
/// `BakaShrot_HasMoreMessages()` says whether more follow the last one.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_GetMessagesA(
|
||||
topic: *const c_char,
|
||||
node: *const c_char,
|
||||
after: i64,
|
||||
limit: i32,
|
||||
) -> i32 {
|
||||
unsafe { messages::<Utf8>(topic.cast(), node.cast(), after, limit) }
|
||||
}
|
||||
|
||||
/// The same as `BakaShrot_GetMessagesA`, in UTF-16.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_GetMessagesW(
|
||||
topic: *const u16,
|
||||
node: *const u16,
|
||||
after: i64,
|
||||
limit: i32,
|
||||
) -> i32 {
|
||||
unsafe { messages::<Utf16>(topic, node, after, limit) }
|
||||
}
|
||||
|
||||
/// How many messages the last `GetMessages` or `GetLatestMessageOf` got.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn BakaShrot_GetMessageCount() -> i32 {
|
||||
get(0, |state| state.messages.len() as i32)
|
||||
}
|
||||
|
||||
/// Selects the message at `index` (0 to the count - 1) for the getters: 0
|
||||
/// if there's none there (`InvalidArgument`), the selection unchanged.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn BakaShrot_SelectMessage(index: i32) -> isize {
|
||||
call(0, |state| {
|
||||
let index = usize::try_from(index)
|
||||
.ok()
|
||||
.filter(|index| *index < state.messages.len())
|
||||
.ok_or_else(|| invalid(format!("no message at {index}")))?;
|
||||
state.selected = index;
|
||||
Ok(1)
|
||||
})
|
||||
}
|
||||
|
||||
/// 1 if more messages follow the last one the last `GetMessages` got: ask
|
||||
/// again after its id.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn BakaShrot_HasMoreMessages() -> isize {
|
||||
get(0, |state| bool_result(state.more))
|
||||
}
|
||||
|
||||
/// The selected message's id, 0 if none.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn BakaShrot_GetMessageId() -> i64 {
|
||||
get(0, |state| {
|
||||
state.message().map_or(0, |message| message.id as i64)
|
||||
})
|
||||
}
|
||||
|
||||
/// When the selected message was pushed, by the server it was pushed to:
|
||||
/// milliseconds since 1970-01-01 UTC, 0 if none.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn BakaShrot_GetMessagePushedAt() -> i64 {
|
||||
get(0, |state| {
|
||||
state
|
||||
.message()
|
||||
.map_or(0, |message| message.pushed_at as i64)
|
||||
})
|
||||
}
|
||||
|
||||
/// The selected message's attachment's size, 0 without one.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn BakaShrot_GetMessageAttachmentSize() -> i64 {
|
||||
get(0, |state| {
|
||||
state
|
||||
.message()
|
||||
.and_then(|message| message.attachment.as_ref())
|
||||
.map_or(0, |attachment| attachment.size as i64)
|
||||
})
|
||||
}
|
||||
|
||||
/// 1 if the selected message's attachment is all on this server (a
|
||||
/// replicated one may still be on its way).
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn BakaShrot_IsMessageAttachmentReady() -> isize {
|
||||
get(0, |state| {
|
||||
let attachment = state
|
||||
.message()
|
||||
.and_then(|message| message.attachment.as_ref());
|
||||
bool_result(attachment.is_some_and(|attachment| attachment.ready))
|
||||
})
|
||||
}
|
||||
|
||||
/// The selected message's data, as pushed (JSON or not).
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_GetMessageDataA(buffer: *mut c_char, size: isize) -> isize {
|
||||
unsafe {
|
||||
get_text::<Utf8>(buffer.cast(), size, |state| {
|
||||
state.message().map_or("", |message| &message.data)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The same as `BakaShrot_GetMessageDataA`, in UTF-16.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_GetMessageDataW(buffer: *mut u16, size: isize) -> isize {
|
||||
unsafe {
|
||||
get_text::<Utf16>(buffer, size, |state| {
|
||||
state.message().map_or("", |message| &message.data)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The topic the last `GetMessages` or `GetLatestMessageOf` asked for.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_GetMessageTopicA(buffer: *mut c_char, size: isize) -> isize {
|
||||
unsafe { get_text::<Utf8>(buffer.cast(), size, |state| &state.topic) }
|
||||
}
|
||||
|
||||
/// The same as `BakaShrot_GetMessageTopicA`, in UTF-16.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_GetMessageTopicW(buffer: *mut u16, size: isize) -> isize {
|
||||
unsafe { get_text::<Utf16>(buffer, size, |state| &state.topic) }
|
||||
}
|
||||
|
||||
/// The node the last `GetMessages` or `GetLatestMessageOf` asked for.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_GetMessageNodeA(buffer: *mut c_char, size: isize) -> isize {
|
||||
unsafe { get_text::<Utf8>(buffer.cast(), size, |state| &state.node) }
|
||||
}
|
||||
|
||||
/// The same as `BakaShrot_GetMessageNodeA`, in UTF-16.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_GetMessageNodeW(buffer: *mut u16, size: isize) -> isize {
|
||||
unsafe { get_text::<Utf16>(buffer, size, |state| &state.node) }
|
||||
}
|
||||
|
||||
// --- Names -------------------------------------------------------------------
|
||||
|
||||
fn list(kind: NameKind) -> i32 {
|
||||
call(-1, |state| {
|
||||
state.names.clear();
|
||||
let list = state.client()?.list_names(kind)?;
|
||||
let kind = match kind {
|
||||
NameKind::Topic => "topic",
|
||||
NameKind::Node => "node",
|
||||
};
|
||||
let count = list.names.len() as i32;
|
||||
state.names = serde_json::json!({
|
||||
"kind": kind,
|
||||
"truncated": list.truncated,
|
||||
"names": list.names,
|
||||
})
|
||||
.to_string();
|
||||
Ok(count)
|
||||
})
|
||||
}
|
||||
|
||||
/// Lists the topics this client may push to or read (every one if it may
|
||||
/// query): how many, -1 on failure. Then `BakaShrot_GetNamesList()`.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn BakaShrot_ListTopics() -> i32 {
|
||||
list(NameKind::Topic)
|
||||
}
|
||||
|
||||
/// Lists every node with messages: how many, -1 on failure. Then
|
||||
/// `BakaShrot_GetNamesList()`.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn BakaShrot_ListNodes() -> i32 {
|
||||
list(NameKind::Node)
|
||||
}
|
||||
|
||||
/// The last list, as JSON:
|
||||
/// `{"kind":"topic","truncated":false,"names":["logs",...]}`, `truncated`
|
||||
/// if some didn't fit.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_GetNamesListA(buffer: *mut c_char, size: isize) -> isize {
|
||||
unsafe { get_text::<Utf8>(buffer.cast(), size, |state| &state.names) }
|
||||
}
|
||||
|
||||
/// The same as `BakaShrot_GetNamesListA`, in UTF-16.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_GetNamesListW(buffer: *mut u16, size: isize) -> isize {
|
||||
unsafe { get_text::<Utf16>(buffer, size, |state| &state.names) }
|
||||
}
|
||||
|
||||
// --- Queries -----------------------------------------------------------------
|
||||
|
||||
unsafe fn query<T: Text>(sql: *const T::Unit) -> isize {
|
||||
call(0, |state| {
|
||||
state.query.clear();
|
||||
let sql = required(unsafe { text::read::<T>(sql, "query")? }, "query")?;
|
||||
state.query = state.client()?.query(&sql)?;
|
||||
Ok(1)
|
||||
})
|
||||
}
|
||||
|
||||
/// Runs read-only SQL on the server (one SELECT or WITH), if this client
|
||||
/// may query. Then `BakaShrot_GetQueryResult()`.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_QueryA(sql: *const c_char) -> isize {
|
||||
unsafe { query::<Utf8>(sql.cast()) }
|
||||
}
|
||||
|
||||
/// The same as `BakaShrot_QueryA`, in UTF-16.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_QueryW(sql: *const u16) -> isize {
|
||||
unsafe { query::<Utf16>(sql) }
|
||||
}
|
||||
|
||||
/// The last query's result, as JSON:
|
||||
/// `{"columns":[...],"rows":[[...],...]}`, every value a string or null.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_GetQueryResultA(buffer: *mut c_char, size: isize) -> isize {
|
||||
unsafe { get_text::<Utf8>(buffer.cast(), size, |state| &state.query) }
|
||||
}
|
||||
|
||||
/// The same as `BakaShrot_GetQueryResultA`, in UTF-16.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_GetQueryResultW(buffer: *mut u16, size: isize) -> isize {
|
||||
unsafe { get_text::<Utf16>(buffer, size, |state| &state.query) }
|
||||
}
|
||||
|
||||
// --- Attachments -------------------------------------------------------------
|
||||
|
||||
/// A message id, as arguments.
|
||||
fn message_id(id: i64) -> Result<u64> {
|
||||
u64::try_from(id).map_err(|_| invalid(format!("message {id}")))
|
||||
}
|
||||
|
||||
unsafe fn push_with_file<T: Text>(
|
||||
topic: *const T::Unit,
|
||||
data: *const T::Unit,
|
||||
path: *const T::Unit,
|
||||
) -> i64 {
|
||||
call(-1, |state| {
|
||||
let (topic, data) = unsafe { topic_and_data::<T>(topic, data)? };
|
||||
let path = required(unsafe { text::read::<T>(path, "the file")? }, "file")?;
|
||||
let mut file = File::open(&path)
|
||||
.map_err(|error| Error::new(ErrorCode::FileError, format!("{path}: {error}")))?;
|
||||
let id = state
|
||||
.client()?
|
||||
.push_with_attachment(&topic, &data, &mut file)?;
|
||||
Ok(id as i64)
|
||||
})
|
||||
}
|
||||
|
||||
/// Pushes a message with the file at `FilePath` as its attachment (1 byte
|
||||
/// to 1 TiB, the server may take less: `TooBig`): uploaded with it, the
|
||||
/// message stored once all of it came. Its id, -1 on failure. The file is
|
||||
/// read twice (its SHA-256 first): one changed in between is refused
|
||||
/// (`DataMismatch`).
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_PushMessageWithFileA(
|
||||
topic: *const c_char,
|
||||
data: *const c_char,
|
||||
file_path: *const c_char,
|
||||
) -> i64 {
|
||||
unsafe { push_with_file::<Utf8>(topic.cast(), data.cast(), file_path.cast()) }
|
||||
}
|
||||
|
||||
/// The same as `BakaShrot_PushMessageWithFileA`, in UTF-16.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_PushMessageWithFileW(
|
||||
topic: *const u16,
|
||||
data: *const u16,
|
||||
file_path: *const u16,
|
||||
) -> i64 {
|
||||
unsafe { push_with_file::<Utf16>(topic, data, file_path) }
|
||||
}
|
||||
|
||||
unsafe fn push_with_data<T: Text>(
|
||||
topic: *const T::Unit,
|
||||
data: *const T::Unit,
|
||||
attachment: *const c_void,
|
||||
size: i64,
|
||||
) -> i64 {
|
||||
call(-1, |state| {
|
||||
let (topic, data) = unsafe { topic_and_data::<T>(topic, data)? };
|
||||
if attachment.is_null() {
|
||||
return Err(invalid("no attachment (a null pointer)"));
|
||||
}
|
||||
let size = usize::try_from(size)
|
||||
.ok()
|
||||
.filter(|size| *size > 0)
|
||||
.ok_or_else(|| invalid(format!("an attachment of {size} bytes")))?;
|
||||
let bytes = unsafe { std::slice::from_raw_parts(attachment.cast::<u8>(), size) };
|
||||
let id = state
|
||||
.client()?
|
||||
.push_with_attachment(&topic, &data, &mut Cursor::new(bytes))?;
|
||||
Ok(id as i64)
|
||||
})
|
||||
}
|
||||
|
||||
/// Pushes a message with the `Size` bytes at `Data` as its attachment, as
|
||||
/// `BakaShrot_PushMessageWithFileA` does.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_PushMessageWithDataA(
|
||||
topic: *const c_char,
|
||||
data: *const c_char,
|
||||
attachment: *const c_void,
|
||||
size: i64,
|
||||
) -> i64 {
|
||||
unsafe { push_with_data::<Utf8>(topic.cast(), data.cast(), attachment, size) }
|
||||
}
|
||||
|
||||
/// The same as `BakaShrot_PushMessageWithDataA`, in UTF-16.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_PushMessageWithDataW(
|
||||
topic: *const u16,
|
||||
data: *const u16,
|
||||
attachment: *const c_void,
|
||||
size: i64,
|
||||
) -> i64 {
|
||||
unsafe { push_with_data::<Utf16>(topic, data, attachment, size) }
|
||||
}
|
||||
|
||||
unsafe fn save<T: Text>(
|
||||
topic: *const T::Unit,
|
||||
node: *const T::Unit,
|
||||
id: i64,
|
||||
path: *const T::Unit,
|
||||
) -> i64 {
|
||||
call(-1, |state| {
|
||||
let (topic, node) = unsafe { topic_and_node::<T>(topic, node)? };
|
||||
let path = required(unsafe { text::read::<T>(path, "the file")? }, "file")?;
|
||||
let size =
|
||||
state
|
||||
.client()?
|
||||
.save_attachment(&topic, &node, message_id(id)?, Path::new(&path))?;
|
||||
Ok(size as i64)
|
||||
})
|
||||
}
|
||||
|
||||
/// Saves the attachment of `Topic`, `Node`'s message `MessageId` as the
|
||||
/// file at `FilePath` (replaced), read a part at a time and checked with
|
||||
/// its SHA-256: its size, -1 on failure (`NotFound` without one,
|
||||
/// `NotReady` if it isn't on this server yet, `AttachmentMismatch`). A
|
||||
/// failed one leaves no file.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_SaveAttachmentA(
|
||||
topic: *const c_char,
|
||||
node: *const c_char,
|
||||
message_id: i64,
|
||||
file_path: *const c_char,
|
||||
) -> i64 {
|
||||
unsafe { save::<Utf8>(topic.cast(), node.cast(), message_id, file_path.cast()) }
|
||||
}
|
||||
|
||||
/// The same as `BakaShrot_SaveAttachmentA`, in UTF-16.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_SaveAttachmentW(
|
||||
topic: *const u16,
|
||||
node: *const u16,
|
||||
message_id: i64,
|
||||
file_path: *const u16,
|
||||
) -> i64 {
|
||||
unsafe { save::<Utf16>(topic, node, message_id, file_path) }
|
||||
}
|
||||
|
||||
unsafe fn load<T: Text>(topic: *const T::Unit, node: *const T::Unit, id: i64) -> i64 {
|
||||
call(-1, |state| {
|
||||
state.attachment = Vec::new();
|
||||
let (topic, node) = unsafe { topic_and_node::<T>(topic, node)? };
|
||||
let mut attachment = Vec::new();
|
||||
let size =
|
||||
state
|
||||
.client()?
|
||||
.get_attachment(&topic, &node, message_id(id)?, &mut attachment)?;
|
||||
state.attachment = attachment;
|
||||
Ok(size as i64)
|
||||
})
|
||||
}
|
||||
|
||||
/// Reads the attachment of `Topic`, `Node`'s message `MessageId` into
|
||||
/// memory, checked with its SHA-256 (`BakaShrot_SaveAttachmentA` for big
|
||||
/// ones): its size, -1 on failure. Then `BakaShrot_GetAttachmentData()`.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_LoadAttachmentA(
|
||||
topic: *const c_char,
|
||||
node: *const c_char,
|
||||
message_id: i64,
|
||||
) -> i64 {
|
||||
unsafe { load::<Utf8>(topic.cast(), node.cast(), message_id) }
|
||||
}
|
||||
|
||||
/// The same as `BakaShrot_LoadAttachmentA`, in UTF-16.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_LoadAttachmentW(
|
||||
topic: *const u16,
|
||||
node: *const u16,
|
||||
message_id: i64,
|
||||
) -> i64 {
|
||||
unsafe { load::<Utf16>(topic, node, message_id) }
|
||||
}
|
||||
|
||||
/// Copies what the last `BakaShrot_LoadAttachment()` read into `Buffer`, if
|
||||
/// `BufferSize` is enough: returns its size (0 if none), copies nothing if
|
||||
/// it doesn't fit (a null `Buffer` asks for the size).
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_GetAttachmentData(buffer: *mut c_void, buffer_size: i64) -> i64 {
|
||||
get(0, |state| {
|
||||
let data = &state.attachment;
|
||||
if !buffer.is_null() && usize::try_from(buffer_size).is_ok_and(|size| size >= data.len()) {
|
||||
unsafe { std::ptr::copy_nonoverlapping(data.as_ptr(), buffer.cast(), data.len()) };
|
||||
}
|
||||
data.len() as i64
|
||||
})
|
||||
}
|
||||
|
||||
/// Frees what `BakaShrot_LoadAttachment()` read: 1.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn BakaShrot_FreeAttachmentData() -> isize {
|
||||
let freed = catch_unwind(AssertUnwindSafe(|| state().attachment = Vec::new()));
|
||||
bool_result(freed.is_ok())
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
//! Strings across the C boundary: arguments read as UTF-8 (`A` exports) or
|
||||
//! UTF-16 (`W` exports), answers copied into the caller's buffers.
|
||||
|
||||
use bakashrot_client::Error;
|
||||
use bakashrot_proto::ErrorCode;
|
||||
|
||||
/// An encoding of the exports' strings.
|
||||
pub(crate) trait Text {
|
||||
/// One code unit: `u8` or `u16`.
|
||||
type Unit: Copy + Default + PartialEq;
|
||||
/// Its name, for errors.
|
||||
const NAME: &'static str;
|
||||
fn decode(units: &[Self::Unit]) -> Option<String>;
|
||||
fn encode(text: &str) -> Vec<Self::Unit>;
|
||||
}
|
||||
|
||||
/// UTF-8, `char*`: the `A` exports.
|
||||
pub(crate) struct Utf8;
|
||||
|
||||
impl Text for Utf8 {
|
||||
type Unit = u8;
|
||||
const NAME: &'static str = "UTF-8";
|
||||
|
||||
fn decode(units: &[u8]) -> Option<String> {
|
||||
String::from_utf8(units.to_vec()).ok()
|
||||
}
|
||||
|
||||
fn encode(text: &str) -> Vec<u8> {
|
||||
text.as_bytes().to_vec()
|
||||
}
|
||||
}
|
||||
|
||||
/// UTF-16, `uint16_t*` (`wchar_t*` on Windows): the `W` exports.
|
||||
pub(crate) struct Utf16;
|
||||
|
||||
impl Text for Utf16 {
|
||||
type Unit = u16;
|
||||
const NAME: &'static str = "UTF-16";
|
||||
|
||||
fn decode(units: &[u16]) -> Option<String> {
|
||||
String::from_utf16(units).ok()
|
||||
}
|
||||
|
||||
fn encode(text: &str) -> Vec<u16> {
|
||||
text.encode_utf16().collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// A null-terminated string argument; `None` for a null pointer (what
|
||||
/// PureBasic passes for an empty string).
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// `pointer` is null, or points to a string ending with a zero unit.
|
||||
pub(crate) unsafe fn read<T: Text>(
|
||||
pointer: *const T::Unit,
|
||||
what: &str,
|
||||
) -> Result<Option<String>, Error> {
|
||||
if pointer.is_null() {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut units = Vec::new();
|
||||
loop {
|
||||
// Unaligned: callers' buffers may be byte arrays.
|
||||
let unit = unsafe { pointer.add(units.len()).read_unaligned() };
|
||||
if unit == T::Unit::default() {
|
||||
break;
|
||||
}
|
||||
units.push(unit);
|
||||
}
|
||||
T::decode(&units).map(Some).ok_or_else(|| {
|
||||
Error::new(
|
||||
ErrorCode::InvalidArgument,
|
||||
format!("{what}: not valid {}", T::NAME),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// Copies `text`, terminated, into `buffer` of `size` bytes if it fits
|
||||
/// (nothing otherwise, or with a null `buffer`): the bytes it needs.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// `buffer` is null, or writable for `size` bytes.
|
||||
pub(crate) unsafe fn copy<T: Text>(text: &str, buffer: *mut T::Unit, size: isize) -> isize {
|
||||
let mut units = T::encode(text);
|
||||
units.push(T::Unit::default());
|
||||
let needed = std::mem::size_of_val(units.as_slice());
|
||||
if !buffer.is_null() && size >= needed as isize {
|
||||
unsafe {
|
||||
std::ptr::copy_nonoverlapping(units.as_ptr().cast::<u8>(), buffer.cast::<u8>(), needed);
|
||||
}
|
||||
}
|
||||
needed as isize
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
//! A server on a free port, in a folder of its own with its CA and the
|
||||
//! clients' certificates.
|
||||
|
||||
use bakashrot_config::Config;
|
||||
use bakashrot_pki::{Ca, Identity, Usage};
|
||||
use bakashrot_server::Server;
|
||||
use std::path::PathBuf;
|
||||
|
||||
const CONFIG: &str = r#"
|
||||
[server]
|
||||
listen = "127.0.0.1:0"
|
||||
ca = "ca.crt"
|
||||
certificate = "server.crt"
|
||||
key = "server.key"
|
||||
topics = ["logs", "secret"]
|
||||
|
||||
[roles.home]
|
||||
push_topics = ["logs", "secret"]
|
||||
read_topics = ["*"]
|
||||
query = true
|
||||
|
||||
[roles.lounge]
|
||||
read_topics = ["logs"]
|
||||
"#;
|
||||
|
||||
pub struct Running {
|
||||
pub folder: PathBuf,
|
||||
pub port: u16,
|
||||
ca: Ca,
|
||||
// Kept for the server's tasks to run.
|
||||
_runtime: tokio::runtime::Runtime,
|
||||
}
|
||||
|
||||
impl Running {
|
||||
pub fn start(name: &str) -> Running {
|
||||
let folder = PathBuf::from(env!("CARGO_TARGET_TMPDIR"))
|
||||
.join(format!("capi-{}-{name}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&folder);
|
||||
std::fs::create_dir_all(&folder).unwrap();
|
||||
let issued = Ca::create("Test CA", 10).unwrap();
|
||||
let ca = Ca::load(&issued.certificate, &issued.key).unwrap();
|
||||
let server = ca
|
||||
.issue(
|
||||
&Identity::new("server-1", &["peer"]).unwrap(),
|
||||
Usage::Server,
|
||||
10,
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(folder.join("ca.crt"), &issued.certificate).unwrap();
|
||||
std::fs::write(folder.join("server.crt"), &server.certificate).unwrap();
|
||||
std::fs::write(folder.join("server.key"), &server.key).unwrap();
|
||||
// `SYNC=normal` to measure without a disk flush per push.
|
||||
let sync = std::env::var("SYNC").unwrap_or_else(|_| "full".into());
|
||||
let config = CONFIG.replace(
|
||||
"[roles.home]",
|
||||
&format!(
|
||||
"synchronous = \"{sync}\"
|
||||
|
||||
[roles.home]"
|
||||
),
|
||||
);
|
||||
std::fs::write(folder.join("server.toml"), config).unwrap();
|
||||
let config = Config::load(&folder.join("server.toml")).unwrap();
|
||||
let server = Server::start(config).unwrap();
|
||||
|
||||
let runtime = tokio::runtime::Runtime::new().unwrap();
|
||||
let listener = runtime
|
||||
.block_on(tokio::net::TcpListener::bind("127.0.0.1:0"))
|
||||
.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
runtime.spawn(async move { server.serve(listener).await });
|
||||
Running {
|
||||
folder,
|
||||
port,
|
||||
ca,
|
||||
_runtime: runtime,
|
||||
}
|
||||
}
|
||||
|
||||
/// Issues a client's certificate, written as `<name>.crt` and
|
||||
/// `<name>.key`, with a `<name>.toml` to connect with.
|
||||
pub fn issue(&self, name: &str, roles: &[&str]) {
|
||||
let issued = self
|
||||
.ca
|
||||
.issue(&Identity::new(name, roles).unwrap(), Usage::Client, 10)
|
||||
.unwrap();
|
||||
std::fs::write(self.folder.join(format!("{name}.crt")), &issued.certificate).unwrap();
|
||||
std::fs::write(self.folder.join(format!("{name}.key")), &issued.key).unwrap();
|
||||
let toml = format!(
|
||||
"server = \"127.0.0.1:{}\"\nca = \"ca.crt\"\ncertificate = \"{name}.crt\"\nkey = \"{name}.key\"\n",
|
||||
self.port
|
||||
);
|
||||
std::fs::write(self.folder.join(format!("{name}.toml")), toml).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,341 @@
|
||||
//! The exports called as C would, against a server: the `W` ones (what
|
||||
//! PureBasic uses; Python's check covers the `A` ones), the buffers, the
|
||||
//! errors. One test: the DLL holds one connection per process.
|
||||
|
||||
#![allow(unsafe_code)]
|
||||
|
||||
mod common;
|
||||
|
||||
use bakashrot::*;
|
||||
use bakashrot_proto::ErrorCode;
|
||||
use std::ffi::{CString, c_char};
|
||||
|
||||
fn w(text: &str) -> Vec<u16> {
|
||||
text.encode_utf16().chain([0]).collect()
|
||||
}
|
||||
|
||||
fn a(text: &str) -> CString {
|
||||
CString::new(text).unwrap()
|
||||
}
|
||||
|
||||
/// A `W` getter's string: asks for the size, then copies.
|
||||
fn get_w(getter: unsafe extern "C" fn(*mut u16, isize) -> isize) -> String {
|
||||
let size = unsafe { getter(std::ptr::null_mut(), 0) };
|
||||
let mut buffer = vec![0u16; size as usize / 2];
|
||||
unsafe { getter(buffer.as_mut_ptr(), size) };
|
||||
String::from_utf16(&buffer[..buffer.len() - 1]).unwrap()
|
||||
}
|
||||
|
||||
fn get_a(getter: unsafe extern "C" fn(*mut c_char, isize) -> isize) -> String {
|
||||
let size = unsafe { getter(std::ptr::null_mut(), 0) };
|
||||
let mut buffer = vec![0u8; size as usize];
|
||||
unsafe { getter(buffer.as_mut_ptr().cast(), size) };
|
||||
String::from_utf8(buffer[..buffer.len() - 1].to_vec()).unwrap()
|
||||
}
|
||||
|
||||
/// The last error's code and reason.
|
||||
fn error() -> (u32, String) {
|
||||
(
|
||||
BakaShrot_GetLastError() as u32,
|
||||
get_w(BakaShrot_GetRefusalReasonW),
|
||||
)
|
||||
}
|
||||
|
||||
fn code(code: ErrorCode) -> u32 {
|
||||
code.code()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exports() {
|
||||
let running = common::Running::start("exports");
|
||||
running.issue("kitchen", &["home"]);
|
||||
running.issue("lounge", &["lounge"]);
|
||||
let file = |name: &str| running.folder.join(name).display().to_string();
|
||||
let pem = |name: &str| std::fs::read_to_string(running.folder.join(name)).unwrap();
|
||||
let localhost = w("127.0.0.1");
|
||||
let port = i32::from(running.port);
|
||||
|
||||
unsafe {
|
||||
// Nothing set, not connected.
|
||||
assert_eq!(
|
||||
BakaShrot_PushMessageToW(w("logs").as_ptr(), w("{}").as_ptr()),
|
||||
-1
|
||||
);
|
||||
assert_eq!(error().0, code(ErrorCode::NotConnected));
|
||||
assert_eq!(BakaShrot_ConnectW(localhost.as_ptr(), port), 0);
|
||||
let (failed, why) = error();
|
||||
assert_eq!(failed, code(ErrorCode::InvalidArgument));
|
||||
assert!(why.contains("BakaShrot_SetCaCertificate"), "{why}");
|
||||
|
||||
// Files or PEM text; a missing file, an empty setting.
|
||||
assert_eq!(
|
||||
BakaShrot_SetCaCertificateW(w(&file("missing.crt")).as_ptr()),
|
||||
0
|
||||
);
|
||||
assert_eq!(error().0, code(ErrorCode::FileError));
|
||||
assert_eq!(BakaShrot_SetCertificateW(std::ptr::null()), 0);
|
||||
assert_eq!(error().0, code(ErrorCode::InvalidArgument));
|
||||
assert_eq!(BakaShrot_SetCaCertificateW(w(&file("ca.crt")).as_ptr()), 1);
|
||||
assert_eq!(BakaShrot_GetLastError(), 0);
|
||||
assert_eq!(
|
||||
BakaShrot_SetCertificateW(w(&pem("kitchen.crt")).as_ptr()),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
BakaShrot_SetPrivateKeyA(a(&file("kitchen.key")).as_ptr()),
|
||||
1
|
||||
);
|
||||
assert_eq!(BakaShrot_SetCrlW(std::ptr::null()), 1);
|
||||
assert_eq!(BakaShrot_ConnectW(localhost.as_ptr(), 0), 0);
|
||||
assert_eq!(error().0, code(ErrorCode::InvalidArgument));
|
||||
|
||||
assert_eq!(
|
||||
BakaShrot_ConnectW(localhost.as_ptr(), port),
|
||||
1,
|
||||
"{:?}",
|
||||
error()
|
||||
);
|
||||
assert_eq!(BakaShrot_IsConnected(), 1);
|
||||
assert_eq!(get_w(BakaShrot_GetNodeW), "kitchen");
|
||||
assert_eq!(BakaShrot_ConnectW(localhost.as_ptr(), port), 0);
|
||||
assert_eq!(error().0, code(ErrorCode::AlreadyConnected));
|
||||
assert_eq!(BakaShrot_SetCaCertificateW(w(&file("ca.crt")).as_ptr()), 0);
|
||||
assert_eq!(error().0, code(ErrorCode::AlreadyConnected));
|
||||
|
||||
// Pushes: UTF-16, a null message is an empty one.
|
||||
assert_eq!(
|
||||
BakaShrot_PushMessageToW(w("logs").as_ptr(), w(r#"{"i":1}"#).as_ptr()),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
BakaShrot_PushMessageToW(w("logs").as_ptr(), w("héllo 🌍").as_ptr()),
|
||||
2
|
||||
);
|
||||
assert_eq!(
|
||||
BakaShrot_PushMessageToW(w("logs").as_ptr(), std::ptr::null()),
|
||||
3
|
||||
);
|
||||
assert_eq!(
|
||||
BakaShrot_PushMessageToW(std::ptr::null(), w("{}").as_ptr()),
|
||||
-1
|
||||
);
|
||||
assert_eq!(error().0, code(ErrorCode::InvalidArgument));
|
||||
assert_eq!(
|
||||
BakaShrot_PushMessageToW(w("nothing").as_ptr(), w("{}").as_ptr()),
|
||||
-1
|
||||
);
|
||||
let (failed, why) = error();
|
||||
assert_eq!(failed, code(ErrorCode::UnknownName));
|
||||
assert!(why.contains("unknown topic"), "{why}");
|
||||
|
||||
// The latest; none yet in another topic.
|
||||
assert_eq!(
|
||||
BakaShrot_GetLatestMessageOfW(w("logs").as_ptr(), w("kitchen").as_ptr()),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
(BakaShrot_GetMessageCount(), BakaShrot_GetMessageId()),
|
||||
(1, 3)
|
||||
);
|
||||
assert_eq!(get_w(BakaShrot_GetMessageDataW), "");
|
||||
assert!(BakaShrot_GetMessagePushedAt() > 1_700_000_000_000);
|
||||
assert_eq!(BakaShrot_GetMessageAttachmentSize(), 0);
|
||||
assert_eq!(BakaShrot_IsMessageAttachmentReady(), 0);
|
||||
assert_eq!(
|
||||
BakaShrot_GetLatestMessageOfW(w("secret").as_ptr(), w("kitchen").as_ptr()),
|
||||
0
|
||||
);
|
||||
assert_eq!(error().0, code(ErrorCode::NotFound));
|
||||
assert_eq!(BakaShrot_GetMessageCount(), 0);
|
||||
|
||||
// A run of messages, selected one by one.
|
||||
assert_eq!(
|
||||
BakaShrot_GetMessagesW(w("logs").as_ptr(), w("kitchen").as_ptr(), 0, 2),
|
||||
2
|
||||
);
|
||||
assert_eq!(BakaShrot_HasMoreMessages(), 1);
|
||||
assert_eq!(get_w(BakaShrot_GetMessageTopicW), "logs");
|
||||
assert_eq!(get_w(BakaShrot_GetMessageNodeW), "kitchen");
|
||||
assert_eq!(BakaShrot_GetMessageId(), 1);
|
||||
assert_eq!(BakaShrot_SelectMessage(1), 1);
|
||||
assert_eq!(get_w(BakaShrot_GetMessageDataW), "héllo 🌍");
|
||||
assert_eq!(get_a(BakaShrot_GetMessageDataA), "héllo 🌍");
|
||||
assert_eq!(BakaShrot_SelectMessage(2), 0);
|
||||
assert_eq!(error().0, code(ErrorCode::InvalidArgument));
|
||||
assert_eq!(BakaShrot_GetMessageId(), 2, "the selection stays");
|
||||
assert_eq!(
|
||||
BakaShrot_GetMessagesW(w("logs").as_ptr(), w("kitchen").as_ptr(), 3, 10),
|
||||
0
|
||||
);
|
||||
assert_eq!(BakaShrot_HasMoreMessages(), 0);
|
||||
assert_eq!(BakaShrot_GetMessageId(), 0);
|
||||
for (after, limit) in [(-1, 10), (0, 0), (0, 10_001)] {
|
||||
assert_eq!(
|
||||
BakaShrot_GetMessagesW(w("logs").as_ptr(), w("kitchen").as_ptr(), after, limit),
|
||||
-1
|
||||
);
|
||||
assert_eq!(error().0, code(ErrorCode::InvalidArgument));
|
||||
}
|
||||
assert_eq!(
|
||||
BakaShrot_GetMessagesW(w("logs").as_ptr(), w("nobody").as_ptr(), 0, 10),
|
||||
-1
|
||||
);
|
||||
assert_eq!(error().0, code(ErrorCode::UnknownName));
|
||||
assert_eq!(BakaShrot_IsConnected(), 1, "a refusal keeps the connection");
|
||||
|
||||
// The buffers: the size needed, nothing copied if it doesn't fit.
|
||||
BakaShrot_GetMessagesW(w("logs").as_ptr(), w("kitchen").as_ptr(), 0, 1);
|
||||
assert_eq!(BakaShrot_GetMessageDataW(std::ptr::null_mut(), 0), 16);
|
||||
assert_eq!(BakaShrot_GetMessageDataA(std::ptr::null_mut(), 0), 8);
|
||||
let mut small = [7u16; 7];
|
||||
assert_eq!(BakaShrot_GetMessageDataW(small.as_mut_ptr(), 14), 16);
|
||||
assert_eq!(small, [7; 7]);
|
||||
// Unaligned: a byte buffer.
|
||||
let mut bytes = [0u8; 17];
|
||||
assert_eq!(
|
||||
BakaShrot_GetMessageDataW(bytes[1..].as_mut_ptr().cast(), 16),
|
||||
16
|
||||
);
|
||||
assert_eq!(bytes[1..3], [b'{', 0]);
|
||||
|
||||
// Names, queries.
|
||||
assert_eq!(BakaShrot_ListTopics(), 2);
|
||||
assert_eq!(
|
||||
get_w(BakaShrot_GetNamesListW),
|
||||
r#"{"kind":"topic","names":["logs","secret"],"truncated":false}"#
|
||||
);
|
||||
assert_eq!(BakaShrot_ListNodes(), 1);
|
||||
assert_eq!(
|
||||
BakaShrot_QueryW(w("SELECT COUNT(*) AS n FROM data").as_ptr()),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
get_w(BakaShrot_GetQueryResultW),
|
||||
r#"{"columns":["n"],"rows":[["3"]]}"#
|
||||
);
|
||||
assert_eq!(BakaShrot_QueryW(w("SELECT nope").as_ptr()), 0);
|
||||
assert_eq!(error().0, code(ErrorCode::QueryFailed));
|
||||
assert_eq!(get_w(BakaShrot_GetQueryResultW), "");
|
||||
|
||||
// Attachments: from a file or memory, saved or loaded back.
|
||||
let (logs, kitchen) = (w("logs"), w("kitchen"));
|
||||
let photo: Vec<u8> = (0..1_500_000u32).map(|i| (i % 251) as u8).collect();
|
||||
std::fs::write(running.folder.join("photo.bin"), &photo).unwrap();
|
||||
let photo_file = w(&file("photo.bin"));
|
||||
let pushed = BakaShrot_PushMessageWithFileW(
|
||||
logs.as_ptr(),
|
||||
w(r#"{"photo":1}"#).as_ptr(),
|
||||
photo_file.as_ptr(),
|
||||
);
|
||||
assert_eq!(pushed, 4, "{:?}", error());
|
||||
let tiny = b"tiny";
|
||||
let pushed = BakaShrot_PushMessageWithDataW(
|
||||
logs.as_ptr(),
|
||||
std::ptr::null(),
|
||||
tiny.as_ptr().cast(),
|
||||
4,
|
||||
);
|
||||
assert_eq!(pushed, 5, "{:?}", error());
|
||||
assert_eq!(
|
||||
BakaShrot_GetLatestMessageOfW(logs.as_ptr(), kitchen.as_ptr()),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
(
|
||||
BakaShrot_GetMessageId(),
|
||||
BakaShrot_GetMessageAttachmentSize(),
|
||||
BakaShrot_IsMessageAttachmentReady()
|
||||
),
|
||||
(5, 4, 1)
|
||||
);
|
||||
let saved = w(&file("saved.bin"));
|
||||
assert_eq!(
|
||||
BakaShrot_SaveAttachmentW(logs.as_ptr(), kitchen.as_ptr(), 4, saved.as_ptr()),
|
||||
1_500_000
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read(running.folder.join("saved.bin")).unwrap(),
|
||||
photo
|
||||
);
|
||||
assert_eq!(
|
||||
BakaShrot_LoadAttachmentW(logs.as_ptr(), kitchen.as_ptr(), 5),
|
||||
4
|
||||
);
|
||||
assert_eq!(BakaShrot_GetAttachmentData(std::ptr::null_mut(), 0), 4);
|
||||
let mut small = [9u8; 3];
|
||||
assert_eq!(BakaShrot_GetAttachmentData(small.as_mut_ptr().cast(), 3), 4);
|
||||
assert_eq!(small, [9; 3], "nothing copied if it doesn't fit");
|
||||
let mut data = [0u8; 4];
|
||||
assert_eq!(BakaShrot_GetAttachmentData(data.as_mut_ptr().cast(), 4), 4);
|
||||
assert_eq!(&data, tiny);
|
||||
assert_eq!(BakaShrot_FreeAttachmentData(), 1);
|
||||
assert_eq!(BakaShrot_GetAttachmentData(std::ptr::null_mut(), 0), 0);
|
||||
assert_eq!(
|
||||
BakaShrot_LoadAttachmentA(a("logs").as_ptr(), a("kitchen").as_ptr(), 4),
|
||||
1_500_000
|
||||
);
|
||||
BakaShrot_FreeAttachmentData();
|
||||
|
||||
// Refused, or the client's own failures: -1, no file.
|
||||
let none = w(&file("none.bin"));
|
||||
assert_eq!(
|
||||
BakaShrot_SaveAttachmentW(logs.as_ptr(), kitchen.as_ptr(), 1, none.as_ptr()),
|
||||
-1
|
||||
);
|
||||
assert_eq!(error().0, code(ErrorCode::NotFound));
|
||||
assert!(!running.folder.join("none.bin").exists());
|
||||
assert_eq!(
|
||||
BakaShrot_SaveAttachmentW(logs.as_ptr(), kitchen.as_ptr(), -1, none.as_ptr()),
|
||||
-1
|
||||
);
|
||||
assert_eq!(error().0, code(ErrorCode::InvalidArgument));
|
||||
let missing = w(&file("missing.bin"));
|
||||
assert_eq!(
|
||||
BakaShrot_PushMessageWithFileW(logs.as_ptr(), std::ptr::null(), missing.as_ptr()),
|
||||
-1
|
||||
);
|
||||
assert_eq!(error().0, code(ErrorCode::FileError));
|
||||
for (pointer, size) in [(std::ptr::null(), 4), (tiny.as_ptr(), 0)] {
|
||||
let pushed = BakaShrot_PushMessageWithDataW(
|
||||
logs.as_ptr(),
|
||||
std::ptr::null(),
|
||||
pointer.cast(),
|
||||
size,
|
||||
);
|
||||
assert_eq!(pushed, -1);
|
||||
assert_eq!(error().0, code(ErrorCode::InvalidArgument));
|
||||
}
|
||||
assert_eq!(BakaShrot_IsConnected(), 1);
|
||||
|
||||
// Closed: requests refused, the settings kept.
|
||||
assert_eq!(BakaShrot_Disconnect(), 1);
|
||||
assert_eq!(BakaShrot_Disconnect(), 0);
|
||||
assert_eq!(BakaShrot_IsConnected(), 0);
|
||||
assert_eq!(get_w(BakaShrot_GetNodeW), "");
|
||||
assert_eq!(BakaShrot_QueryW(w("SELECT 1").as_ptr()), 0);
|
||||
assert_eq!(error().0, code(ErrorCode::NotConnected));
|
||||
|
||||
// Another identity, by the A exports: not allowed to query.
|
||||
assert_eq!(
|
||||
BakaShrot_SetCertificateA(a(&file("lounge.crt")).as_ptr()),
|
||||
1
|
||||
);
|
||||
assert_eq!(BakaShrot_SetPrivateKeyA(a(&pem("lounge.key")).as_ptr()), 1);
|
||||
assert_eq!(
|
||||
BakaShrot_ConnectA(a("localhost").as_ptr(), port),
|
||||
1,
|
||||
"{:?}",
|
||||
error()
|
||||
);
|
||||
assert_eq!(get_a(BakaShrot_GetNodeA), "lounge");
|
||||
assert_eq!(BakaShrot_QueryA(a("SELECT 1").as_ptr()), 0);
|
||||
let (failed, why) = error();
|
||||
assert_eq!(failed, code(ErrorCode::NotAllowed));
|
||||
assert_eq!(get_a(BakaShrot_GetRefusalReasonA), why);
|
||||
BakaShrot_Disconnect();
|
||||
|
||||
// Nothing listening there.
|
||||
assert_eq!(BakaShrot_ConnectA(a("127.0.0.1").as_ptr(), 1), 0);
|
||||
assert_eq!(error().0, code(ErrorCode::ConnectFailed));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
//! `bindings/c/bakashrot.h` matches the exports: rewritten when it doesn't
|
||||
//! (the test fails then, check the new one in).
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
#[test]
|
||||
fn the_header_is_current() {
|
||||
let crate_dir = env!("CARGO_MANIFEST_DIR");
|
||||
let path = Path::new(crate_dir).join("../../bindings/c/bakashrot.h");
|
||||
let mut generated = Vec::new();
|
||||
cbindgen::generate(crate_dir)
|
||||
.expect("cbindgen reads the crate")
|
||||
.write(&mut generated);
|
||||
let current = std::fs::read(&path).unwrap_or_default();
|
||||
if current != generated {
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(&path, &generated).unwrap();
|
||||
panic!("{} was out of date: rewritten, check it in", path.display());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
//! `bindings/python/check_bakashrot.py` on the DLL against a server: the
|
||||
//! Python module and the DLL as an app loads it. Skipped (said so) without
|
||||
//! a Python 3.11+ on the PATH.
|
||||
|
||||
mod common;
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
#[test]
|
||||
fn check_bakashrot_py() {
|
||||
let Some(python) = ["python3", "python"].into_iter().find(|python| {
|
||||
Command::new(python)
|
||||
.args(["-c", "import sys, tomllib; sys.exit(0)"])
|
||||
.output()
|
||||
.is_ok_and(|output| output.status.success())
|
||||
}) else {
|
||||
eprintln!("SKIPPED: no Python 3.11+ on the PATH");
|
||||
return;
|
||||
};
|
||||
|
||||
let dll = built_dll();
|
||||
|
||||
let running = common::Running::start("python");
|
||||
running.issue("kitchen", &["home"]);
|
||||
running.issue("lounge", &["lounge"]);
|
||||
running.issue("guest", &["guest"]);
|
||||
|
||||
let bindings = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../bindings/python");
|
||||
let output = Command::new(python)
|
||||
.arg(bindings.join("check_bakashrot.py"))
|
||||
.arg(&dll)
|
||||
.arg(&running.folder)
|
||||
.env("PYTHONPATH", &bindings)
|
||||
.env("PYTHONIOENCODING", "utf-8")
|
||||
.output()
|
||||
.unwrap();
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
println!("{stdout}");
|
||||
eprintln!("{}", String::from_utf8_lossy(&output.stderr));
|
||||
assert!(output.status.success(), "check_bakashrot.py failed");
|
||||
assert!(stdout.contains("All checks passed"));
|
||||
}
|
||||
|
||||
/// The DLL cargo built with this test: next to it (cargo's older layout),
|
||||
/// or the newest in this crate's build folders (`build/bakashrot-capi/*/out/`).
|
||||
fn built_dll() -> PathBuf {
|
||||
let name = format!(
|
||||
"{}bakashrot{}",
|
||||
std::env::consts::DLL_PREFIX,
|
||||
std::env::consts::DLL_SUFFIX
|
||||
);
|
||||
let exe = std::env::current_exe().unwrap();
|
||||
let here = exe.parent().unwrap();
|
||||
if here.join(&name).exists() {
|
||||
return here.join(name);
|
||||
}
|
||||
let builds = here.ancestors().nth(2).unwrap();
|
||||
std::fs::read_dir(builds)
|
||||
.unwrap()
|
||||
.filter_map(|entry| Some(entry.ok()?.path().join("out").join(&name)))
|
||||
.filter_map(|dll| Some((dll.metadata().ok()?.modified().ok()?, dll)))
|
||||
.max()
|
||||
.map(|(_, dll)| dll)
|
||||
.unwrap_or_else(|| panic!("no {name} built near {}", here.display()))
|
||||
}
|
||||
Reference in New Issue
Block a user