mirror of
https://github.com/aziascreations/BakaShrot.git
synced 2026-11-23 20:58:46 +01:00
Added filtered name lists and the DLL's enumerations, Opened the query connection read-only, Bumped to 0.4.0
- Protocol 8: ListTopics / ListNodes became one ListNames [kind, topics, nodes], each filter a name or a pattern: the topics a node pushed to, the nodes that pushed to a topic, wildcards included. No storage change; the permissions are the lists' (may_list_topic, may_list_nodes_of) - The DLL: the JSON getters are suffixed AsJson (GetNamesListAsJson, GetQueryResultAsJson); ListNamesA/W replaces ListTopics / ListNodes. Beside them, Win32-like enumerations: EnumerateNames / EnumerateQuery, NextName / NextQueryRow (before the first item at first), getters, CloseEnum (enumerations.rs). They don't outlive their client: FreeClient closes them - C#: EnumerateTopics / EnumerateNodes / EnumerateQuery as IEnumerable (QueryRow for a query), fetched at each foreach, closed in finally - Queries: the connection opens the file read-only (SQLITE_OPEN_READ_ONLY), a fifth guard beside query_only, the read-only statement check, one statement only and the PRAGMA-denying authorizer; a unit test checks the handle is read-only - Python, PureBasic, the tool, docs, guides and revamp.md (step 16) updated; versions 0.4.0 everywhere Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,365 @@
|
||||
//! Enumerations: a list of names or a query's rows, kept whole, read an
|
||||
//! item at a time like Win32's `FindFirstFile` / `FindNextFile` /
|
||||
//! `FindClose`. `Next...()` first (an enumeration starts before its first
|
||||
//! item), then the getters; `BakaShrot_CloseEnum()` once done, or
|
||||
//! `BakaShrot_FreeClient()` closes its client's.
|
||||
|
||||
use super::{
|
||||
Error, HANDLES, Result, State, Text, Utf8, Utf16, bool_result, call, fetch_names, fetch_query,
|
||||
invalid, lock, text,
|
||||
};
|
||||
use bakashrot_proto::ErrorCode;
|
||||
use std::ffi::c_char;
|
||||
use std::panic::{AssertUnwindSafe, catch_unwind};
|
||||
|
||||
/// An answer of a client, kept whole.
|
||||
pub(crate) struct Enumeration {
|
||||
pub(crate) client: i64,
|
||||
items: Items,
|
||||
}
|
||||
|
||||
enum Items {
|
||||
Names {
|
||||
names: Cursor<String>,
|
||||
truncated: bool,
|
||||
},
|
||||
Query {
|
||||
columns: Vec<String>,
|
||||
rows: Cursor<Vec<Option<String>>>,
|
||||
},
|
||||
}
|
||||
|
||||
/// Items and where it's at: 0 before the first, `n` on the `n`th, the
|
||||
/// count + 1 past the last.
|
||||
struct Cursor<T> {
|
||||
items: Vec<T>,
|
||||
position: usize,
|
||||
}
|
||||
|
||||
impl<T> Cursor<T> {
|
||||
fn new(items: Vec<T>) -> Cursor<T> {
|
||||
Cursor { items, position: 0 }
|
||||
}
|
||||
|
||||
/// Moves to the next item: whether there was one.
|
||||
fn advance(&mut self) -> bool {
|
||||
self.position = (self.position + 1).min(self.items.len() + 1);
|
||||
self.position <= self.items.len()
|
||||
}
|
||||
|
||||
fn current(&self) -> Option<&T> {
|
||||
self.items.get(self.position.checked_sub(1)?)
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `fetch` on a client, keeps what it gives as an enumeration of that
|
||||
/// client: its handle, 0 if it failed (the client's last error says why).
|
||||
fn enumerate(client: i64, fetch: impl FnOnce(&mut State) -> Result<Items>) -> i64 {
|
||||
call(client, 0, |state| {
|
||||
let items = fetch(state)?;
|
||||
let handles = &mut *lock(&HANDLES);
|
||||
// Freed by another thread during the call: its enumerations went.
|
||||
if !handles.clients.contains_key(&client) {
|
||||
return Err(invalid(format!("client {client} freed during the call")));
|
||||
}
|
||||
let handle = handles.take();
|
||||
handles
|
||||
.enumerations
|
||||
.insert(handle, Enumeration { client, items });
|
||||
Ok(handle)
|
||||
})
|
||||
}
|
||||
|
||||
/// Reads an enumeration: `default` for a bad handle, or `read` giving
|
||||
/// `None` (one of the other kind, no current item, no such column).
|
||||
fn read<R>(handle: i64, default: R, read: impl FnOnce(&mut Items) -> Option<R>) -> R {
|
||||
catch_unwind(AssertUnwindSafe(|| {
|
||||
let handles = &mut *lock(&HANDLES);
|
||||
read(&mut handles.enumerations.get_mut(&handle)?.items)
|
||||
}))
|
||||
.ok()
|
||||
.flatten()
|
||||
.unwrap_or(default)
|
||||
}
|
||||
|
||||
/// A column index, as arguments.
|
||||
fn column(index: i32) -> Option<usize> {
|
||||
usize::try_from(index).ok()
|
||||
}
|
||||
|
||||
/// Closes an enumeration: 1, or 0 if it wasn't one.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn BakaShrot_CloseEnum(enumeration: i64) -> isize {
|
||||
let closed = catch_unwind(|| lock(&HANDLES).enumerations.remove(&enumeration).is_some());
|
||||
bool_result(closed.unwrap_or(false))
|
||||
}
|
||||
|
||||
// --- Names -------------------------------------------------------------------
|
||||
|
||||
unsafe fn enumerate_names<T: Text>(
|
||||
client: i64,
|
||||
kind: i32,
|
||||
topics: *const T::Unit,
|
||||
nodes: *const T::Unit,
|
||||
) -> i64 {
|
||||
enumerate(client, |state| {
|
||||
let list = unsafe { fetch_names::<T>(state, kind, topics, nodes)? };
|
||||
Ok(Items::Names {
|
||||
names: Cursor::new(list.names),
|
||||
truncated: list.truncated,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Lists names as `BakaShrot_ListNames()` does (the same arguments), into
|
||||
/// an enumeration: its handle, 0 on failure (`BakaShrot_GetLastError(client)`).
|
||||
/// Then `BakaShrot_NextName()` and `BakaShrot_GetEnumName()`, and
|
||||
/// `BakaShrot_CloseEnum()`. Closed with its client by
|
||||
/// `BakaShrot_FreeClient()`.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_EnumerateNamesA(
|
||||
client: i64,
|
||||
kind: i32,
|
||||
topics: *const c_char,
|
||||
nodes: *const c_char,
|
||||
) -> i64 {
|
||||
unsafe { enumerate_names::<Utf8>(client, kind, topics.cast(), nodes.cast()) }
|
||||
}
|
||||
|
||||
/// The same as `BakaShrot_EnumerateNamesA`, in UTF-16.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_EnumerateNamesW(
|
||||
client: i64,
|
||||
kind: i32,
|
||||
topics: *const u16,
|
||||
nodes: *const u16,
|
||||
) -> i64 {
|
||||
unsafe { enumerate_names::<Utf16>(client, kind, topics, nodes) }
|
||||
}
|
||||
|
||||
/// Moves to the next name (the first, the first time): 1, 0 if there are
|
||||
/// no more, -1 if it isn't a names enumeration.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn BakaShrot_NextName(enumeration: i64) -> isize {
|
||||
read(enumeration, -1, |items| match items {
|
||||
Items::Names { names, .. } => Some(bool_result(names.advance())),
|
||||
Items::Query { .. } => None,
|
||||
})
|
||||
}
|
||||
|
||||
unsafe fn enum_name<T: Text>(enumeration: i64, buffer: *mut T::Unit, size: isize) -> isize {
|
||||
read(enumeration, 0, |items| match items {
|
||||
Items::Names { names, .. } => names
|
||||
.current()
|
||||
.map(|name| unsafe { text::copy::<T>(name, buffer, size) }),
|
||||
Items::Query { .. } => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The current name: the bytes it needs, 0 if there's none (before the
|
||||
/// first, past the last) or it isn't a names enumeration.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_GetEnumNameA(
|
||||
enumeration: i64,
|
||||
buffer: *mut c_char,
|
||||
size: isize,
|
||||
) -> isize {
|
||||
unsafe { enum_name::<Utf8>(enumeration, buffer.cast(), size) }
|
||||
}
|
||||
|
||||
/// The same as `BakaShrot_GetEnumNameA`, in UTF-16.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_GetEnumNameW(
|
||||
enumeration: i64,
|
||||
buffer: *mut u16,
|
||||
size: isize,
|
||||
) -> isize {
|
||||
unsafe { enum_name::<Utf16>(enumeration, buffer, size) }
|
||||
}
|
||||
|
||||
/// How many names, -1 if it isn't a names enumeration.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn BakaShrot_GetNameCount(enumeration: i64) -> i32 {
|
||||
read(enumeration, -1, |items| match items {
|
||||
Items::Names { names, .. } => Some(names.items.len() as i32),
|
||||
Items::Query { .. } => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether some names didn't fit in the server's answer: 1 or 0, -1 if it
|
||||
/// isn't a names enumeration.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn BakaShrot_IsNamesListTruncated(enumeration: i64) -> isize {
|
||||
read(enumeration, -1, |items| match items {
|
||||
Items::Names { truncated, .. } => Some(bool_result(*truncated)),
|
||||
Items::Query { .. } => None,
|
||||
})
|
||||
}
|
||||
|
||||
// --- Queries -----------------------------------------------------------------
|
||||
|
||||
/// The server's `{"columns":[...],"rows":[[...],...]}`, each value a
|
||||
/// string or null.
|
||||
fn parse_query(json: &str) -> Option<Items> {
|
||||
let value: serde_json::Value = serde_json::from_str(json).ok()?;
|
||||
let columns = value
|
||||
.get("columns")?
|
||||
.as_array()?
|
||||
.iter()
|
||||
.map(|column| column.as_str().map(str::to_owned))
|
||||
.collect::<Option<Vec<_>>>()?;
|
||||
let rows = value
|
||||
.get("rows")?
|
||||
.as_array()?
|
||||
.iter()
|
||||
.map(|row| {
|
||||
row.as_array()?
|
||||
.iter()
|
||||
.map(|value| match value {
|
||||
serde_json::Value::Null => Some(None),
|
||||
serde_json::Value::String(text) => Some(Some(text.clone())),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Option<Vec<_>>>()
|
||||
})
|
||||
.collect::<Option<Vec<_>>>()?;
|
||||
Some(Items::Query {
|
||||
columns,
|
||||
rows: Cursor::new(rows),
|
||||
})
|
||||
}
|
||||
|
||||
unsafe fn enumerate_query<T: Text>(client: i64, sql: *const T::Unit) -> i64 {
|
||||
enumerate(client, |state| {
|
||||
let json = unsafe { fetch_query::<T>(state, sql)? };
|
||||
parse_query(&json)
|
||||
.ok_or_else(|| Error::new(ErrorCode::Internal, "the server's query result isn't one"))
|
||||
})
|
||||
}
|
||||
|
||||
/// Runs a query as `BakaShrot_Query()` does, into an enumeration: its
|
||||
/// handle, 0 on failure (`BakaShrot_GetLastError(client)`). Then
|
||||
/// `BakaShrot_GetQueryColumnCount()` and `GetQueryColumnName()`,
|
||||
/// `BakaShrot_NextQueryRow()` and `GetQueryValue()` / `IsQueryValueNull()`,
|
||||
/// and `BakaShrot_CloseEnum()`. Closed with its client by
|
||||
/// `BakaShrot_FreeClient()`.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_EnumerateQueryA(client: i64, sql: *const c_char) -> i64 {
|
||||
unsafe { enumerate_query::<Utf8>(client, sql.cast()) }
|
||||
}
|
||||
|
||||
/// The same as `BakaShrot_EnumerateQueryA`, in UTF-16.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_EnumerateQueryW(client: i64, sql: *const u16) -> i64 {
|
||||
unsafe { enumerate_query::<Utf16>(client, sql) }
|
||||
}
|
||||
|
||||
/// How many columns, -1 if it isn't a query enumeration.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn BakaShrot_GetQueryColumnCount(enumeration: i64) -> i32 {
|
||||
read(enumeration, -1, |items| match items {
|
||||
Items::Query { columns, .. } => Some(columns.len() as i32),
|
||||
Items::Names { .. } => None,
|
||||
})
|
||||
}
|
||||
|
||||
unsafe fn column_name<T: Text>(
|
||||
enumeration: i64,
|
||||
index: i32,
|
||||
buffer: *mut T::Unit,
|
||||
size: isize,
|
||||
) -> isize {
|
||||
read(enumeration, 0, |items| match items {
|
||||
Items::Query { columns, .. } => columns
|
||||
.get(column(index)?)
|
||||
.map(|name| unsafe { text::copy::<T>(name, buffer, size) }),
|
||||
Items::Names { .. } => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// A column's name (`index` 0 to the count - 1): the bytes it needs, 0 if
|
||||
/// there's no such column or it isn't a query enumeration.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_GetQueryColumnNameA(
|
||||
enumeration: i64,
|
||||
index: i32,
|
||||
buffer: *mut c_char,
|
||||
size: isize,
|
||||
) -> isize {
|
||||
unsafe { column_name::<Utf8>(enumeration, index, buffer.cast(), size) }
|
||||
}
|
||||
|
||||
/// The same as `BakaShrot_GetQueryColumnNameA`, in UTF-16.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_GetQueryColumnNameW(
|
||||
enumeration: i64,
|
||||
index: i32,
|
||||
buffer: *mut u16,
|
||||
size: isize,
|
||||
) -> isize {
|
||||
unsafe { column_name::<Utf16>(enumeration, index, buffer, size) }
|
||||
}
|
||||
|
||||
/// Moves to the next row (the first, the first time): 1, 0 if there are
|
||||
/// no more, -1 if it isn't a query enumeration.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn BakaShrot_NextQueryRow(enumeration: i64) -> isize {
|
||||
read(enumeration, -1, |items| match items {
|
||||
Items::Query { rows, .. } => Some(bool_result(rows.advance())),
|
||||
Items::Names { .. } => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The current row's value in a column: `None` without a row or column.
|
||||
fn value(items: &Items, index: i32) -> Option<&Option<String>> {
|
||||
match items {
|
||||
Items::Query { rows, .. } => rows.current()?.get(column(index)?),
|
||||
Items::Names { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn query_value<T: Text>(
|
||||
enumeration: i64,
|
||||
index: i32,
|
||||
buffer: *mut T::Unit,
|
||||
size: isize,
|
||||
) -> isize {
|
||||
read(enumeration, 0, |items| {
|
||||
value(items, index)?
|
||||
.as_deref()
|
||||
.map(|text| unsafe { text::copy::<T>(text, buffer, size) })
|
||||
})
|
||||
}
|
||||
|
||||
/// The current row's value in a column (`index` 0 to the count - 1): the
|
||||
/// bytes it needs, 0 if it's null (`BakaShrot_IsQueryValueNull()`), there's
|
||||
/// no current row or such column, or it isn't a query enumeration.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_GetQueryValueA(
|
||||
enumeration: i64,
|
||||
index: i32,
|
||||
buffer: *mut c_char,
|
||||
size: isize,
|
||||
) -> isize {
|
||||
unsafe { query_value::<Utf8>(enumeration, index, buffer.cast(), size) }
|
||||
}
|
||||
|
||||
/// The same as `BakaShrot_GetQueryValueA`, in UTF-16.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_GetQueryValueW(
|
||||
enumeration: i64,
|
||||
index: i32,
|
||||
buffer: *mut u16,
|
||||
size: isize,
|
||||
) -> isize {
|
||||
unsafe { query_value::<Utf16>(enumeration, index, buffer, size) }
|
||||
}
|
||||
|
||||
/// Whether the current row's value in a column is null: 1 or 0, -1 if
|
||||
/// there's no current row or such column, or it isn't a query enumeration.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn BakaShrot_IsQueryValueNull(enumeration: i64, index: i32) -> isize {
|
||||
read(enumeration, -1, |items| {
|
||||
value(items, index).map(|value| bool_result(value.is_none()))
|
||||
})
|
||||
}
|
||||
@@ -9,6 +9,11 @@
|
||||
//! first argument of every other export. Each has its own connection,
|
||||
//! answers and errors; different clients can be used from different
|
||||
//! threads at once.
|
||||
//! - **Enumerations** (`BakaShrot_EnumerateNames()`, `EnumerateQuery()`):
|
||||
//! an answer kept whole, read with `Next...()` (before the first item
|
||||
//! at first) and its getters, closed with `BakaShrot_CloseEnum()` or
|
||||
//! with their client by `BakaShrot_FreeClient()`. Their handles are
|
||||
//! numbered with the clients', so one is never the other's.
|
||||
//! - **`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`
|
||||
@@ -27,11 +32,13 @@
|
||||
|
||||
#![allow(unsafe_code, non_snake_case, clippy::missing_safety_doc)]
|
||||
|
||||
mod enumerations;
|
||||
pub use enumerations::*;
|
||||
mod text;
|
||||
|
||||
use bakashrot_client::{Client, Error, Settings};
|
||||
use bakashrot_proto::ErrorCode;
|
||||
use bakashrot_proto::packets::{MessageEntry, NameKind};
|
||||
use bakashrot_proto::packets::{MessageEntry, NameKind, NamesList};
|
||||
use std::collections::BTreeMap;
|
||||
use std::ffi::{c_char, c_void};
|
||||
use std::fs::File;
|
||||
@@ -43,9 +50,28 @@ use text::{Text, Utf8, Utf16};
|
||||
|
||||
type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
/// The next handle, and the clients by handle. A call holds its client's
|
||||
/// The clients and enumerations by handle. A call holds its client's
|
||||
/// `Arc`, so a client freed during a call goes when the call ends.
|
||||
static CLIENTS: Mutex<(i64, BTreeMap<i64, Shared>)> = Mutex::new((1, BTreeMap::new()));
|
||||
static HANDLES: Mutex<Handles> = Mutex::new(Handles {
|
||||
next: 1,
|
||||
clients: BTreeMap::new(),
|
||||
enumerations: BTreeMap::new(),
|
||||
});
|
||||
|
||||
struct Handles {
|
||||
/// The next handle, of a client or an enumeration: never reused.
|
||||
next: i64,
|
||||
clients: BTreeMap<i64, Shared>,
|
||||
/// Freed with their client. Only ever copied from, under this lock.
|
||||
enumerations: BTreeMap<i64, enumerations::Enumeration>,
|
||||
}
|
||||
|
||||
impl Handles {
|
||||
fn take(&mut self) -> i64 {
|
||||
self.next += 1;
|
||||
self.next - 1
|
||||
}
|
||||
}
|
||||
|
||||
type Shared = Arc<Mutex<State>>;
|
||||
|
||||
@@ -66,7 +92,7 @@ struct State {
|
||||
messages: Vec<MessageEntry>,
|
||||
selected: usize,
|
||||
more: bool,
|
||||
/// The last `ListTopics` / `ListNodes`, as JSON.
|
||||
/// The last `ListNames`, as JSON.
|
||||
names: String,
|
||||
/// The last `Query`'s result.
|
||||
query: String,
|
||||
@@ -135,7 +161,7 @@ fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
|
||||
}
|
||||
|
||||
fn find(client: i64) -> Option<Shared> {
|
||||
lock(&CLIENTS).1.get(&client).cloned()
|
||||
lock(&HANDLES).clients.get(&client).cloned()
|
||||
}
|
||||
|
||||
/// Runs a call that can fail on a client: its last error reset, then set
|
||||
@@ -186,8 +212,22 @@ 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)")))
|
||||
/// A string argument that must be there: `InvalidArgument` for a null
|
||||
/// pointer.
|
||||
unsafe fn required<T: Text>(pointer: *const T::Unit, what: &str) -> Result<String> {
|
||||
unsafe { text::read::<T>(pointer, what)? }
|
||||
.ok_or_else(|| invalid(format!("no {what} (a null pointer)")))
|
||||
}
|
||||
|
||||
/// Settings change only before connecting.
|
||||
fn not_connected(state: &State) -> Result<()> {
|
||||
match state.client {
|
||||
Some(_) => Err(Error::new(
|
||||
ErrorCode::AlreadyConnected,
|
||||
"already connected: disconnect first",
|
||||
)),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn bool_result(ok: bool) -> isize {
|
||||
@@ -200,19 +240,27 @@ fn bool_result(ok: bool) -> isize {
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn BakaShrot_CreateClient() -> i64 {
|
||||
let made = catch_unwind(|| {
|
||||
let (next, clients) = &mut *lock(&CLIENTS);
|
||||
clients.insert(*next, Arc::new(Mutex::new(State::new())));
|
||||
*next += 1;
|
||||
*next - 1
|
||||
let handles = &mut *lock(&HANDLES);
|
||||
let client = handles.take();
|
||||
handles
|
||||
.clients
|
||||
.insert(client, Arc::new(Mutex::new(State::new())));
|
||||
client
|
||||
});
|
||||
made.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Frees a client and closes its connection (once a call on it in another
|
||||
/// thread ends): 1, or 0 if it wasn't one.
|
||||
/// thread ends), its enumerations closed too: 1, or 0 if it wasn't one.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn BakaShrot_FreeClient(client: i64) -> isize {
|
||||
let freed = catch_unwind(|| lock(&CLIENTS).1.remove(&client).is_some());
|
||||
let freed = catch_unwind(|| {
|
||||
let handles = &mut *lock(&HANDLES);
|
||||
handles
|
||||
.enumerations
|
||||
.retain(|_, enumeration| enumeration.client != client);
|
||||
handles.clients.remove(&client).is_some()
|
||||
});
|
||||
bool_result(freed.unwrap_or(false))
|
||||
}
|
||||
|
||||
@@ -289,12 +337,7 @@ unsafe fn set<T: Text>(
|
||||
slot: fn(&mut State) -> &mut Option<String>,
|
||||
) -> isize {
|
||||
call(client, 0, |state| {
|
||||
if state.client.is_some() {
|
||||
return Err(Error::new(
|
||||
ErrorCode::AlreadyConnected,
|
||||
"already connected: disconnect first",
|
||||
));
|
||||
}
|
||||
not_connected(state)?;
|
||||
let value = unsafe { text::read::<T>(value, what)? };
|
||||
*slot(state) = pem_or_file(value, what, optional)?;
|
||||
Ok(1)
|
||||
@@ -391,13 +434,8 @@ pub unsafe extern "C" fn BakaShrot_SetCrlW(client: i64, crl: *const u16) -> isiz
|
||||
|
||||
unsafe fn connect<T: Text>(client: i64, host: *const T::Unit, port: i32) -> isize {
|
||||
call(client, 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")?;
|
||||
not_connected(state)?;
|
||||
let host = unsafe { required::<T>(host, "host")? };
|
||||
let port = u16::try_from(port)
|
||||
.ok()
|
||||
.filter(|port| *port != 0)
|
||||
@@ -466,6 +504,10 @@ pub extern "C" fn BakaShrot_Disconnect(client: i64) -> isize {
|
||||
})
|
||||
}
|
||||
|
||||
fn node(state: &State) -> &str {
|
||||
state.client.as_ref().map_or("", Client::node)
|
||||
}
|
||||
|
||||
/// The node this client is, as the server said when connecting: its
|
||||
/// certificate's name. Empty when not connected.
|
||||
#[unsafe(no_mangle)]
|
||||
@@ -474,21 +516,13 @@ pub unsafe extern "C" fn BakaShrot_GetNodeA(
|
||||
buffer: *mut c_char,
|
||||
size: isize,
|
||||
) -> isize {
|
||||
unsafe {
|
||||
get_text::<Utf8>(client, buffer.cast(), size, |state| {
|
||||
state.client.as_ref().map_or("", Client::node)
|
||||
})
|
||||
}
|
||||
unsafe { get_text::<Utf8>(client, buffer.cast(), size, node) }
|
||||
}
|
||||
|
||||
/// The same as `BakaShrot_GetNodeA`, in UTF-16.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_GetNodeW(client: i64, buffer: *mut u16, size: isize) -> isize {
|
||||
unsafe {
|
||||
get_text::<Utf16>(client, buffer, size, |state| {
|
||||
state.client.as_ref().map_or("", Client::node)
|
||||
})
|
||||
}
|
||||
unsafe { get_text::<Utf16>(client, buffer, size, node) }
|
||||
}
|
||||
|
||||
// --- Pushing -----------------------------------------------------------------
|
||||
@@ -499,7 +533,7 @@ 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 topic = unsafe { required::<T>(topic, "topic")? };
|
||||
let data = unsafe { text::read::<T>(data, "the message")? }.unwrap_or_default();
|
||||
Ok((topic, data))
|
||||
}
|
||||
@@ -541,8 +575,8 @@ 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")?;
|
||||
let topic = unsafe { required::<T>(topic, "topic")? };
|
||||
let node = unsafe { required::<T>(node, "node")? };
|
||||
Ok((topic, node))
|
||||
}
|
||||
|
||||
@@ -772,11 +806,35 @@ pub unsafe extern "C" fn BakaShrot_GetMessageNodeW(
|
||||
|
||||
// --- Names -------------------------------------------------------------------
|
||||
|
||||
fn list(client: i64, kind: NameKind) -> i32 {
|
||||
/// Asks for a list of names: `kind` 1 topics, 2 nodes, as on the wire;
|
||||
/// the filters null for any.
|
||||
unsafe fn fetch_names<T: Text>(
|
||||
state: &mut State,
|
||||
kind: i32,
|
||||
topics: *const T::Unit,
|
||||
nodes: *const T::Unit,
|
||||
) -> Result<NamesList> {
|
||||
let kind = u8::try_from(kind)
|
||||
.ok()
|
||||
.and_then(|kind| NameKind::try_from(kind).ok())
|
||||
.ok_or_else(|| invalid(format!("a kind of {kind}: 1 (topics) or 2 (nodes)")))?;
|
||||
let topics = unsafe { text::read::<T>(topics, "topics")? };
|
||||
let nodes = unsafe { text::read::<T>(nodes, "nodes")? };
|
||||
state
|
||||
.client()?
|
||||
.list_names(kind, topics.as_deref(), nodes.as_deref())
|
||||
}
|
||||
|
||||
unsafe fn list<T: Text>(
|
||||
client: i64,
|
||||
kind: i32,
|
||||
topics: *const T::Unit,
|
||||
nodes: *const T::Unit,
|
||||
) -> i32 {
|
||||
call(client, -1, |state| {
|
||||
state.names.clear();
|
||||
let list = state.client()?.list_names(kind)?;
|
||||
let kind = match kind {
|
||||
let list = unsafe { fetch_names::<T>(state, kind, topics, nodes)? };
|
||||
let kind = match list.kind {
|
||||
NameKind::Topic => "topic",
|
||||
NameKind::Node => "node",
|
||||
};
|
||||
@@ -791,27 +849,42 @@ fn list(client: i64, kind: NameKind) -> i32 {
|
||||
})
|
||||
}
|
||||
|
||||
/// Lists the topics with messages that this client may push to or read
|
||||
/// (every one if its roles have `list_topics` or `query`): how many, -1 on
|
||||
/// failure. Then `BakaShrot_GetNamesList()`.
|
||||
/// Lists topics (`kind` 1) or nodes (`kind` 2): the topics with messages
|
||||
/// that this client may push to or read (every one if its roles have
|
||||
/// `list_topics` or `query`), the nodes with messages in the topics it may
|
||||
/// read (every one with `list_nodes` or `query`). Only those of the topic
|
||||
/// and node pairs that `topics` and `nodes` match: each a name or a
|
||||
/// pattern (`sensors.*`), null for any. Every topic: 1, null, null; the
|
||||
/// topics a node pushed to: 1, null, the node; the nodes that pushed to a
|
||||
/// topic: 2, the topic, null. How many, -1 on failure. Then
|
||||
/// `BakaShrot_GetNamesListAsJson()`, or `BakaShrot_EnumerateNames()`
|
||||
/// instead.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn BakaShrot_ListTopics(client: i64) -> i32 {
|
||||
list(client, NameKind::Topic)
|
||||
pub unsafe extern "C" fn BakaShrot_ListNamesA(
|
||||
client: i64,
|
||||
kind: i32,
|
||||
topics: *const c_char,
|
||||
nodes: *const c_char,
|
||||
) -> i32 {
|
||||
unsafe { list::<Utf8>(client, kind, topics.cast(), nodes.cast()) }
|
||||
}
|
||||
|
||||
/// Lists the nodes with messages in the topics this client may read (every
|
||||
/// one if its roles have `list_nodes` or `query`): how many, -1 on failure. Then
|
||||
/// `BakaShrot_GetNamesList()`.
|
||||
/// The same as `BakaShrot_ListNamesA`, in UTF-16.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn BakaShrot_ListNodes(client: i64) -> i32 {
|
||||
list(client, NameKind::Node)
|
||||
pub unsafe extern "C" fn BakaShrot_ListNamesW(
|
||||
client: i64,
|
||||
kind: i32,
|
||||
topics: *const u16,
|
||||
nodes: *const u16,
|
||||
) -> i32 {
|
||||
unsafe { list::<Utf16>(client, kind, topics, nodes) }
|
||||
}
|
||||
|
||||
/// 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(
|
||||
pub unsafe extern "C" fn BakaShrot_GetNamesListAsJsonA(
|
||||
client: i64,
|
||||
buffer: *mut c_char,
|
||||
size: isize,
|
||||
@@ -819,9 +892,9 @@ pub unsafe extern "C" fn BakaShrot_GetNamesListA(
|
||||
unsafe { get_text::<Utf8>(client, buffer.cast(), size, |state| &state.names) }
|
||||
}
|
||||
|
||||
/// The same as `BakaShrot_GetNamesListA`, in UTF-16.
|
||||
/// The same as `BakaShrot_GetNamesListAsJsonA`, in UTF-16.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_GetNamesListW(
|
||||
pub unsafe extern "C" fn BakaShrot_GetNamesListAsJsonW(
|
||||
client: i64,
|
||||
buffer: *mut u16,
|
||||
size: isize,
|
||||
@@ -831,17 +904,23 @@ pub unsafe extern "C" fn BakaShrot_GetNamesListW(
|
||||
|
||||
// --- Queries -----------------------------------------------------------------
|
||||
|
||||
/// Runs a query: the server's JSON.
|
||||
unsafe fn fetch_query<T: Text>(state: &mut State, sql: *const T::Unit) -> Result<String> {
|
||||
let sql = unsafe { required::<T>(sql, "query")? };
|
||||
state.client()?.query(&sql)
|
||||
}
|
||||
|
||||
unsafe fn query<T: Text>(client: i64, sql: *const T::Unit) -> isize {
|
||||
call(client, 0, |state| {
|
||||
state.query.clear();
|
||||
let sql = required(unsafe { text::read::<T>(sql, "query")? }, "query")?;
|
||||
state.query = state.client()?.query(&sql)?;
|
||||
state.query = unsafe { fetch_query::<T>(state, sql)? };
|
||||
Ok(1)
|
||||
})
|
||||
}
|
||||
|
||||
/// Runs read-only SQL on the server (one SELECT or WITH), if this client
|
||||
/// may query. Then `BakaShrot_GetQueryResult()`.
|
||||
/// may query. Then `BakaShrot_GetQueryResultAsJson()`, or
|
||||
/// `BakaShrot_EnumerateQuery()` instead.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_QueryA(client: i64, sql: *const c_char) -> isize {
|
||||
unsafe { query::<Utf8>(client, sql.cast()) }
|
||||
@@ -856,7 +935,7 @@ pub unsafe extern "C" fn BakaShrot_QueryW(client: i64, sql: *const u16) -> isize
|
||||
/// 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(
|
||||
pub unsafe extern "C" fn BakaShrot_GetQueryResultAsJsonA(
|
||||
client: i64,
|
||||
buffer: *mut c_char,
|
||||
size: isize,
|
||||
@@ -864,9 +943,9 @@ pub unsafe extern "C" fn BakaShrot_GetQueryResultA(
|
||||
unsafe { get_text::<Utf8>(client, buffer.cast(), size, |state| &state.query) }
|
||||
}
|
||||
|
||||
/// The same as `BakaShrot_GetQueryResultA`, in UTF-16.
|
||||
/// The same as `BakaShrot_GetQueryResultAsJsonA`, in UTF-16.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn BakaShrot_GetQueryResultW(
|
||||
pub unsafe extern "C" fn BakaShrot_GetQueryResultAsJsonW(
|
||||
client: i64,
|
||||
buffer: *mut u16,
|
||||
size: isize,
|
||||
@@ -889,7 +968,7 @@ unsafe fn push_with_file<T: Text>(
|
||||
) -> i64 {
|
||||
call(client, -1, |state| {
|
||||
let (topic, data) = unsafe { topic_and_data::<T>(topic, data)? };
|
||||
let path = required(unsafe { text::read::<T>(path, "the file")? }, "file")?;
|
||||
let path = unsafe { required::<T>(path, "file")? };
|
||||
let mut file = File::open(&path)
|
||||
.map_err(|error| Error::new(ErrorCode::FileError, format!("{path}: {error}")))?;
|
||||
let id = state
|
||||
@@ -983,7 +1062,7 @@ unsafe fn save<T: Text>(
|
||||
) -> i64 {
|
||||
call(client, -1, |state| {
|
||||
let (topic, node) = unsafe { topic_and_node::<T>(topic, node)? };
|
||||
let path = required(unsafe { text::read::<T>(path, "the file")? }, "file")?;
|
||||
let path = unsafe { required::<T>(path, "file")? };
|
||||
let size =
|
||||
state
|
||||
.client()?
|
||||
|
||||
@@ -242,23 +242,45 @@ fn exports() {
|
||||
|
||||
// Names, queries.
|
||||
// Topics: those with messages (nothing in `secret` yet).
|
||||
assert_eq!(BakaShrot_ListTopics(client), 1);
|
||||
let null = std::ptr::null();
|
||||
assert_eq!(BakaShrot_ListNamesW(client, 1, null, null), 1);
|
||||
assert_eq!(
|
||||
get_w(client, BakaShrot_GetNamesListW),
|
||||
get_w(client, BakaShrot_GetNamesListAsJsonW),
|
||||
r#"{"kind":"topic","names":["logs"],"truncated":false}"#
|
||||
);
|
||||
assert_eq!(BakaShrot_ListNodes(client), 1);
|
||||
assert_eq!(BakaShrot_ListNamesW(client, 2, null, null), 1);
|
||||
// Filtered: the topics a node pushed to, the nodes of a topic.
|
||||
assert_eq!(
|
||||
BakaShrot_ListNamesW(client, 1, null, w("KITCHEN").as_ptr()),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
BakaShrot_ListNamesA(client, 2, a("l*").as_ptr(), null.cast()),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
get_w(client, BakaShrot_GetNamesListAsJsonW),
|
||||
r#"{"kind":"node","names":["kitchen"],"truncated":false}"#
|
||||
);
|
||||
assert_eq!(
|
||||
BakaShrot_ListNamesW(client, 1, null, w("nobody").as_ptr()),
|
||||
0
|
||||
);
|
||||
assert_eq!(BakaShrot_ListNamesW(client, 3, null, null), -1);
|
||||
assert_eq!(error(client).0, code(ErrorCode::InvalidArgument));
|
||||
assert_eq!(BakaShrot_ListNamesW(client, 1, w("a b").as_ptr(), null), -1);
|
||||
assert_eq!(error(client).0, code(ErrorCode::InvalidArgument));
|
||||
assert_eq!(
|
||||
BakaShrot_QueryW(client, w("SELECT COUNT(*) AS n FROM data").as_ptr()),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
get_w(client, BakaShrot_GetQueryResultW),
|
||||
get_w(client, BakaShrot_GetQueryResultAsJsonW),
|
||||
r#"{"columns":["n"],"rows":[["3"]]}"#
|
||||
);
|
||||
assert_eq!(BakaShrot_QueryW(client, w("SELECT nope").as_ptr()), 0);
|
||||
assert_eq!(error(client).0, code(ErrorCode::QueryFailed));
|
||||
assert_eq!(get_w(client, BakaShrot_GetQueryResultW), "");
|
||||
assert_eq!(get_w(client, BakaShrot_GetQueryResultAsJsonW), "");
|
||||
|
||||
// Attachments: from a file or memory, saved or loaded back.
|
||||
let (logs, kitchen) = (w("logs"), w("kitchen"));
|
||||
@@ -564,3 +586,120 @@ fn clients() {
|
||||
assert!(reads >= 1);
|
||||
assert_eq!(failed, code(ErrorCode::InvalidArgument));
|
||||
}
|
||||
|
||||
/// An enumeration's string at an index: asks for the size, then copies.
|
||||
fn get_at(
|
||||
enumeration: i64,
|
||||
index: i32,
|
||||
getter: unsafe extern "C" fn(i64, i32, *mut u16, isize) -> isize,
|
||||
) -> String {
|
||||
let size = unsafe { getter(enumeration, index, std::ptr::null_mut(), 0) };
|
||||
if size == 0 {
|
||||
return String::new();
|
||||
}
|
||||
let mut buffer = vec![0u16; size as usize / 2];
|
||||
unsafe { getter(enumeration, index, buffer.as_mut_ptr(), size) };
|
||||
String::from_utf16(&buffer[..buffer.len() - 1]).unwrap()
|
||||
}
|
||||
|
||||
/// Every name of an enumeration, `NextName` until it says no more.
|
||||
fn names_of(enumeration: i64) -> Vec<String> {
|
||||
let mut names = Vec::new();
|
||||
while BakaShrot_NextName(enumeration) == 1 {
|
||||
names.push(get_w(enumeration, BakaShrot_GetEnumNameW));
|
||||
}
|
||||
names
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enumerations() {
|
||||
let running = common::Running::start("enumerations");
|
||||
running.issue("kitchen", &["home"]);
|
||||
let client = connected(&running, "kitchen");
|
||||
let null = std::ptr::null();
|
||||
unsafe {
|
||||
for (topic, data) in [("logs", "{}"), ("secret", "{}"), ("logs", "{}")] {
|
||||
assert!(BakaShrot_PushMessageToW(client, w(topic).as_ptr(), w(data).as_ptr()) > 0);
|
||||
}
|
||||
|
||||
// Names: before the first at first, then each, then no more.
|
||||
let topics = BakaShrot_EnumerateNamesW(client, 1, null, w("kitchen").as_ptr());
|
||||
assert!(topics > client, "numbered with the clients");
|
||||
assert_eq!(BakaShrot_GetNameCount(topics), 2);
|
||||
assert_eq!(BakaShrot_IsNamesListTruncated(topics), 0);
|
||||
assert_eq!(
|
||||
get_w(topics, BakaShrot_GetEnumNameW),
|
||||
"",
|
||||
"before the first"
|
||||
);
|
||||
assert_eq!(names_of(topics), ["logs", "secret"]);
|
||||
assert_eq!(BakaShrot_NextName(topics), 0, "still none");
|
||||
assert_eq!(get_w(topics, BakaShrot_GetEnumNameW), "");
|
||||
// Several at once, each its own; the client's calls don't change them.
|
||||
let nodes = BakaShrot_EnumerateNamesA(client, 2, a("s*").as_ptr(), null.cast());
|
||||
let none = BakaShrot_EnumerateNamesW(client, 2, w("nothing").as_ptr(), null);
|
||||
assert_eq!(BakaShrot_ListNamesW(client, 1, null, null), 2);
|
||||
assert_eq!(names_of(nodes), ["kitchen"]);
|
||||
assert_eq!(BakaShrot_GetNameCount(none), 0);
|
||||
assert_eq!(BakaShrot_NextName(none), 0);
|
||||
// A failure: 0, the client's error.
|
||||
assert_eq!(BakaShrot_EnumerateNamesW(client, 3, null, null), 0);
|
||||
assert_eq!(error(client).0, code(ErrorCode::InvalidArgument));
|
||||
|
||||
// Queries: columns, rows, nulls.
|
||||
let sql = w(
|
||||
"SELECT topic, CASE WHEN message_id = 1 THEN NULL ELSE message_id END AS id \
|
||||
FROM messages ORDER BY topic, message_id",
|
||||
);
|
||||
let query = BakaShrot_EnumerateQueryW(client, sql.as_ptr());
|
||||
assert!(query > 0, "{:?}", error(client));
|
||||
assert_eq!(BakaShrot_GetQueryColumnCount(query), 2);
|
||||
assert_eq!(get_at(query, 0, BakaShrot_GetQueryColumnNameW), "topic");
|
||||
assert_eq!(get_at(query, 1, BakaShrot_GetQueryColumnNameW), "id");
|
||||
assert_eq!(get_at(query, 2, BakaShrot_GetQueryColumnNameW), "");
|
||||
assert_eq!(BakaShrot_IsQueryValueNull(query, 0), -1, "no row yet");
|
||||
let mut rows = Vec::new();
|
||||
while BakaShrot_NextQueryRow(query) == 1 {
|
||||
let id = match BakaShrot_IsQueryValueNull(query, 1) {
|
||||
1 => None,
|
||||
0 => Some(get_at(query, 1, BakaShrot_GetQueryValueW)),
|
||||
other => panic!("{other}"),
|
||||
};
|
||||
rows.push((get_at(query, 0, BakaShrot_GetQueryValueW), id));
|
||||
}
|
||||
let row = |topic: &str, id: Option<&str>| (topic.to_owned(), id.map(str::to_owned));
|
||||
assert_eq!(
|
||||
rows,
|
||||
[
|
||||
row("logs", None),
|
||||
row("logs", Some("2")),
|
||||
row("secret", None)
|
||||
]
|
||||
);
|
||||
assert_eq!(BakaShrot_IsQueryValueNull(query, 0), -1, "past the last");
|
||||
assert_eq!(
|
||||
BakaShrot_EnumerateQueryW(client, w("SELECT nope").as_ptr()),
|
||||
0
|
||||
);
|
||||
assert_eq!(error(client).0, code(ErrorCode::QueryFailed));
|
||||
|
||||
// Of the other kind, a client's, made up: refused, never a crash.
|
||||
assert_eq!(BakaShrot_NextName(query), -1);
|
||||
assert_eq!(BakaShrot_NextQueryRow(nodes), -1);
|
||||
assert_eq!(BakaShrot_GetQueryColumnCount(nodes), -1);
|
||||
assert_eq!(BakaShrot_NextName(client), -1);
|
||||
assert_eq!(BakaShrot_NextName(99_999), -1);
|
||||
assert_eq!(get_w(99_999, BakaShrot_GetEnumNameW), "");
|
||||
assert_eq!(BakaShrot_CloseEnum(client), 0, "a client isn't one");
|
||||
assert_eq!(BakaShrot_FreeClient(topics), 0, "nor the other way");
|
||||
|
||||
// Closed: refused after. Its client freed: all of its closed.
|
||||
assert_eq!(BakaShrot_CloseEnum(topics), 1);
|
||||
assert_eq!(BakaShrot_CloseEnum(topics), 0);
|
||||
assert_eq!(BakaShrot_GetNameCount(topics), -1);
|
||||
assert_eq!(BakaShrot_FreeClient(client), 1);
|
||||
for enumeration in [nodes, none, query] {
|
||||
assert_eq!(BakaShrot_CloseEnum(enumeration), 0, "{enumeration}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ use bakashrot_proto::limits::{
|
||||
ALPN, ATTACHMENT_PART_SIZE, MAX_ATTACHMENT_SIZE, MAX_MESSAGE_ID, MAX_MESSAGE_SIZE,
|
||||
MAX_MESSAGES_PER_PACKET, MAX_PACKET_SIZE,
|
||||
};
|
||||
use bakashrot_proto::names::is_valid_name;
|
||||
use bakashrot_proto::names::{is_valid_name, is_valid_name_or_pattern};
|
||||
use bakashrot_proto::packets::{
|
||||
Attachment, AttachmentPart, GetAttachment, GetMessages, ListNames, Messages, NameKind,
|
||||
NamesList, PushMessage, Query,
|
||||
@@ -245,12 +245,9 @@ impl Client {
|
||||
sha256.update(&buffer[..read]);
|
||||
size += read as u64;
|
||||
}
|
||||
if !(1..=MAX_ATTACHMENT_SIZE).contains(&size) {
|
||||
return Err(Error::new(
|
||||
ErrorCode::InvalidArgument,
|
||||
format!("an attachment of {size} bytes: 1 to {MAX_ATTACHMENT_SIZE}"),
|
||||
));
|
||||
}
|
||||
require((1..=MAX_ATTACHMENT_SIZE).contains(&size), || {
|
||||
format!("an attachment of {size} bytes: 1 to {MAX_ATTACHMENT_SIZE}")
|
||||
})?;
|
||||
source.rewind().map_err(file_error)?;
|
||||
let mut digest = [0; 32];
|
||||
digest.copy_from_slice(sha256.finish().as_ref());
|
||||
@@ -297,12 +294,9 @@ impl Client {
|
||||
) -> Result<u64> {
|
||||
check_name(topic, "topic")?;
|
||||
check_name(node, "node")?;
|
||||
if !(1..=MAX_MESSAGE_ID).contains(&message_id) {
|
||||
return Err(Error::new(
|
||||
ErrorCode::InvalidArgument,
|
||||
format!("message {message_id}: 1 to {MAX_MESSAGE_ID}"),
|
||||
));
|
||||
}
|
||||
require((1..=MAX_MESSAGE_ID).contains(&message_id), || {
|
||||
format!("message {message_id}: 1 to {MAX_MESSAGE_ID}")
|
||||
})?;
|
||||
let get = GetAttachment {
|
||||
topic: topic.to_owned(),
|
||||
node: node.to_owned(),
|
||||
@@ -389,18 +383,12 @@ impl Client {
|
||||
) -> Result<Messages> {
|
||||
check_name(topic, "topic")?;
|
||||
check_name(node, "node")?;
|
||||
if !(1..=MAX_MESSAGES_PER_PACKET).contains(&limit) {
|
||||
return Err(Error::new(
|
||||
ErrorCode::InvalidArgument,
|
||||
format!("a limit of {limit}: 1 to {MAX_MESSAGES_PER_PACKET}"),
|
||||
));
|
||||
}
|
||||
if after.is_some_and(|after| after > MAX_MESSAGE_ID) {
|
||||
return Err(Error::new(
|
||||
ErrorCode::InvalidArgument,
|
||||
format!("after {}: {MAX_MESSAGE_ID} at most", after.unwrap_or(0)),
|
||||
));
|
||||
}
|
||||
require((1..=MAX_MESSAGES_PER_PACKET).contains(&limit), || {
|
||||
format!("a limit of {limit}: 1 to {MAX_MESSAGES_PER_PACKET}")
|
||||
})?;
|
||||
require(after.is_none_or(|after| after <= MAX_MESSAGE_ID), || {
|
||||
format!("after {}: {MAX_MESSAGE_ID} at most", after.unwrap_or(0))
|
||||
})?;
|
||||
let get = GetMessages {
|
||||
topic: topic.to_owned(),
|
||||
node: node.to_owned(),
|
||||
@@ -415,10 +403,29 @@ impl Client {
|
||||
|
||||
/// The topics with messages that this client may push to or read, or
|
||||
/// the nodes with messages in the topics it may read; every one if its
|
||||
/// roles have `list_topics` / `list_nodes`, or `query`. `truncated` if
|
||||
/// some didn't fit.
|
||||
pub fn list_names(&mut self, kind: NameKind) -> Result<NamesList> {
|
||||
match self.request(ListNames { kind }.into())? {
|
||||
/// roles have `list_topics` / `list_nodes`, or `query`. `topics` and
|
||||
/// `nodes` (a name or a pattern, `None` for any) keep those of the
|
||||
/// topic and node pairs they match: the topics a node pushed to, the
|
||||
/// nodes that pushed to a topic. `truncated` if some didn't fit.
|
||||
pub fn list_names(
|
||||
&mut self,
|
||||
kind: NameKind,
|
||||
topics: Option<&str>,
|
||||
nodes: Option<&str>,
|
||||
) -> Result<NamesList> {
|
||||
for (filter, what) in [(topics, "topic"), (nodes, "node")] {
|
||||
if let Some(filter) = filter {
|
||||
require(is_valid_name_or_pattern(filter), || {
|
||||
format!("'{filter}' isn't a {what} name or pattern")
|
||||
})?;
|
||||
}
|
||||
}
|
||||
let list = ListNames {
|
||||
kind,
|
||||
topics: topics.map(str::to_owned),
|
||||
nodes: nodes.map(str::to_owned),
|
||||
};
|
||||
match self.request(list.into())? {
|
||||
Packet::NamesList(names) => Ok(names),
|
||||
other => Err(unexpected(&other)),
|
||||
}
|
||||
@@ -511,26 +518,25 @@ fn lost(error: io::Error) -> Error {
|
||||
}
|
||||
}
|
||||
|
||||
fn check_name(name: &str, what: &str) -> Result<()> {
|
||||
if is_valid_name(name) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::new(
|
||||
ErrorCode::InvalidArgument,
|
||||
format!("'{name}' isn't a {what} name"),
|
||||
))
|
||||
/// An argument checked before sending: `InvalidArgument`, saying `why`,
|
||||
/// if it isn't `ok`.
|
||||
fn require(ok: bool, why: impl FnOnce() -> String) -> Result<()> {
|
||||
match ok {
|
||||
true => Ok(()),
|
||||
false => Err(Error::new(ErrorCode::InvalidArgument, why())),
|
||||
}
|
||||
}
|
||||
|
||||
fn check_name(name: &str, what: &str) -> Result<()> {
|
||||
require(is_valid_name(name), || {
|
||||
format!("'{name}' isn't a {what} name")
|
||||
})
|
||||
}
|
||||
|
||||
fn check_size(text: &str, what: &str) -> Result<()> {
|
||||
if text.len() <= MAX_MESSAGE_SIZE {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::new(
|
||||
ErrorCode::InvalidArgument,
|
||||
format!("{what} of {} bytes: {MAX_MESSAGE_SIZE} at most", text.len()),
|
||||
))
|
||||
}
|
||||
require(text.len() <= MAX_MESSAGE_SIZE, || {
|
||||
format!("{what} of {} bytes: {MAX_MESSAGE_SIZE} at most", text.len())
|
||||
})
|
||||
}
|
||||
|
||||
fn file_error(error: io::Error) -> Error {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Roles, and what a certificate's roles allow together.
|
||||
|
||||
use crate::values::check_names;
|
||||
use bakashrot_proto::names::{names_equal, pattern_matches};
|
||||
use bakashrot_proto::names::{name_matches, names_equal};
|
||||
use serde::Deserialize;
|
||||
|
||||
/// Topic or node names and patterns (`sensors.*`, `*` for all), none twice.
|
||||
@@ -27,9 +27,7 @@ impl NameList {
|
||||
/// Whether `name` is in it: one of its names, or matched by one of its
|
||||
/// patterns (without case).
|
||||
pub fn matches(&self, name: &str) -> bool {
|
||||
self.0
|
||||
.iter()
|
||||
.any(|entry| names_equal(entry, name) || pattern_matches(entry, name))
|
||||
self.0.iter().any(|entry| name_matches(entry, name))
|
||||
}
|
||||
|
||||
/// Whether it has nothing: matches nothing.
|
||||
@@ -117,15 +115,24 @@ impl Permissions {
|
||||
self.roles.iter().any(|role| role.query)
|
||||
}
|
||||
|
||||
/// Whether listing topics answers every one: `list_topics`, or
|
||||
/// `query` (which reads them all anyway).
|
||||
pub fn lists_every_topic(&self) -> bool {
|
||||
self.roles.iter().any(|role| role.list_topics || role.query)
|
||||
/// Whether listing names may show `topic`: one it may push to or
|
||||
/// read, any with `list_topics` or `query` (which reads them all
|
||||
/// anyway).
|
||||
pub fn may_list_topic(&self, topic: &str) -> bool {
|
||||
self.roles.iter().any(|role| {
|
||||
role.list_topics
|
||||
|| role.query
|
||||
|| role.push_topics.matches(topic)
|
||||
|| role.read_topics.matches(topic)
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether listing nodes answers every one: `list_nodes`, or `query`.
|
||||
pub fn lists_every_node(&self) -> bool {
|
||||
self.roles.iter().any(|role| role.list_nodes || role.query)
|
||||
/// Whether listing names may show the nodes with messages in `topic`:
|
||||
/// one it may read, any with `list_nodes` or `query`.
|
||||
pub fn may_list_nodes_of(&self, topic: &str) -> bool {
|
||||
self.roles
|
||||
.iter()
|
||||
.any(|role| role.list_nodes || role.query || role.read_topics.matches(topic))
|
||||
}
|
||||
|
||||
/// Whether `node`'s messages in `topic` are sent to it.
|
||||
|
||||
@@ -164,19 +164,23 @@ accept_nodes = ["garage"]
|
||||
assert!(both.can_read("Logs"));
|
||||
assert!(!both.can_read("sensors.garage"));
|
||||
assert!(!both.can_query());
|
||||
assert!(!both.lists_every_topic() && !both.lists_every_node());
|
||||
// Listing: the topics it may push to or read, the nodes of those it reads.
|
||||
assert!(both.may_list_topic("sensors.garage") && both.may_list_topic("logs"));
|
||||
assert!(!both.may_list_topic("other"));
|
||||
assert!(both.may_list_nodes_of("logs") && !both.may_list_nodes_of("sensors.garage"));
|
||||
let admin = config.permissions(&["admin"]).unwrap();
|
||||
assert!(admin.can_query());
|
||||
// A query reads them all anyway.
|
||||
assert!(admin.lists_every_topic() && admin.lists_every_node());
|
||||
// A query reads them all anyway; reading messages is still read_topics.
|
||||
assert!(admin.may_list_topic("other") && admin.may_list_nodes_of("other"));
|
||||
assert!(!admin.can_read("logs"));
|
||||
let listing = Config::parse(&with(
|
||||
"[roles.a]\nlist_topics = true\n[roles.b]\nlist_nodes = true\n",
|
||||
))
|
||||
.unwrap();
|
||||
let a = listing.permissions(&["a"]).unwrap();
|
||||
assert!(a.lists_every_topic() && !a.lists_every_node() && !a.can_query());
|
||||
assert!(a.may_list_topic("other") && !a.may_list_nodes_of("other") && !a.can_query());
|
||||
let b = listing.permissions(&["b", "a"]).unwrap();
|
||||
assert!(b.lists_every_topic() && b.lists_every_node());
|
||||
assert!(b.may_list_topic("other") && b.may_list_nodes_of("other"));
|
||||
|
||||
// Replication: each role's topics with that role's nodes, not mixed.
|
||||
let peer = config.permissions(&["peer", "backup"]).unwrap();
|
||||
@@ -338,6 +342,10 @@ fn refusals() {
|
||||
&with("[roles.r]\naccept_nodes = [\"x\", \"X\"]\n"),
|
||||
"'X' is given twice",
|
||||
),
|
||||
(
|
||||
&with("[roles.r]\nlist_topics = 1\n"),
|
||||
"invalid type: integer",
|
||||
),
|
||||
(&with("[roles.r]\nquery = 1\n"), "invalid type: integer"),
|
||||
(&with("[roles.site.reader]\n"), "unknown field `reader`"),
|
||||
];
|
||||
|
||||
@@ -169,11 +169,11 @@ mod tests {
|
||||
fn versions() {
|
||||
let mut stream = Vec::new();
|
||||
write_version(&mut stream).unwrap();
|
||||
assert_eq!(stream, [7, 0, 0, 0]);
|
||||
assert_eq!(stream, [8, 0, 0, 0]);
|
||||
let bytes = read_version(&mut &stream[..]).unwrap();
|
||||
assert_eq!(check_version(bytes), Ok(()));
|
||||
assert_eq!(check_version([6, 0, 0, 0]), Err(6));
|
||||
assert_eq!(check_version([8, 0, 0, 0]), Err(8));
|
||||
assert_eq!(check_version([7, 0, 0, 0]), Err(7));
|
||||
assert_eq!(check_version([9, 0, 0, 0]), Err(9));
|
||||
assert!(read_version(&mut &[7u8, 0][..]).is_err());
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! BakaShrot's protocol, version 7: what the server, the clients and the
|
||||
//! BakaShrot's protocol, version 8: what the server, the clients and the
|
||||
//! tools share, and nothing else.
|
||||
//!
|
||||
//! No I/O of its own beyond reading and writing frames on a stream it's
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
/// The protocol's version. Both ends must have the same: they tell each
|
||||
/// other first thing (`frame::write_version()`), and abandon the
|
||||
/// connection if it differs.
|
||||
pub const PROTOCOL_VERSION: u32 = 7;
|
||||
pub const PROTOCOL_VERSION: u32 = 8;
|
||||
|
||||
/// The ALPN protocol name both ends offer during the TLS handshake: what
|
||||
/// isn't BakaShrot doesn't get past it. Not versioned: the version is
|
||||
|
||||
@@ -45,6 +45,12 @@ pub fn is_valid_name_or_pattern(text: &str) -> bool {
|
||||
is_valid_name(text) || is_valid_pattern(text)
|
||||
}
|
||||
|
||||
/// Whether `name` is `filter` (a name) or matches it (a pattern), without
|
||||
/// case: what a list of names and patterns holds, one entry.
|
||||
pub fn name_matches(filter: &str, name: &str) -> bool {
|
||||
names_equal(filter, name) || pattern_matches(filter, name)
|
||||
}
|
||||
|
||||
/// Whether the name `name` matches `pattern` (without case). Anything that
|
||||
/// isn't a valid name never matches.
|
||||
pub fn pattern_matches(pattern: &str, name: &str) -> bool {
|
||||
@@ -144,4 +150,12 @@ mod tests {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filters() {
|
||||
assert!(name_matches("Logs", "logs"));
|
||||
assert!(name_matches("sensors.*", "Sensors.kitchen"));
|
||||
assert!(!name_matches("logs", "logs-1"));
|
||||
assert!(!name_matches("sensors.*", "sensor.x"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -201,16 +201,36 @@ impl TryFrom<u8> for NameKind {
|
||||
}
|
||||
}
|
||||
|
||||
/// Every topic or node the client may see.
|
||||
/// The topics or nodes the client may see, of the topic and node pairs
|
||||
/// with messages that the filters match: the topics a node pushed to, the
|
||||
/// nodes that pushed to a topic.
|
||||
///
|
||||
/// `[11, [kind]]`
|
||||
/// `[11, [kind, topics, nodes]]`
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ListNames {
|
||||
/// Topics or nodes.
|
||||
pub kind: NameKind,
|
||||
/// Only the pairs whose topic is this name or matches this pattern;
|
||||
/// nil for any.
|
||||
pub topics: Option<String>,
|
||||
/// Only the pairs whose node is this name or matches this pattern;
|
||||
/// nil for any.
|
||||
pub nodes: Option<String>,
|
||||
}
|
||||
|
||||
impl Check for ListNames {}
|
||||
impl Check for ListNames {
|
||||
fn check(&self) -> Result<(), DecodeError> {
|
||||
for (filter, field) in [
|
||||
(&self.topics, "ListNames.topics"),
|
||||
(&self.nodes, "ListNames.nodes"),
|
||||
] {
|
||||
if let Some(filter) = filter {
|
||||
rules::name_or_pattern(filter, field)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Topics or nodes.
|
||||
///
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Every packet of protocol 7.
|
||||
//! Every packet of protocol 8.
|
||||
//!
|
||||
//! A packet is a MessagePack array of two: its type, then its fields as an
|
||||
//! array, `[type, [field, field, ...]]`. Structs inside are arrays of their
|
||||
@@ -298,6 +298,15 @@ pub(crate) mod rules {
|
||||
require(names::is_valid_name(value), field, "must be a name")
|
||||
}
|
||||
|
||||
/// A topic or node name, or a pattern.
|
||||
pub fn name_or_pattern(value: &str, field: &'static str) -> Result<(), DecodeError> {
|
||||
require(
|
||||
names::is_valid_name_or_pattern(value),
|
||||
field,
|
||||
"must be a name or a pattern",
|
||||
)
|
||||
}
|
||||
|
||||
/// A message id: 1 and up.
|
||||
pub fn message_id(value: u64, field: &'static str) -> Result<(), DecodeError> {
|
||||
range(value, 1, MAX_MESSAGE_ID, field)
|
||||
|
||||
@@ -9,7 +9,6 @@ use crate::limits::{
|
||||
MAX_ATTACHMENT_PARTS, MAX_MESSAGE_ID, MAX_MESSAGES_PER_PACKET, MAX_MISSING_ATTACHMENTS,
|
||||
MAX_NAMES_LIST_ENTRIES,
|
||||
};
|
||||
use crate::names;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// What the server takes from this peer, how far it is, and the
|
||||
@@ -75,11 +74,7 @@ impl Check for SyncState {
|
||||
] {
|
||||
rules::most(list.len(), MAX_NAMES_LIST_ENTRIES, field)?;
|
||||
for item in list {
|
||||
rules::require(
|
||||
names::is_valid_name_or_pattern(item),
|
||||
field,
|
||||
"must be a name or a pattern",
|
||||
)?;
|
||||
rules::name_or_pattern(item, field)?;
|
||||
}
|
||||
}
|
||||
for head in &self.heads {
|
||||
|
||||
@@ -98,6 +98,14 @@ fn samples() -> Vec<Packet> {
|
||||
AttachmentPart { data: vec![1] }.into(),
|
||||
ListNames {
|
||||
kind: NameKind::Topic,
|
||||
topics: None,
|
||||
nodes: None,
|
||||
}
|
||||
.into(),
|
||||
ListNames {
|
||||
kind: NameKind::Node,
|
||||
topics: Some("sensors.*".into()),
|
||||
nodes: Some("kitchen".into()),
|
||||
}
|
||||
.into(),
|
||||
NamesList {
|
||||
@@ -297,8 +305,18 @@ fn shapes() {
|
||||
PacketType::Messages,
|
||||
(1u8, Vec::<u8>::new())
|
||||
)));
|
||||
assert!(malformed(&raw(PacketType::ListNames, (3u8,))), "kind 3");
|
||||
assert!(malformed(&raw(PacketType::ListNames, (0u8,))), "kind 0");
|
||||
assert!(
|
||||
malformed(&raw(PacketType::ListNames, (3u8, (), ()))),
|
||||
"kind 3"
|
||||
);
|
||||
assert!(
|
||||
malformed(&raw(PacketType::ListNames, (0u8, (), ()))),
|
||||
"kind 0"
|
||||
);
|
||||
assert!(
|
||||
malformed(&raw(PacketType::ListNames, (1u8,))),
|
||||
"protocol 7's, no filters"
|
||||
);
|
||||
assert!(
|
||||
malformed(&raw(
|
||||
PacketType::Attachment,
|
||||
@@ -365,6 +383,19 @@ fn ranges() {
|
||||
assert!(Packet::decode(&get(Some(MAX_MESSAGE_ID), 1)).is_ok());
|
||||
assert!(invalid(&get(Some(MAX_MESSAGE_ID + 1), 1)));
|
||||
|
||||
let list = |topics: Option<&str>, nodes: Option<&str>| {
|
||||
ListNames {
|
||||
kind: NameKind::Node,
|
||||
topics: topics.map(Into::into),
|
||||
nodes: nodes.map(Into::into),
|
||||
}
|
||||
.encode()
|
||||
};
|
||||
assert!(Packet::decode(&list(Some("sensors.*"), Some("kitchen"))).is_ok());
|
||||
assert!(invalid(&list(Some("a b"), None)));
|
||||
assert!(invalid(&list(None, Some(""))));
|
||||
assert!(invalid(&list(None, Some("12"))));
|
||||
|
||||
let times = |pushed_at| {
|
||||
Messages {
|
||||
more: false,
|
||||
|
||||
@@ -7,7 +7,7 @@ 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::names::{name_matches, names_equal};
|
||||
use bakashrot_proto::packets::{
|
||||
Attachment, AttachmentPart, Continue, GetAttachment, GetMessages, ListNames, MessagePushed,
|
||||
Messages, NameKind, NamesList, PushMessage, Query, QueryResult, RequestRefused, Welcome,
|
||||
@@ -476,38 +476,50 @@ async fn get_messages(shared: &Arc<Shared>, peer: &Peer, get: GetMessages) -> Pa
|
||||
}
|
||||
}
|
||||
|
||||
/// Topics: those with messages (pushed here or replicated) that it may
|
||||
/// push to or read; every one with `list_topics` or `query`. Nodes: those
|
||||
/// with messages in the topics it may read; every one with `list_nodes`
|
||||
/// or `query`.
|
||||
/// The topics or nodes of the topic and node pairs with messages (pushed
|
||||
/// here or replicated, or that had some) that the filters match, among
|
||||
/// those it may see. A pair's topic must be one it may see when the answer
|
||||
/// is topics or `topics` filters them: one it may push to or read, any
|
||||
/// with `list_topics` or `query`. Its node, when the answer is nodes or
|
||||
/// `nodes` filters them: one in a topic it may read, any with
|
||||
/// `list_nodes` or `query`. Without filters: the topics it may see, the
|
||||
/// nodes it may.
|
||||
async fn list_names(shared: &Arc<Shared>, peer: &Peer, list: ListNames) -> Packet {
|
||||
let permissions = &peer.permissions;
|
||||
let found = match list.kind {
|
||||
NameKind::Topic => shared
|
||||
.read(|reader| reader.topics())
|
||||
.await
|
||||
.map(|mut topics| {
|
||||
if !permissions.lists_every_topic() {
|
||||
topics
|
||||
.retain(|topic| permissions.can_push(topic) || permissions.can_read(topic));
|
||||
}
|
||||
topics
|
||||
}),
|
||||
NameKind::Node if permissions.lists_every_node() => {
|
||||
shared.read(|reader| reader.nodes()).await
|
||||
}
|
||||
NameKind::Node => shared.read(|reader| reader.heads()).await.map(|heads| {
|
||||
let mut nodes: Vec<String> = heads
|
||||
let permissions = peer.permissions.clone();
|
||||
let kind = list.kind;
|
||||
// A pass over every pair: on the read's thread, off the async ones.
|
||||
let found = shared
|
||||
.read(move |reader| {
|
||||
let matches = |filter: &Option<String>, name: &str| {
|
||||
filter
|
||||
.as_deref()
|
||||
.is_none_or(|filter| name_matches(filter, name))
|
||||
};
|
||||
let check_topic = kind == NameKind::Topic || list.topics.is_some();
|
||||
let check_node = kind == NameKind::Node || list.nodes.is_some();
|
||||
let mut names: Vec<String> = reader
|
||||
.heads()?
|
||||
.into_iter()
|
||||
.filter(|head| permissions.can_read(&head.topic))
|
||||
.map(|head| head.node)
|
||||
.filter(|head| {
|
||||
matches(&list.topics, &head.topic)
|
||||
&& matches(&list.nodes, &head.node)
|
||||
&& (!check_topic || permissions.may_list_topic(&head.topic))
|
||||
&& (!check_node || permissions.may_list_nodes_of(&head.topic))
|
||||
})
|
||||
.map(|head| match kind {
|
||||
NameKind::Topic => head.topic,
|
||||
NameKind::Node => head.node,
|
||||
})
|
||||
.collect();
|
||||
// As `reader.nodes()` answers them: in order, none twice.
|
||||
nodes.sort_by_cached_key(|node| node.to_ascii_lowercase());
|
||||
nodes.dedup_by(|a, b| names_equal(a, b));
|
||||
nodes
|
||||
}),
|
||||
};
|
||||
// In order, none twice (names are without case).
|
||||
names.sort_unstable_by(|a, b| {
|
||||
let a = a.bytes().map(|c| c.to_ascii_lowercase());
|
||||
a.cmp(b.bytes().map(|c| c.to_ascii_lowercase()))
|
||||
});
|
||||
names.dedup_by(|a, b| names_equal(a, b));
|
||||
Ok(names)
|
||||
})
|
||||
.await;
|
||||
let mut names = match found {
|
||||
Ok(names) => names,
|
||||
Err(refused) => return refused.into(),
|
||||
@@ -515,7 +527,7 @@ async fn list_names(shared: &Arc<Shared>, peer: &Peer, list: ListNames) -> Packe
|
||||
let truncated = names.len() > MAX_NAMES_LIST_ENTRIES;
|
||||
names.truncate(MAX_NAMES_LIST_ENTRIES);
|
||||
NamesList {
|
||||
kind: list.kind,
|
||||
kind,
|
||||
truncated,
|
||||
names,
|
||||
}
|
||||
|
||||
@@ -596,12 +596,13 @@ fn names() {
|
||||
.connect(&running.issue("analyst-1", &["analyst"]))
|
||||
.unwrap();
|
||||
|
||||
let names = |client: &mut Client, kind| {
|
||||
let list = client.list_names(kind).unwrap();
|
||||
let filtered = |client: &mut Client, kind, topics, nodes| {
|
||||
let list = client.list_names(kind, topics, nodes).unwrap();
|
||||
assert_eq!(list.kind, kind);
|
||||
assert!(!list.truncated);
|
||||
list.names
|
||||
};
|
||||
let names = |client: &mut Client, kind| filtered(client, kind, None, None);
|
||||
// Topics: those it may push to or read; every one for a query role.
|
||||
assert_eq!(names(&mut sensor, NameKind::Topic), ["logs", "sensors"]);
|
||||
assert_eq!(names(&mut screen, NameKind::Topic), ["logs"]);
|
||||
@@ -624,6 +625,55 @@ fn names() {
|
||||
),
|
||||
ErrorCode::NotAllowed.code()
|
||||
);
|
||||
|
||||
// Filtered: the topics a node pushed to, the nodes that pushed to a
|
||||
// topic; names (without case) or patterns.
|
||||
sensor.push("sensors", "{}").unwrap();
|
||||
let (topic, node) = (NameKind::Topic, NameKind::Node);
|
||||
let every = &mut analyst;
|
||||
assert_eq!(
|
||||
filtered(every, topic, None, Some("kitchen")),
|
||||
["logs", "sensors"]
|
||||
);
|
||||
assert_eq!(
|
||||
filtered(every, topic, None, Some("KITCHEN")),
|
||||
["logs", "sensors"]
|
||||
);
|
||||
assert_eq!(filtered(every, topic, None, Some("g*")), ["sensors"]);
|
||||
assert!(filtered(every, topic, None, Some("nobody")).is_empty());
|
||||
assert_eq!(
|
||||
filtered(every, node, Some("sensors"), None),
|
||||
["garage", "kitchen"]
|
||||
);
|
||||
assert_eq!(filtered(every, node, Some("l?gs"), None), ["kitchen"]);
|
||||
assert_eq!(filtered(every, node, Some("*"), Some("k*")), ["kitchen"]);
|
||||
assert_eq!(
|
||||
filtered(every, topic, Some("s*"), Some("kitchen")),
|
||||
["sensors"]
|
||||
);
|
||||
// Only what it may see: the nodes of the topics it may read...
|
||||
assert_eq!(
|
||||
filtered(&mut screen, topic, None, Some("kitchen")),
|
||||
["logs"]
|
||||
);
|
||||
assert!(filtered(&mut screen, topic, None, Some("garage")).is_empty());
|
||||
assert_eq!(filtered(&mut screen, node, Some("*"), None), ["kitchen"]);
|
||||
// ...not of those it may only push to, the topics of those it may.
|
||||
assert!(filtered(&mut sensor, topic, None, Some("garage")).is_empty());
|
||||
assert_eq!(filtered(&mut sensor, topic, Some("s*"), None), ["sensors"]);
|
||||
assert_eq!(
|
||||
filtered(&mut explorer, topic, None, Some("garage")),
|
||||
["sensors"]
|
||||
);
|
||||
assert_eq!(
|
||||
filtered(&mut explorer, node, Some("logs"), None),
|
||||
["kitchen"]
|
||||
);
|
||||
// Neither a name nor a pattern: refused before it's sent.
|
||||
let error = analyst
|
||||
.list_names(NameKind::Node, Some("a b"), None)
|
||||
.unwrap_err();
|
||||
assert_eq!(error.code(), ErrorCode::InvalidArgument.code(), "{error}");
|
||||
}
|
||||
|
||||
/// Queries: allowed or not, results, refusals.
|
||||
@@ -1549,14 +1599,20 @@ fn replication_edges() {
|
||||
assert_eq!(got.messages[0].data, "m1");
|
||||
// (`old` had a message, past its age.)
|
||||
assert_eq!(
|
||||
reader.list_names(NameKind::Topic).unwrap().names,
|
||||
reader
|
||||
.list_names(NameKind::Topic, None, None)
|
||||
.unwrap()
|
||||
.names,
|
||||
["elsewhere", "logs", "old"]
|
||||
);
|
||||
let mut logs_only = running
|
||||
.connect(&running.issue("lounge", &["logs"]))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
logs_only.list_names(NameKind::Topic).unwrap().names,
|
||||
logs_only
|
||||
.list_names(NameKind::Topic, None, None)
|
||||
.unwrap()
|
||||
.names,
|
||||
["logs"]
|
||||
);
|
||||
assert_eq!(
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
use crate::{Error, QueryRunner, Reader, Result, SCHEMA_VERSION, Writer};
|
||||
use bakashrot_config::Synchronous;
|
||||
use rusqlite::hooks::{AuthAction, AuthContext, Authorization};
|
||||
use rusqlite::{Connection, OptionalExtension, TransactionBehavior};
|
||||
use rusqlite::{Connection, OpenFlags, OptionalExtension, TransactionBehavior};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -129,13 +129,20 @@ impl Database {
|
||||
Ok(Reader::new(self.connect()?))
|
||||
}
|
||||
|
||||
/// A connection for clients' queries: read-only (`query_only`), and
|
||||
/// every PRAGMA refused from then on (SQLite's authorizer). Some take
|
||||
/// effect when they're prepared, before a statement can be refused
|
||||
/// for what it is: `PRAGMA query_only = 0` turned `query_only` off
|
||||
/// for the connection's next queries.
|
||||
/// A connection for clients' queries: the file opened read-only
|
||||
/// (`SQLITE_OPEN_READONLY`: the file handle can't write), `query_only`,
|
||||
/// and every PRAGMA refused from then on (SQLite's authorizer). Some
|
||||
/// take effect when they're prepared, before a statement can be
|
||||
/// refused for what it is: `PRAGMA query_only = 0` turned
|
||||
/// `query_only` off for the connection's next queries. The database is
|
||||
/// in WAL mode already (the writer made it so), which a read-only
|
||||
/// connection can't change and doesn't need to.
|
||||
pub fn query_runner(&self) -> Result<QueryRunner> {
|
||||
let mut connection = self.connect()?;
|
||||
let flags = OpenFlags::SQLITE_OPEN_READ_ONLY
|
||||
| OpenFlags::SQLITE_OPEN_URI
|
||||
| OpenFlags::SQLITE_OPEN_NO_MUTEX;
|
||||
let mut connection = Connection::open_with_flags(&self.path, flags)?;
|
||||
connection.busy_timeout(BUSY_TIMEOUT)?;
|
||||
connection.pragma_update(None, "query_only", true)?;
|
||||
connection.authorizer(Some(|context: AuthContext<'_>| match context.action {
|
||||
AuthAction::Pragma { .. } => Authorization::Deny,
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! Clients' read-only SQL (`Query`).
|
||||
//!
|
||||
//! Read-only three ways: the connection has `query_only` on (SQLite
|
||||
//! refuses any write), the statement must be one SQLite says only reads
|
||||
//! Read-only four ways: the file is opened read-only (the handle itself
|
||||
//! can't write), the connection has `query_only` on (SQLite refuses any
|
||||
//! write), the statement must be one SQLite says only reads
|
||||
//! (`sqlite3_stmt_readonly`), and only one statement runs (more is an
|
||||
//! error, not ignored). PRAGMAs are refused as they're prepared
|
||||
//! (`Database::query_runner`'s authorizer): some would change the
|
||||
@@ -96,3 +97,33 @@ fn text(value: ValueRef<'_>) -> Value {
|
||||
ValueRef::Blob(bytes) => Value::String(bytes.iter().map(|b| format!("{b:02x}")).collect()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::Database;
|
||||
use bakashrot_config::Synchronous;
|
||||
use rusqlite::MAIN_DB;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// The fifth guard, which the others hide from a test of what's
|
||||
/// refused: SQLite says the file itself is read-only on it.
|
||||
#[test]
|
||||
fn the_file_is_opened_read_only() {
|
||||
let folder = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../target/storage-unit");
|
||||
std::fs::create_dir_all(&folder).unwrap();
|
||||
let path = folder.join(format!("query-{}.sqlite", std::process::id()));
|
||||
let database = Database::open(&path, Synchronous::Normal).unwrap();
|
||||
// The server's writer is always open: the WAL's files are there.
|
||||
let writer = database.writer().unwrap();
|
||||
let runner = database.query_runner().unwrap();
|
||||
assert!(runner.connection.is_readonly(MAIN_DB).unwrap());
|
||||
assert_eq!(
|
||||
runner.run("SELECT 1 AS one").unwrap(),
|
||||
r#"{"columns":["one"],"rows":[["1"]]}"#
|
||||
);
|
||||
drop((runner, writer, database));
|
||||
for suffix in ["", "-wal", "-shm"] {
|
||||
let _ = std::fs::remove_file(format!("{}{suffix}", path.display()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -152,11 +152,6 @@ impl Reader {
|
||||
self.strings("SELECT DISTINCT topic FROM streams ORDER BY topic")
|
||||
}
|
||||
|
||||
/// Every node with messages (or that had some), in order.
|
||||
pub fn nodes(&self) -> Result<Vec<String>> {
|
||||
self.strings("SELECT DISTINCT node FROM streams ORDER BY node")
|
||||
}
|
||||
|
||||
/// Whether `node` has messages in any topic (or had some).
|
||||
fn has_node(&self, node: &str) -> Result<bool> {
|
||||
self.connection
|
||||
|
||||
@@ -159,7 +159,6 @@ fn pushing_and_reading() {
|
||||
|
||||
// Names, heads.
|
||||
assert_eq!(reader.topics().unwrap(), ["logs", "sensors"]);
|
||||
assert_eq!(reader.nodes().unwrap(), ["garage", "kitchen"]);
|
||||
let heads: Vec<_> = reader
|
||||
.heads()
|
||||
.unwrap()
|
||||
|
||||
@@ -105,10 +105,20 @@ enum Command {
|
||||
},
|
||||
/// Lists the topics this client may use and the nodes of those it may
|
||||
/// read; every one if its roles have list_topics / list_nodes, or query.
|
||||
/// --topics and --nodes keep the topics and nodes of the topic and node
|
||||
/// pairs they match: `list topics --nodes kitchen` the topics kitchen
|
||||
/// pushed to, `list nodes --topics 'sensors.*'` the nodes that pushed
|
||||
/// to those.
|
||||
List {
|
||||
/// What to list.
|
||||
#[arg(value_enum, default_value_t = What::All)]
|
||||
what: What,
|
||||
/// Only of the topics with this name or matching this pattern.
|
||||
#[arg(long)]
|
||||
topics: Option<String>,
|
||||
/// Only of the nodes with this name or matching this pattern.
|
||||
#[arg(long)]
|
||||
nodes: Option<String>,
|
||||
/// Prints JSON, a line per list: {"kind":...,"names":[...],"truncated":...}.
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
@@ -264,7 +274,12 @@ fn run(config: &Path, command: Command) -> Result<(), String> {
|
||||
let sql = input(&sql)?;
|
||||
println!("{}", connect(config)?.query(&sql).map_err(failed)?);
|
||||
}
|
||||
Command::List { what, json } => {
|
||||
Command::List {
|
||||
what,
|
||||
topics,
|
||||
nodes,
|
||||
json,
|
||||
} => {
|
||||
let mut client = connect(config)?;
|
||||
let kinds = [
|
||||
(NameKind::Topic, "topic", "Topics"),
|
||||
@@ -277,7 +292,9 @@ fn run(config: &Path, command: Command) -> Result<(), String> {
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
let list = client.list_names(kind).map_err(failed)?;
|
||||
let list = client
|
||||
.list_names(kind, topics.as_deref(), nodes.as_deref())
|
||||
.map_err(failed)?;
|
||||
if json {
|
||||
let json = serde_json::json!({
|
||||
"kind": name,
|
||||
|
||||
@@ -463,6 +463,24 @@ fn queries_and_lists() {
|
||||
json.ok().out,
|
||||
"{\"kind\":\"node\",\"names\":[\"kitchen\"],\"truncated\":false}\n"
|
||||
);
|
||||
// Filtered: the topics a node pushed to, the nodes of some topics.
|
||||
assert_eq!(
|
||||
server
|
||||
.tool("kitchen", &["list", "topics", "--nodes", "Kitchen"])
|
||||
.ok()
|
||||
.out,
|
||||
"Topics (1):\n logs\n"
|
||||
);
|
||||
assert_eq!(
|
||||
server
|
||||
.tool("kitchen", &["list", "--topics", "l*", "--nodes", "nobody"])
|
||||
.ok()
|
||||
.out,
|
||||
"Topics (0):\nNodes (0):\n"
|
||||
);
|
||||
server
|
||||
.tool("kitchen", &["list", "nodes", "--topics", "a b"])
|
||||
.fails(1, "isn't a topic name or pattern");
|
||||
server
|
||||
.tool("kitchen", &["list", "everything"])
|
||||
.fails(2, "everything");
|
||||
|
||||
Reference in New Issue
Block a user