1
0
mirror of https://github.com/aziascreations/BakaShrot.git synced 2026-11-23 20:58:46 +01:00

Moved the PureBasic version to OldSource/, Started the Rust rewrite in Source/

The rewrite's plan and decisions are in revamp.md. Steps 0 to 10 are done:
the workspace and checks, bakashrot-proto, bakashrot-pki and
bakashrot-cert, bakashrot-config, bakashrot-storage (schema v9), the
server and the client library (every request but replication's,
attachments and retention included), the C DLL with its C, PureBasic and
Python bindings, and the bakashrot tool. Step 11 (replication) is next.

OldSource/ is the old implementation, kept building and passing as the
reference.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RwFeVTGs2SsufaH6zquzcb
This commit is contained in:
2026-11-14 12:47:40 +01:00
parent d0048b17c8
commit e044fcf359
225 changed files with 21849 additions and 123 deletions
+333
View File
@@ -0,0 +1,333 @@
# ============================================================================
# BakaShrot build & run script
#
# 0. Extracts libsodium's dynamic build from Libs/libsodium-*-msvc.zip, and
# sqlite3.dll from the latest Libs/sqlite-dll-win-*.zip, if not done yet.
# Delete Libs/libsodium/x64 or Libs/sqlite/x64 to extract them again.
# 1. Compiles BakaShrotGenerateKeyPairs, the server, the client DLL, its
# example app and the tools (BakaShrotPushMessage,
# BakaShrotGetLatestMessage, BakaShrotGetMessages, BakaShrotGetAttachment,
# BakaShrotQuery, BakaShrotResolveIds, BakaShrotList) into ./Build, next to copies of
# libsodium.dll and sqlite3.dll
# 2. Generates a keypair for two servers and one for a client
# 3. Writes the servers' configs and the client's keys. Topics and nodes
# have names, and each server its own ids for them, to show names being
# translated (logs is 1 on server, 200 on server2):
# server.ini logs:server1 on port 12345, registers the client, peer
# of server2, database ./server.sqlite
# server2.ini logs:server2 on port 12346, peer of server, database
# ./server2.sqlite
# client.ini logs:local through server, for the tools and the example
# app, may push to logs and sensors, read every topic, and
# run raw queries
# client2.ini logs:local2 through server2, same client key, may not query
# Both servers replicate logs and sensors to each other, e.g.:
# .\BakaShrotPushMessage.exe -t sensors @msg.json client.ini
# .\BakaShrotGetLatestMessage.exe sensors local client2.ini
# .\BakaShrotGetMessages.exe logs local --follow client2.ini
# .\BakaShrotResolveIds.exe topic sensors client2.ini (201 there, 2 on server)
# .\BakaShrotQuery.exe "SELECT topic, node, message_id FROM messages" client.ini
# 4. Runs the first server, type "quit" or an empty line to stop it, or
# "restart" / "vacuum" / "help". Run the second one in
# another terminal to see them link: .\BakaShrot_Server.exe server2.ini
#
# Usage: powershell -ExecutionPolicy Bypass -File Build.ps1 [-Compiler <path>]
#
# Keys are regenerated on every run, ./Build is git-ignored since it holds
# private keys.
# ============================================================================
param(
[string]$Compiler = "C:\Program Files\PureBasic_573\Compilers\pbcompiler.exe"
)
$ErrorActionPreference = "Stop"
$Root = $PSScriptRoot
$Output = Join-Path $Root "Build"
# Where Commons/Cryptography/Libsodium.pbi imports it from, x64 since the
# compiler above is the x64 one.
$SodiumDir = Join-Path $Root "Libs\libsodium\x64"
# Where sqlite3.dll is extracted to, the server loads it instead of the
# SQLite bundled with PureBasic 5.73, which lacks the JSON functions.
$SqliteDir = Join-Path $Root "Libs\sqlite\x64"
$ServerHost = "127.0.0.1"
$ServerPort = 12345
$Server2Port = 12346
$PeerRetryDelay = 10
$PeerBatchSize = 100
# The same names on both servers, different ids, see the top of this file.
# Same client, through server2 as its own node (local2), so no topic/node is
# ever written to on both servers.
$Topics = @{ logs = 1; sensors = 2 }
$Nodes = @{ server1 = 1; local = 2; server2 = 3; local2 = 4 }
$Topics2 = @{ logs = 200; sensors = 201 }
$Nodes2 = @{ server1 = 11; local = 12; server2 = 13; local2 = 14 }
function Format-Names($Names) {
($Names.GetEnumerator() | Sort-Object Value | ForEach-Object { "$($_.Key) = $($_.Value)" }) -join "`r`n"
}
function Expand-Libsodium {
$Zip = Get-ChildItem (Join-Path $Root "Libs") -Filter "libsodium-*-msvc.zip" | Select-Object -First 1
if (-not $Zip) {
throw "Missing Libs\libsodium-*-msvc.zip, get it from https://download.libsodium.org/libsodium/releases/"
}
Write-Host "Extracting libsodium from $($Zip.Name)"
Add-Type -AssemblyName System.IO.Compression.FileSystem
$Archive = [IO.Compression.ZipFile]::OpenRead($Zip.FullName)
try {
# Zip folder -> Libs\libsodium folder
$Targets = @{ "x64" = "x64"; "Win32" = "x86" }
foreach ($Arch in $Targets.Keys) {
$Destination = Join-Path $Root "Libs\libsodium\$($Targets[$Arch])"
New-Item -ItemType Directory -Force $Destination | Out-Null
foreach ($Name in @("libsodium.dll", "libsodium.lib")) {
$Entry = $Archive.GetEntry("libsodium/$Arch/Release/v143/dynamic/$Name")
if (-not $Entry) {
throw "$($Zip.Name) has no $Arch dynamic $Name"
}
[IO.Compression.ZipFileExtensions]::ExtractToFile($Entry, (Join-Path $Destination $Name), $true)
}
}
}
finally {
$Archive.Dispose()
}
}
function Expand-Sqlite {
Add-Type -AssemblyName System.IO.Compression.FileSystem
foreach ($Arch in @("x64", "x86")) {
# The version in the name is zero-padded, so the last one by name is the latest.
$Zip = Get-ChildItem (Join-Path $Root "Libs") -Filter "sqlite-dll-win-$Arch-*.zip" | Sort-Object Name | Select-Object -Last 1
if (-not $Zip) {
throw "Missing Libs\sqlite-dll-win-$Arch-*.zip, get it from https://www.sqlite.org/download.html"
}
Write-Host "Extracting SQLite from $($Zip.Name)"
$Destination = Join-Path $Root "Libs\sqlite\$Arch"
New-Item -ItemType Directory -Force $Destination | Out-Null
$Archive = [IO.Compression.ZipFile]::OpenRead($Zip.FullName)
try {
$Entry = $Archive.GetEntry("sqlite3.dll")
if (-not $Entry) {
throw "$($Zip.Name) has no sqlite3.dll"
}
[IO.Compression.ZipFileExtensions]::ExtractToFile($Entry, (Join-Path $Destination "sqlite3.dll"), $true)
}
finally {
$Archive.Dispose()
}
}
}
function Invoke-Compiler($Source, $Executable, $Flags) {
Write-Host "Compiling $Source"
& $Compiler (Join-Path $Root $Source) @Flags /QUIET /EXE (Join-Path $Output $Executable)
if ($LASTEXITCODE -ne 0) {
throw "Failed to compile $Source"
}
}
function New-KeyPair {
# BakaShrotGenerateKeyPairs prints "PrivateKey = ..." then "PublicKey = ...".
$Lines = & (Join-Path $Output "BakaShrotGenerateKeyPairs.exe")
if ($LASTEXITCODE -ne 0) {
throw "BakaShrotGenerateKeyPairs failed: $Lines"
}
return @{
PrivateKey = $Lines[0] -replace "^PrivateKey = ", ""
PublicKey = $Lines[1] -replace "^PublicKey = ", ""
}
}
Push-Location $Root
try {
New-Item -ItemType Directory -Force $Output | Out-Null
# 0. libsodium
if (-not (Test-Path (Join-Path $SodiumDir "libsodium.lib"))) {
Expand-Libsodium
}
Copy-Item (Join-Path $SodiumDir "libsodium.dll") $Output -Force
# 0. SQLite
if (-not (Test-Path (Join-Path $SqliteDir "sqlite3.dll"))) {
Expand-Sqlite
}
Copy-Item (Join-Path $SqliteDir "sqlite3.dll") $Output -Force
# 1. Compile
Invoke-Compiler "Tools\BakaShrotGenerateKeyPairs\BakaShrotGenerateKeyPairs.pb" "BakaShrotGenerateKeyPairs.exe" @("/CONSOLE")
Invoke-Compiler "Server\BakaShrot_Server.pb" "BakaShrot_Server.exe" @("/CONSOLE", "/THREAD")
Invoke-Compiler "Client\BakaShrot_Client.pbi" "BakaShrot_Client.dll" @("/DLL", "/THREAD")
# Example app using the DLL, run it from ./Build while the server runs.
Invoke-Compiler "Client\BakaShrot_Client_Prototypes.pbi" "ClientExample.exe" @("/CONSOLE")
# Tools using the DLL, same as the example:
# BakaShrotPushMessage [-t <Topic>] [-a <File>] <Json|@JsonFile> [ClientIni]
Invoke-Compiler "Tools\BakaShrotPushMessage\BakaShrotPushMessage.pb" "BakaShrotPushMessage.exe" @("/CONSOLE")
# BakaShrotGetLatestMessage <Topic> <Node> [ClientIni]
Invoke-Compiler "Tools\BakaShrotGetLatestMessage\BakaShrotGetLatestMessage.pb" "BakaShrotGetLatestMessage.exe" @("/CONSOLE")
# BakaShrotGetMessages <Topic> <Node> [--after <Id|latest>] [--limit <N>] [--follow] [ClientIni]
Invoke-Compiler "Tools\BakaShrotGetMessages\BakaShrotGetMessages.pb" "BakaShrotGetMessages.exe" @("/CONSOLE")
# BakaShrotGetAttachment <Topic> <Node> <MessageId> <OutFile> [ClientIni]
Invoke-Compiler "Tools\BakaShrotGetAttachment\BakaShrotGetAttachment.pb" "BakaShrotGetAttachment.exe" @("/CONSOLE")
# BakaShrotQuery <Sql|@SqlFile> [ClientIni]
Invoke-Compiler "Tools\BakaShrotQuery\BakaShrotQuery.pb" "BakaShrotQuery.exe" @("/CONSOLE")
# BakaShrotResolveIds <topic|node> <NameOrId> [ClientIni]
Invoke-Compiler "Tools\BakaShrotResolveIds\BakaShrotResolveIds.pb" "BakaShrotResolveIds.exe" @("/CONSOLE")
# BakaShrotList [topics|nodes|all] [ClientIni] [--json]
Invoke-Compiler "Tools\BakaShrotList\BakaShrotList.pb" "BakaShrotList.exe" @("/CONSOLE")
# 2. Keys
Write-Host "Generating keys"
$ServerKeys = New-KeyPair
$Server2Keys = New-KeyPair
$ClientKeys = New-KeyPair
# 3. Configs
# Both servers are each other's peer, and register each other as a client
# so the links can authenticate.
$ServerConfig = @"
[BakaShrot]
PrivateKey = $($ServerKeys.PrivateKey)
Node = server1
; This server's ids for the names every server shares.
[BakaShrot.Topics]
$(Format-Names $Topics)
[BakaShrot.Nodes]
$(Format-Names $Nodes)
[BakaShrot.Server]
Host = $ServerHost
Port = $ServerPort
ReplicatingTopics = logs;sensors
NetThreadPoolSize = 4
DatabasePath = ./server.sqlite
PeerRetryDelay = $PeerRetryDelay
PeerBatchSize = $PeerBatchSize
[BakaShrot.Peer.server2]
Host = $ServerHost
Port = $Server2Port
Node = server2
PublicKey = $($Server2Keys.PublicKey)
[BakaShrot.Client.local]
PublicKeys = $($ClientKeys.PublicKey)
Node = local
DefaultTopic = logs
PushTopics = logs;sensors
ReadTopics = *
AllowRead = 1
AllowWrite = 1
AllowQuery = 1
; The peer only replicates, it has no business reading or writing as a client.
[BakaShrot.Client.server2]
PublicKeys = $($Server2Keys.PublicKey)
Node = server2
AllowRead = 0
AllowWrite = 0
AllowQuery = 0
"@
Set-Content -Path (Join-Path $Output "server.ini") -Value $ServerConfig -Encoding Ascii
$Server2Config = @"
[BakaShrot]
PrivateKey = $($Server2Keys.PrivateKey)
Node = server2
; Other ids than server's, same names: replication goes by name.
[BakaShrot.Topics]
$(Format-Names $Topics2)
[BakaShrot.Nodes]
$(Format-Names $Nodes2)
[BakaShrot.Server]
Host = $ServerHost
Port = $Server2Port
ReplicatingTopics = logs;sensors
NetThreadPoolSize = 4
DatabasePath = ./server2.sqlite
PeerRetryDelay = $PeerRetryDelay
PeerBatchSize = $PeerBatchSize
[BakaShrot.Peer.server]
Host = $ServerHost
Port = $ServerPort
Node = server1
PublicKey = $($ServerKeys.PublicKey)
; The peer only replicates, it has no business reading or writing as a client.
[BakaShrot.Client.server]
PublicKeys = $($ServerKeys.PublicKey)
Node = server1
AllowRead = 0
AllowWrite = 0
AllowQuery = 0
; No raw queries through this server.
[BakaShrot.Client.local]
PublicKeys = $($ClientKeys.PublicKey)
Node = local2
DefaultTopic = logs
PushTopics = logs;sensors
ReadTopics = *
AllowRead = 1
AllowWrite = 1
AllowQuery = 0
"@
Set-Content -Path (Join-Path $Output "server2.ini") -Value $Server2Config -Encoding Ascii
$Client2Config = @"
[BakaShrot]
PrivateKey = $($ClientKeys.PrivateKey)
PublicKey = $($ClientKeys.PublicKey)
Node = local2
ServerHost = $ServerHost
ServerPort = $Server2Port
ServerPublicKey = $($Server2Keys.PublicKey)
"@
Set-Content -Path (Join-Path $Output "client2.ini") -Value $Client2Config -Encoding Ascii
# Read by ClientExample.exe.
$ClientConfig = @"
[BakaShrot]
PrivateKey = $($ClientKeys.PrivateKey)
PublicKey = $($ClientKeys.PublicKey)
Node = local
ServerHost = $ServerHost
ServerPort = $ServerPort
ServerPublicKey = $($ServerKeys.PublicKey)
"@
Set-Content -Path (Join-Path $Output "client.ini") -Value $ClientConfig -Encoding Ascii
Write-Host "Wrote Build\server.ini, Build\server2.ini, Build\client.ini and Build\client2.ini"
# 4. Run, from ./Build so ./test.sqlite ends up there too.
Write-Host "Start the second server in another terminal to see them link:"
Write-Host " cd Build; .\BakaShrot_Server.exe server2.ini"
Push-Location $Output
try {
& ".\BakaShrot_Server.exe" "server.ini"
}
finally {
Pop-Location
}
}
finally {
Pop-Location
}
+121
View File
@@ -0,0 +1,121 @@
# BakaShrot, the old PureBasic implementation - start here
**Frozen since 2026-11-13** as the reference for the Rust rewrite
(`../revamp.md`, `../CLAUDE.md`). Every path below is relative to this
folder, `OldSource/`: run the scripts and compilers from here.
A message store with replication, in PureBasic: servers take JSON (or any)
messages per topic/node from authenticated clients, store them in SQLite,
and replicate them between peers by name. Clients: a DLL, CLI tools, a
Python module. An **internal tool on trusted machines**: correctness and
operations come before security hardening (`Notes.md`, "Threat model").
## Read first
1. `Notes.md`: "Right now" (what's committed, what's next), where things
stand, "Open items, by importance" (the to-do list), "Testing tips".
2. `Design/`, by topic: `Packets.md` (the protocol, where every file lives,
code conventions), `Attachments.md`, `Cryptography.md`,
`Certificates.md`, `StorageConcurrency.md`, `ReplicationIssues.md`,
`Release.md`, `Suggestions.md`.
3. `git log --oneline` and `git status`: what's committed. Work happens on
branches off `master` (`timestamps-retention` at this writing).
## Build
- Dev compiler, PureBasic 5.73: `C:\Program Files\PureBasic_573\Compilers\pbcompiler.exe <src> /EXE <out> [flags]`.
Release compiler, 6.40 C backend: `C:\Program Files\PureBasic_640\Compilers\pbcompilerc.exe <src> /OUTPUT <out> /OPTIMIZER`.
Code must compile with both (`Release.ps1` checks the 6.40 side).
- `Build.ps1` builds everything into `Build\`, **regenerates keys and
configs, then runs a server waiting on its console**: don't run it from
an automated shell. To rebuild after a change, compile what changed:
| Source | Output | Flags |
|---|---|---|
| `Server\BakaShrot_Server.pb` | `Build\BakaShrot_Server.exe` | `/CONSOLE /THREAD` |
| `Client\BakaShrot_Client.pbi` | `Build\BakaShrot_Client.dll` | `/DLL /THREAD` |
| `Tools\<Name>\<Name>.pb` (BakaShrot + PushMessage, GetLatestMessage, GetMessages, GetAttachment, Query, ResolveIds, List, GenerateKeyPairs) | `Build\<Name>.exe` | `/CONSOLE` |
| `Client\BakaShrot_Client_Prototypes.pbi` | `Build\ClientExample.exe` | `/CONSOLE` |
| `Tests\Bench\BenchServer.pb` (the server with a stop file, used by every test) | `Build\Bench\BenchServer.exe` | `/CONSOLE /THREAD` |
| `Tests\Bench\BenchClient.pb`, `BenchSeed.pb` | `Build\Bench\` | `/CONSOLE /THREAD` |
| `Tests\HandshakeTest.pb`, `Tests\CipherTest.pb`, `Tests\X509Test.pb` | `Build\` | `/CONSOLE` |
| `Tests\AttachmentEdgeClient.pb` | `Build\AttachmentEdgeClient.exe` | `/CONSOLE /THREAD` |
- `Release.ps1 [-Force]` builds the release with 6.40 into `Release\` and
smoke-tests it (`-Force` replaces an existing folder of the same name).
- Linux: same sources and flags (`-t`, `-e`, `-so` for the DLL), with
`libsodium-dev`. `Docker/Server/` builds the server image, on the
PureBasic image `git.nibblepoker.lu/packages/purebasic` (6.41, linux3;
needs a `docker login`), see its Dockerfile.
## Test
Each suite starts its own servers (`BenchServer.exe`) on fixed ports, in a
fresh folder under `Build\`, and prints PASS/FAIL lines; exit code 0 means
all passed. `powershell -ExecutionPolicy Bypass -File Tests\<Suite>.ps1`:
| Suite | Ports | Covers |
|---|---|---|
| `Names-Test.ps1` | 12401-12402 | names/ids, filters, wildcards, replication by name |
| `BigMessages-Test.ps1` | 12403-12404 | 16 MB messages, handshake frame limit, `is_json`, query errors |
| `GetMessages-Test.ps1` | 12405 | runs of messages, `--follow` |
| `Python-Test.ps1` | 12406-12407 | `bakashrot.py` (`check_bakashrot.py`), the wire is encrypted (`wire_check.py`) |
| `Retention-Test.ps1` | 12408-12409 | `pushed_at`, retention, schema upgrade (Python) |
| `Attachments-Test.ps1` | 12410-12411 | attachments through the tools, replication, limits |
| `AttachmentEdges-Test.ps1` | 12413-12414 | raw-protocol edge cases, expiry, resuming, corruption (Python) |
| `Restart-Test.ps1` | 12415-12416 | servers killed mid-traffic and mid-catch-up: nothing acknowledged lost, ids carry on, both catch up (Python pushers) |
| `X509-Test.ps1` | none | X.509 certificates (`X509Test.exe`), both ways with OpenSSL when it's there (Git's) |
Plus `Build\HandshakeTest.exe` and `Build\CipherTest.exe` (no server), and
the release's smoke test. Speed: `Tests\Bench\Bench-Replication.ps1 -Ramp 10x0 -Parts Ramp`
(push ceiling for 4 servers: ~17,000 msg/s with the default `Synchronous =
FULL`, ~34,000-40,000 with `-Synchronous NORMAL`). After a change, run every
suite: they take a few minutes in all.
## Traps
- **Run exes from `Build\`**: the antivirus blocks them in temp folders.
- **`Build\` holds private keys**: git-ignored, never publish it. The one
exception: `Examples/*/` commit their configs, keys included, on purpose
(public, example-only, marked so); don't copy those keys anywhere else.
- **PureBasic is single pass**: constants, structures and procedures must
be declared before use, so include order matters (e.g. `Config.pbi`
includes `Packets.pbi` for its constants).
- **`SetDatabase*()` binds the next statement run on that connection**, not
a specific one: set them right before their `DatabaseUpdate/Query`.
- **Never `Goto` out of a `Select`**: 5.73's ASM backend keeps the value on
the stack, the jump corrupts it (a config error crashed the server with
0xC0000005). Set the error, leave the `Select`, then jump. Out of
`For`/`ForEach`/`While` loops is fine (checked on both compilers).
- **PureBasic lists aren't safe to walk from several threads** (`ForEach`
moves the shared current element): give each thread its own copy.
- **Files mix CRLF and LF**: edits must keep each file's line endings.
- **PowerShell 5**: JSON passed as an argument loses its double quotes
(tests write it to a file, `@file`), and `@()` can't be passed through
`-File`.
- **Bash tool heredocs collapse `\\`**, and PureBasic uses `\` for fields:
write edit scripts to files, or use the Edit tool.
- **The real server needs a console on Windows** (it stops at once without
input): tests use `BenchServer.exe` and its stop file instead. On Linux
it runs on without one, SIGTERM/SIGINT stop it.
## Working rules
- **Commit only when the owner asks**, on a branch, not `master`.
- **Wire changes bump `#BakaShrot_ProtocolVersion`** (`Packets.pbi`, 6 at
this writing); any difference refuses the connection.
- **Schema changes** add a `Server/Storage/db_schema_vN.dbml` (v8 at this
writing) and a migration in `SetupStorageDatabase()` (`Storage.pbi`),
existing databases must keep working.
- **Packets** follow `Design/Packets.md` "Code conventions": one file per
packet in `Commons/Networking/Packets/`, `_Encode` / `_Decode` (and
`_Free` when it holds data), every field validated on decode.
- **Every write goes through the writer** (`Server/Storage/Writer.pbi`,
under its mutex); reads use the thread's own connection.
- **Every `.pb`/`.pbi` starts with a code header** (`;{- Code Header`,
like PB-MessagePack's): name, version (0.0.1 at this writing), tested
compilers. A release bumps the version in all of them; only list a
compiler/platform once every suite passed with it.
- **Docs follow the code**: a finished piece gets a "Done: ... (date)"
section in `Notes.md`, what's left goes to its open items, and the
`Design/` doc of that area is updated with it.
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,7 @@
IDE Options = PureBasic 6.41 beta 2 (Windows - x64)
CursorPosition = 4
EnableXP
DPIAware
CompileSourceDirectory
EnableCompileCount = 0
EnableBuildCount = 0
@@ -0,0 +1,380 @@
;{- Code Header
; ==- Basic Info -================================
; Name: BakaShrot_Client_Prototypes.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; BakaShrot Client DLL - Prototypes
;
; Include this in an app to use BakaShrot_Client.dll:
; XIncludeFile "BakaShrot_Client_Prototypes.pbi"
; If BakaShrot_LoadClient("BakaShrot_Client.dll")
; BakaShrot_SetPrivateKey("...")
; BakaShrot_SetPublicKey("...")
; BakaShrot_SetServerPublicKey("...")
; ...
; BakaShrot_UnloadClient()
; EndIf
;
; See BakaShrot_Client.pbi for what each function does.
; The string functions are mapped to the DLL's W (UTF-16) variants.
; After a failed call, BakaShrot_GetLastError() tells why: the codes and
; what to do about each are in BakaShrot_ErrorCodes.pbi, next to this file
; (included below), BakaShrot_ErrorName() names them.
; ============================================================================
XIncludeFile "BakaShrot_ErrorCodes.pbi"
PrototypeC.i BakaShrot_SetPrivateKey_Prototype(PrivateKey.p-unicode)
PrototypeC.i BakaShrot_SetPublicKey_Prototype(PublicKey.p-unicode)
PrototypeC.i BakaShrot_SetServerPublicKey_Prototype(PublicKey.p-unicode)
PrototypeC.i BakaShrot_SetNodeId_Prototype(NodeId.l)
PrototypeC.i BakaShrot_SetNode_Prototype(Node.p-unicode)
PrototypeC.i BakaShrot_Connect_Prototype(Host.p-unicode, Port.l)
PrototypeC.i BakaShrot_IsConnected_Prototype()
PrototypeC.i BakaShrot_Disconnect_Prototype()
PrototypeC.q BakaShrot_PushMessage_Prototype(JsonData.p-unicode)
PrototypeC.q BakaShrot_PushMessageTo_Prototype(Topic.p-unicode, JsonData.p-unicode)
PrototypeC.i BakaShrot_GetLatestMessage_Prototype(TopicId.l, NodeId.l)
PrototypeC.i BakaShrot_GetLatestMessageOf_Prototype(Topic.p-unicode, Node.p-unicode)
PrototypeC.q BakaShrot_GetMessageId_Prototype()
PrototypeC.q BakaShrot_GetMessagePushedAt_Prototype()
PrototypeC.i BakaShrot_GetMessageData_Prototype(*Buffer, BufferSize.i)
PrototypeC.l BakaShrot_GetMessageTopicId_Prototype()
PrototypeC.l BakaShrot_GetMessageNodeId_Prototype()
PrototypeC.i BakaShrot_GetMessageTopic_Prototype(*Buffer, BufferSize.i)
PrototypeC.i BakaShrot_GetMessageNode_Prototype(*Buffer, BufferSize.i)
PrototypeC.l BakaShrot_ResolveTopic_Prototype(Ref.p-unicode)
PrototypeC.l BakaShrot_ResolveNode_Prototype(Ref.p-unicode)
PrototypeC.i BakaShrot_GetResolvedName_Prototype(*Buffer, BufferSize.i)
PrototypeC.l BakaShrot_ListTopics_Prototype()
PrototypeC.l BakaShrot_ListNodes_Prototype()
PrototypeC.i BakaShrot_GetNamesList_Prototype(*Buffer, BufferSize.i)
PrototypeC.i BakaShrot_GetRefusalReason_Prototype(*Buffer, BufferSize.i)
PrototypeC.l BakaShrot_GetLastError_Prototype()
PrototypeC.i BakaShrot_Query_Prototype(Sql.p-unicode)
PrototypeC.i BakaShrot_GetQueryResult_Prototype(*Buffer, BufferSize.i)
PrototypeC.l BakaShrot_GetMessages_Prototype(Topic.p-unicode, Node.p-unicode, AfterMessageId.q, Limit.l)
PrototypeC.l BakaShrot_GetMessageCount_Prototype()
PrototypeC.i BakaShrot_SelectMessage_Prototype(Index.l)
PrototypeC.i BakaShrot_HasMoreMessages_Prototype()
PrototypeC.q BakaShrot_PushMessageWithFile_Prototype(Topic.p-unicode, JsonData.p-unicode, FilePath.p-unicode)
PrototypeC.q BakaShrot_PushMessageWithData_Prototype(Topic.p-unicode, JsonData.p-unicode, *Data, Size.q)
PrototypeC.q BakaShrot_SaveAttachment_Prototype(Topic.p-unicode, Node.p-unicode, MessageId.q, FilePath.p-unicode)
PrototypeC.q BakaShrot_LoadAttachment_Prototype(Topic.p-unicode, Node.p-unicode, MessageId.q)
PrototypeC.q BakaShrot_GetAttachmentData_Prototype(*Buffer, BufferSize.q)
PrototypeC.i BakaShrot_FreeAttachmentData_Prototype()
PrototypeC.q BakaShrot_GetMessageAttachmentSize_Prototype()
PrototypeC.i BakaShrot_IsMessageAttachmentReady_Prototype()
Global BakaShrot_SetPrivateKey.BakaShrot_SetPrivateKey_Prototype
Global BakaShrot_SetPublicKey.BakaShrot_SetPublicKey_Prototype
Global BakaShrot_SetServerPublicKey.BakaShrot_SetServerPublicKey_Prototype
Global BakaShrot_SetNodeId.BakaShrot_SetNodeId_Prototype
Global BakaShrot_SetNode.BakaShrot_SetNode_Prototype
Global BakaShrot_Connect.BakaShrot_Connect_Prototype
Global BakaShrot_IsConnected.BakaShrot_IsConnected_Prototype
Global BakaShrot_Disconnect.BakaShrot_Disconnect_Prototype
Global BakaShrot_PushMessage.BakaShrot_PushMessage_Prototype
Global BakaShrot_PushMessageTo.BakaShrot_PushMessageTo_Prototype
Global BakaShrot_GetLatestMessage.BakaShrot_GetLatestMessage_Prototype
Global BakaShrot_GetLatestMessageOf.BakaShrot_GetLatestMessageOf_Prototype
Global BakaShrot_GetMessageId.BakaShrot_GetMessageId_Prototype
Global BakaShrot_GetMessagePushedAt.BakaShrot_GetMessagePushedAt_Prototype
Global BakaShrot_GetMessageData.BakaShrot_GetMessageData_Prototype
Global BakaShrot_GetMessageTopicId.BakaShrot_GetMessageTopicId_Prototype
Global BakaShrot_GetMessageNodeId.BakaShrot_GetMessageNodeId_Prototype
Global BakaShrot_GetMessageTopic.BakaShrot_GetMessageTopic_Prototype
Global BakaShrot_GetMessageNode.BakaShrot_GetMessageNode_Prototype
Global BakaShrot_ResolveTopic.BakaShrot_ResolveTopic_Prototype
Global BakaShrot_ResolveNode.BakaShrot_ResolveNode_Prototype
Global BakaShrot_GetResolvedName.BakaShrot_GetResolvedName_Prototype
Global BakaShrot_ListTopics.BakaShrot_ListTopics_Prototype
Global BakaShrot_ListNodes.BakaShrot_ListNodes_Prototype
Global BakaShrot_GetNamesList.BakaShrot_GetNamesList_Prototype
Global BakaShrot_GetRefusalReason.BakaShrot_GetRefusalReason_Prototype
Global BakaShrot_GetLastError.BakaShrot_GetLastError_Prototype
Global BakaShrot_Query.BakaShrot_Query_Prototype
Global BakaShrot_GetQueryResult.BakaShrot_GetQueryResult_Prototype
Global BakaShrot_GetMessages.BakaShrot_GetMessages_Prototype
Global BakaShrot_GetMessageCount.BakaShrot_GetMessageCount_Prototype
Global BakaShrot_SelectMessage.BakaShrot_SelectMessage_Prototype
Global BakaShrot_HasMoreMessages.BakaShrot_HasMoreMessages_Prototype
Global BakaShrot_PushMessageWithFile.BakaShrot_PushMessageWithFile_Prototype
Global BakaShrot_PushMessageWithData.BakaShrot_PushMessageWithData_Prototype
Global BakaShrot_SaveAttachment.BakaShrot_SaveAttachment_Prototype
Global BakaShrot_LoadAttachment.BakaShrot_LoadAttachment_Prototype
Global BakaShrot_GetAttachmentData.BakaShrot_GetAttachmentData_Prototype
Global BakaShrot_FreeAttachmentData.BakaShrot_FreeAttachmentData_Prototype
Global BakaShrot_GetMessageAttachmentSize.BakaShrot_GetMessageAttachmentSize_Prototype
Global BakaShrot_IsMessageAttachmentReady.BakaShrot_IsMessageAttachmentReady_Prototype
Global BakaShrot_ClientLibrary.i = 0
; Unloads the DLL loaded by BakaShrot_LoadClient().
Procedure BakaShrot_UnloadClient()
If BakaShrot_ClientLibrary
CloseLibrary(BakaShrot_ClientLibrary)
BakaShrot_ClientLibrary = 0
EndIf
EndProcedure
; Loads the DLL at DllPath and fills the function pointers above.
; Returns #False if the DLL can't be loaded or a function is missing.
Procedure.i BakaShrot_LoadClient(DllPath.s)
If BakaShrot_ClientLibrary
ProcedureReturn #False
EndIf
BakaShrot_ClientLibrary = OpenLibrary(#PB_Any, DllPath)
If Not BakaShrot_ClientLibrary
ProcedureReturn #False
EndIf
; PureBasic strings are UTF-16, so the W variants are used.
BakaShrot_SetPrivateKey = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_SetPrivateKeyW")
BakaShrot_SetPublicKey = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_SetPublicKeyW")
BakaShrot_SetServerPublicKey = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_SetServerPublicKeyW")
BakaShrot_SetNodeId = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_SetNodeId")
BakaShrot_SetNode = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_SetNodeW")
BakaShrot_Connect = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_ConnectW")
BakaShrot_IsConnected = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_IsConnected")
BakaShrot_Disconnect = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_Disconnect")
BakaShrot_PushMessage = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_PushMessageW")
BakaShrot_GetLatestMessage = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetLatestMessage")
BakaShrot_GetMessageId = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetMessageId")
BakaShrot_GetMessagePushedAt = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetMessagePushedAt")
BakaShrot_GetMessageData = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetMessageDataW")
BakaShrot_GetRefusalReason = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetRefusalReasonW")
BakaShrot_GetLastError = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetLastError")
BakaShrot_Query = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_QueryW")
BakaShrot_GetQueryResult = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetQueryResultW")
BakaShrot_PushMessageTo = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_PushMessageToW")
BakaShrot_GetLatestMessageOf = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetLatestMessageOfW")
BakaShrot_GetMessageTopicId = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetMessageTopicId")
BakaShrot_GetMessageNodeId = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetMessageNodeId")
BakaShrot_GetMessageTopic = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetMessageTopicW")
BakaShrot_GetMessageNode = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetMessageNodeW")
BakaShrot_ResolveTopic = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_ResolveTopicW")
BakaShrot_ResolveNode = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_ResolveNodeW")
BakaShrot_GetResolvedName = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetResolvedNameW")
BakaShrot_ListTopics = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_ListTopics")
BakaShrot_ListNodes = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_ListNodes")
BakaShrot_GetNamesList = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetNamesListW")
BakaShrot_GetMessages = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetMessagesW")
BakaShrot_GetMessageCount = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetMessageCount")
BakaShrot_SelectMessage = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_SelectMessage")
BakaShrot_HasMoreMessages = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_HasMoreMessages")
BakaShrot_PushMessageWithFile = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_PushMessageWithFileW")
BakaShrot_PushMessageWithData = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_PushMessageWithDataW")
BakaShrot_SaveAttachment = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_SaveAttachmentW")
BakaShrot_LoadAttachment = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_LoadAttachmentW")
BakaShrot_GetAttachmentData = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetAttachmentData")
BakaShrot_FreeAttachmentData = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_FreeAttachmentData")
BakaShrot_GetMessageAttachmentSize = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetMessageAttachmentSize")
BakaShrot_IsMessageAttachmentReady = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_IsMessageAttachmentReady")
If Not BakaShrot_SetPrivateKey Or Not BakaShrot_SetPublicKey Or Not BakaShrot_SetServerPublicKey Or Not BakaShrot_SetNodeId Or Not BakaShrot_Connect Or Not BakaShrot_IsConnected Or Not BakaShrot_Disconnect
BakaShrot_UnloadClient()
ProcedureReturn #False
EndIf
If Not BakaShrot_PushMessage Or Not BakaShrot_GetLatestMessage Or Not BakaShrot_GetMessageId Or Not BakaShrot_GetMessagePushedAt Or Not BakaShrot_GetMessageData Or Not BakaShrot_GetRefusalReason Or Not BakaShrot_GetLastError
BakaShrot_UnloadClient()
ProcedureReturn #False
EndIf
If Not BakaShrot_Query Or Not BakaShrot_GetQueryResult
BakaShrot_UnloadClient()
ProcedureReturn #False
EndIf
If Not BakaShrot_SetNode Or Not BakaShrot_PushMessageTo Or Not BakaShrot_GetLatestMessageOf Or
Not BakaShrot_GetMessageTopicId Or Not BakaShrot_GetMessageNodeId Or Not BakaShrot_GetMessageTopic Or Not BakaShrot_GetMessageNode Or
Not BakaShrot_ResolveTopic Or Not BakaShrot_ResolveNode Or Not BakaShrot_GetResolvedName Or
Not BakaShrot_ListTopics Or Not BakaShrot_ListNodes Or Not BakaShrot_GetNamesList
BakaShrot_UnloadClient()
ProcedureReturn #False
EndIf
If Not BakaShrot_GetMessages Or Not BakaShrot_GetMessageCount Or Not BakaShrot_SelectMessage Or Not BakaShrot_HasMoreMessages
BakaShrot_UnloadClient()
ProcedureReturn #False
EndIf
If Not BakaShrot_PushMessageWithFile Or Not BakaShrot_PushMessageWithData Or Not BakaShrot_SaveAttachment Or Not BakaShrot_LoadAttachment Or Not BakaShrot_GetAttachmentData Or Not BakaShrot_FreeAttachmentData Or Not BakaShrot_GetMessageAttachmentSize Or Not BakaShrot_IsMessageAttachmentReady
BakaShrot_UnloadClient()
ProcedureReturn #False
EndIf
ProcedureReturn #True
EndProcedure
; BakaShrot_GetMessageData() as a string, asks for the size, then copies.
Procedure.s BakaShrot_GetMessageDataString()
Protected *Buffer, BufferSize.i, Text.s
BufferSize = BakaShrot_GetMessageData(0, 0)
*Buffer = AllocateMemory(BufferSize)
If Not *Buffer
ProcedureReturn ""
EndIf
BakaShrot_GetMessageData(*Buffer, BufferSize)
Text = PeekS(*Buffer, -1, #PB_Unicode)
FreeMemory(*Buffer)
ProcedureReturn Text
EndProcedure
; BakaShrot_GetQueryResult() as a string, asks for the size, then copies.
Procedure.s BakaShrot_GetQueryResultString()
Protected *Buffer, BufferSize.i, Text.s
BufferSize = BakaShrot_GetQueryResult(0, 0)
*Buffer = AllocateMemory(BufferSize)
If Not *Buffer
ProcedureReturn ""
EndIf
BakaShrot_GetQueryResult(*Buffer, BufferSize)
Text = PeekS(*Buffer, -1, #PB_Unicode)
FreeMemory(*Buffer)
ProcedureReturn Text
EndProcedure
; Calls a string getter of the DLL (*Getter(*Buffer, BufferSize)) and
; returns the string: asks for the size, then copies.
PrototypeC.i BakaShrot_StringGetter_Prototype(*Buffer, BufferSize.i)
Procedure.s BakaShrot_GetString(Getter.BakaShrot_StringGetter_Prototype)
Protected *Buffer, BufferSize.i, Text.s
BufferSize = Getter(0, 0)
*Buffer = AllocateMemory(BufferSize)
If Not *Buffer
ProcedureReturn ""
EndIf
Getter(*Buffer, BufferSize)
Text = PeekS(*Buffer, -1, #PB_Unicode)
FreeMemory(*Buffer)
ProcedureReturn Text
EndProcedure
; BakaShrot_GetMessageTopic/Node() and BakaShrot_GetResolvedName() as strings.
Procedure.s BakaShrot_GetMessageTopicString()
ProcedureReturn BakaShrot_GetString(BakaShrot_GetMessageTopic)
EndProcedure
Procedure.s BakaShrot_GetMessageNodeString()
ProcedureReturn BakaShrot_GetString(BakaShrot_GetMessageNode)
EndProcedure
Procedure.s BakaShrot_GetResolvedNameString()
ProcedureReturn BakaShrot_GetString(BakaShrot_GetResolvedName)
EndProcedure
Procedure.s BakaShrot_GetNamesListString()
ProcedureReturn BakaShrot_GetString(BakaShrot_GetNamesList)
EndProcedure
; BakaShrot_GetRefusalReason() as a string, asks for the size, then copies.
Procedure.s BakaShrot_GetRefusalReasonString()
Protected *Buffer, BufferSize.i, Text.s
BufferSize = BakaShrot_GetRefusalReason(0, 0)
*Buffer = AllocateMemory(BufferSize)
If Not *Buffer
ProcedureReturn ""
EndIf
BakaShrot_GetRefusalReason(*Buffer, BufferSize)
Text = PeekS(*Buffer, -1, #PB_Unicode)
FreeMemory(*Buffer)
ProcedureReturn Text
EndProcedure
; Usage example. Only compiled when this file is run directly (F5 in the
; IDE), not when it's included by an app.
; Connects with the identity from the client.ini that Build.ps1 generates,
; run it from the Build folder while BakaShrot_Server.exe is running.
CompilerIf #PB_Compiler_IsMainFile
Define PrivateKey.s, PublicKey.s, ServerPublicKey.s, Node.s, ServerHost.s, ServerPort.l
OpenConsole()
If Not OpenPreferences("client.ini")
PrintN("Failed to open client.ini")
End 1
EndIf
PreferenceGroup("BakaShrot")
PrivateKey = ReadPreferenceString("PrivateKey", "")
PublicKey = ReadPreferenceString("PublicKey", "")
ServerPublicKey = ReadPreferenceString("ServerPublicKey", "")
Node = ReadPreferenceString("Node", ReadPreferenceString("NodeId", ""))
ServerHost = ReadPreferenceString("ServerHost", "")
ServerPort = ReadPreferenceLong("ServerPort", 0)
ClosePreferences()
If Not BakaShrot_LoadClient("BakaShrot_Client.dll")
PrintN("Failed to load BakaShrot_Client.dll")
End 1
EndIf
If Not BakaShrot_SetPrivateKey(PrivateKey)
PrintN("Failed to set the private key")
End 1
EndIf
If Not BakaShrot_SetPublicKey(PublicKey)
PrintN("Failed to set the public key")
End 1
EndIf
If Not BakaShrot_SetServerPublicKey(ServerPublicKey)
PrintN("Failed to set the server's public key")
End 1
EndIf
If Not BakaShrot_SetNode(Node)
PrintN("Failed to set the node")
End 1
EndIf
If Not BakaShrot_Connect(ServerHost, ServerPort)
PrintN("Failed to connect and authenticate to " + ServerHost + ":" + Str(ServerPort))
End 1
EndIf
PrintN("Connected and authenticated to " + ServerHost + ":" + Str(ServerPort))
Delay(500)
PrintN("IsConnected: " + Str(BakaShrot_IsConnected()))
BakaShrot_Disconnect()
PrintN("IsConnected after disconnecting: " + Str(BakaShrot_IsConnected()))
BakaShrot_UnloadClient()
End 0
CompilerEndIf
+145
View File
@@ -0,0 +1,145 @@
;{- Code Header
; ==- Basic Info -================================
; Name: BakaShrot_ErrorCodes.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; BakaShrot error codes
;
; What BakaShrot_GetLastError() returns after a failed call of the client DLL
; (BakaShrot_Client.pbi), and the code a server sends with each refusal
; (RequestRefused, protocol 6). The Python client has the same numbers in
; bakashrot.ErrorCode. Shipped next to BakaShrot_Client_Prototypes.pbi,
; which includes it.
;
; 0 no error (the last call succeeded)
; 1-99 refused by the server: the connection is still open, see
; BakaShrot_GetRefusalReason() for the details
; 100+ the client's own: the connection, the arguments, the files
;
; What to do about each:
; reconnect, then retry: NotConnected, ConnectFailed, ConnectionLost,
; ProtocolError (the connection is closed)
; retry later: NotReady (an attachment still on its way),
; ServerError (the server's storage failed)
; fix the config: AuthRejected, ServerNotVerified, NotAllowed,
; UnknownName, NoDefaultTopic
; fix the call: InvalidArgument, InvalidRequest, TooBig,
; QueryFailed, FileError
; gone, or not yet there: NotFound
; sent again by itself: DataMismatch (an upload that doesn't match its
; SHA-256: upload it again), AttachmentMismatch (a
; downloaded one that doesn't: read it again)
;
; A push whose answer was lost (ConnectionLost) may still have been stored:
; pushing it again can store it twice, under the next id. Delivery is at
; least once; check the latest message first if a duplicate matters.
; ============================================================================
; --- Refused by the server (RequestRefused's Code) ----------------------------
; Not allowed to this client: AllowRead / AllowWrite / AllowQuery, its
; PushTopics / ReadTopics, or a request only peers may make.
#BakaShrot_Refused_NotAllowed = 1
; A topic or node name (or id) this server doesn't know.
#BakaShrot_Refused_UnknownName = 2
; No such message, attachment or upload.
#BakaShrot_Refused_NotFound = 3
; The attachment isn't on this server yet (still being replicated).
#BakaShrot_Refused_NotReady = 4
; A message, attachment or query result over a limit, or an attachment
; bigger than this server keeps.
#BakaShrot_Refused_TooBig = 5
; A push without a topic, and no DefaultTopic for this client.
#BakaShrot_Refused_NoDefaultTopic = 6
; A request that doesn't fit: parts out of order, an upload for another
; topic or already attached, a part that doesn't exist...
#BakaShrot_Refused_InvalidRequest = 7
; An uploaded attachment that doesn't match its SHA-256: dropped.
#BakaShrot_Refused_DataMismatch = 8
; The SQL of a query failed (its error in the reason).
#BakaShrot_Refused_QueryFailed = 9
; The server couldn't store or read something: its database failed.
#BakaShrot_Refused_ServerError = 10
; The highest a refusal can have, anything above is the client's own.
#BakaShrot_Refused_Max = 99
; --- The client's own (BakaShrot_GetLastError()) --------------------------------
#BakaShrot_Error_None = 0
; Not connected: never, or the connection was closed or lost before.
#BakaShrot_Error_NotConnected = 100
; The server couldn't be reached at that host and port.
#BakaShrot_Error_ConnectFailed = 101
; The server closed the connection during the handshake: wrong
; ServerPublicKey, a key or node it doesn't allow, or another protocol
; version (its log says which).
#BakaShrot_Error_AuthRejected = 102
; The server couldn't prove it holds ServerPublicKey's private key.
#BakaShrot_Error_ServerNotVerified = 103
; The connection broke during a request (it's closed now). A push may
; still have been stored.
#BakaShrot_Error_ConnectionLost = 104
; The server answered something unexpected or malformed: the connection is
; closed.
#BakaShrot_Error_ProtocolError = 105
; A bad argument: a ref that's neither a name nor an id, a null pointer, a
; message or attachment over the limits, a setting missing before connecting.
#BakaShrot_Error_InvalidArgument = 106
; A file couldn't be opened, read or written.
#BakaShrot_Error_FileError = 107
; A downloaded attachment doesn't match its SHA-256.
#BakaShrot_Error_AttachmentMismatch = 108
; Already connected: disconnect first.
#BakaShrot_Error_AlreadyConnected = 109
; Out of memory, or another failure inside the client.
#BakaShrot_Error_Internal = 110
; The name of an error code, as the constants have it ("NotFound"), or
; "Error <code>" for an unknown one.
Procedure.s BakaShrot_ErrorName(Code.l)
Select Code
Case #BakaShrot_Error_None : ProcedureReturn "None"
Case #BakaShrot_Refused_NotAllowed : ProcedureReturn "NotAllowed"
Case #BakaShrot_Refused_UnknownName : ProcedureReturn "UnknownName"
Case #BakaShrot_Refused_NotFound : ProcedureReturn "NotFound"
Case #BakaShrot_Refused_NotReady : ProcedureReturn "NotReady"
Case #BakaShrot_Refused_TooBig : ProcedureReturn "TooBig"
Case #BakaShrot_Refused_NoDefaultTopic : ProcedureReturn "NoDefaultTopic"
Case #BakaShrot_Refused_InvalidRequest : ProcedureReturn "InvalidRequest"
Case #BakaShrot_Refused_DataMismatch : ProcedureReturn "DataMismatch"
Case #BakaShrot_Refused_QueryFailed : ProcedureReturn "QueryFailed"
Case #BakaShrot_Refused_ServerError : ProcedureReturn "ServerError"
Case #BakaShrot_Error_NotConnected : ProcedureReturn "NotConnected"
Case #BakaShrot_Error_ConnectFailed : ProcedureReturn "ConnectFailed"
Case #BakaShrot_Error_AuthRejected : ProcedureReturn "AuthRejected"
Case #BakaShrot_Error_ServerNotVerified : ProcedureReturn "ServerNotVerified"
Case #BakaShrot_Error_ConnectionLost : ProcedureReturn "ConnectionLost"
Case #BakaShrot_Error_ProtocolError : ProcedureReturn "ProtocolError"
Case #BakaShrot_Error_InvalidArgument : ProcedureReturn "InvalidArgument"
Case #BakaShrot_Error_FileError : ProcedureReturn "FileError"
Case #BakaShrot_Error_AttachmentMismatch : ProcedureReturn "AttachmentMismatch"
Case #BakaShrot_Error_AlreadyConnected : ProcedureReturn "AlreadyConnected"
Case #BakaShrot_Error_Internal : ProcedureReturn "Internal"
EndSelect
ProcedureReturn "Error " + Str(Code)
EndProcedure
; #True for a code a server sends with a refusal (1-99).
Procedure.i BakaShrot_IsRefusalCode(Code.l)
ProcedureReturn Bool(Code >= 1 And Code <= #BakaShrot_Refused_Max)
EndProcedure
+4
View File
@@ -0,0 +1,4 @@
client should be a DLL that can connect in the back.
And it should provide functions to the caller that lets it query or do shit on the server.
When saying server, it will usually be a local process.
View File
+255
View File
@@ -0,0 +1,255 @@
;{- Code Header
; ==- Basic Info -================================
; Name: Cipher.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; BakaShrot Cipher
;
; Encrypts and authenticates buffers with a shared key, and checks and
; decrypts them, so the rest of the code never touches the crypto: give it
; a key once, then hand it buffers.
;
; Cipher.BakaShrot_Cipher
; BakaShrot_Cipher_Init(@Cipher, *Key, #BakaShrot_Cipher_Client)
; *Sealed = BakaShrot_Cipher_Encrypt(@Cipher, *Packet, PacketSize, @SealedSize)
; ... send it, and on the other end, with a cipher for #BakaShrot_Cipher_Server:
; *Packet = BakaShrot_Cipher_Decrypt(@Cipher, *Sealed, SealedSize, @PacketSize)
; If Not *Packet : abort the connection : EndIf
; BakaShrot_Cipher_Clear(@Cipher) once done, wipes the keys.
;
; What it guarantees, for buffers sent in order over one connection (TCP):
; - Nobody without the key can read them (XChaCha20).
; - Nobody without the key can change, forge or truncate one (Poly1305):
; decrypting it fails.
; - Nobody can replay, reorder, drop or reflect one: each buffer carries
; its sequence number, the receiver only takes the next one it expects,
; and each direction encrypts under its own nonces (or its own key), so
; a buffer sent back to its sender doesn't decrypt either.
; Any failure means the stream can't be trusted anymore: abort the
; connection, don't try the next buffer.
;
; What it doesn't do: get the key. Both ends must already share it, agreed
; on for this connection only (Session.pbi does it for the handshake), never
; a key reused across connections: the sequence numbers start over at 0.
;
; A sealed buffer is:
; [sequence number, 8 bytes, little-endian][encrypted data][tag, 16 bytes]
; #BakaShrot_Cipher_Overhead bytes more than the data. The nonce (24 bytes)
; is the direction (1 byte), zeros, then the sequence number, never sent.
; The sequence number is authenticated too (additional data).
;
; libsodium's crypto_aead_xchacha20poly1305_ietf_*, imported in
; Libsodium.pbi: nothing here implements a primitive. InitCryptography()
; must have been called.
;
; Threads: encrypting and decrypting use separate state, so one thread may
; send while another receives. Two threads must not encrypt (or decrypt)
; with the same cipher at once.
; ============================================================================
XIncludeFile "Libsodium.pbi"
#BakaShrot_Cipher_KeySize = #BakaShrot_XChaCha20Poly1305_KeySize
#BakaShrot_Cipher_SequenceSize = 8
#BakaShrot_Cipher_Overhead = #BakaShrot_Cipher_SequenceSize + #BakaShrot_XChaCha20Poly1305_TagSize
; Which end of the connection a cipher is on, when both share one key: each
; encrypts under its own nonces. Never 0.
#BakaShrot_Cipher_Client = 1
#BakaShrot_Cipher_Server = 2
; Past this many buffers in one direction, encrypting refuses: never reached
; in practice (2^63), but a sequence number must never wrap around.
#BakaShrot_Cipher_MaxSequence = $7FFFFFFFFFFFFFFF
Structure BakaShrot_CipherNonce
Bytes.a[#BakaShrot_XChaCha20Poly1305_NonceSize]
EndStructure
Structure BakaShrot_Cipher
SendKey.a[#BakaShrot_Cipher_KeySize]
ReceiveKey.a[#BakaShrot_Cipher_KeySize]
; First byte of the nonces of each direction.
SendDirection.a
ReceiveDirection.a
; Sequence number of the next buffer to send, and of the next one
; expected.
SendSequence.q
ReceiveSequence.q
IsReady.l
EndStructure
; Fills *Key (#BakaShrot_Cipher_KeySize bytes) with a new random key.
Procedure BakaShrot_Cipher_GenerateKey(*Key)
crypto_aead_xchacha20poly1305_ietf_keygen(*Key)
EndProcedure
; Wipes *Cipher's keys and state, it refuses everything until initialized
; again. Call it once the connection is over.
Procedure BakaShrot_Cipher_Clear(*Cipher.BakaShrot_Cipher)
sodium_memzero(*Cipher, SizeOf(BakaShrot_Cipher))
EndProcedure
; Sets *Cipher up with one key shared by both ends (*Key,
; #BakaShrot_Cipher_KeySize bytes, copied), Role being which end this is:
; #BakaShrot_Cipher_Client or #BakaShrot_Cipher_Server, the other end must
; take the other one.
; Returns #False if Role isn't one of them.
Procedure.i BakaShrot_Cipher_Init(*Cipher.BakaShrot_Cipher, *Key, Role.i)
BakaShrot_Cipher_Clear(*Cipher)
If Not *Key Or (Role <> #BakaShrot_Cipher_Client And Role <> #BakaShrot_Cipher_Server)
ProcedureReturn #False
EndIf
CopyMemory(*Key, @*Cipher\SendKey[0], #BakaShrot_Cipher_KeySize)
CopyMemory(*Key, @*Cipher\ReceiveKey[0], #BakaShrot_Cipher_KeySize)
*Cipher\SendDirection = Role
If Role = #BakaShrot_Cipher_Client
*Cipher\ReceiveDirection = #BakaShrot_Cipher_Server
Else
*Cipher\ReceiveDirection = #BakaShrot_Cipher_Client
EndIf
*Cipher\IsReady = #True
ProcedureReturn #True
EndProcedure
; Sets *Cipher up with a key per direction (each #BakaShrot_Cipher_KeySize
; bytes, copied), like libsodium's crypto_kx_* gives: the other end's
; *SendKey is this one's *ReceiveKey.
; Returns #False if they're the same key: the two directions would then
; encrypt under the same nonces, use BakaShrot_Cipher_Init() for one key.
Procedure.i BakaShrot_Cipher_InitWithKeys(*Cipher.BakaShrot_Cipher, *SendKey, *ReceiveKey)
BakaShrot_Cipher_Clear(*Cipher)
If Not *SendKey Or Not *ReceiveKey Or CompareMemory(*SendKey, *ReceiveKey, #BakaShrot_Cipher_KeySize)
ProcedureReturn #False
EndIf
CopyMemory(*SendKey, @*Cipher\SendKey[0], #BakaShrot_Cipher_KeySize)
CopyMemory(*ReceiveKey, @*Cipher\ReceiveKey[0], #BakaShrot_Cipher_KeySize)
; Different keys already keep the directions apart.
*Cipher\SendDirection = 0
*Cipher\ReceiveDirection = 0
*Cipher\IsReady = #True
ProcedureReturn #True
EndProcedure
; The nonce of the buffer with that direction and sequence number.
Procedure BakaShrot_Cipher_MakeNonce(*Nonce.BakaShrot_CipherNonce, Direction.a, Sequence.q)
FillMemory(*Nonce, #BakaShrot_XChaCha20Poly1305_NonceSize, 0)
*Nonce\Bytes[0] = Direction
PokeQ(@*Nonce\Bytes[#BakaShrot_XChaCha20Poly1305_NonceSize - 8], Sequence)
EndProcedure
; Encrypts and authenticates *Data (Size bytes, may be 0) into *Sealed,
; which must have room for Size + #BakaShrot_Cipher_Overhead bytes and not
; overlap *Data. *Data is left untouched.
; Returns #False, writing nothing, if *Cipher isn't set up.
Procedure.i BakaShrot_Cipher_EncryptTo(*Cipher.BakaShrot_Cipher, *Data, Size.i, *Sealed)
Protected Nonce.BakaShrot_CipherNonce
If Not *Cipher\IsReady Or Not *Sealed Or Size < 0 Or (Size > 0 And Not *Data) Or *Cipher\SendSequence >= #BakaShrot_Cipher_MaxSequence
ProcedureReturn #False
EndIf
; libsodium wants a valid pointer even for no data.
If Size = 0
*Data = *Sealed
EndIf
PokeQ(*Sealed, *Cipher\SendSequence)
BakaShrot_Cipher_MakeNonce(@Nonce, *Cipher\SendDirection, *Cipher\SendSequence)
crypto_aead_xchacha20poly1305_ietf_encrypt(*Sealed + #BakaShrot_Cipher_SequenceSize, 0, *Data, Size,
*Sealed, #BakaShrot_Cipher_SequenceSize, 0, @Nonce, @*Cipher\SendKey[0])
*Cipher\SendSequence + 1
ProcedureReturn #True
EndProcedure
; Same, into a freshly allocated buffer of Size + #BakaShrot_Cipher_Overhead
; bytes, its size in *OutSize\i.
; Returns 0 if *Cipher isn't set up, or out of memory. The caller owns the
; returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_Cipher_Encrypt(*Cipher.BakaShrot_Cipher, *Data, Size.i, *OutSize.Integer)
Protected *Sealed
If Not *Cipher\IsReady Or Size < 0
ProcedureReturn 0
EndIf
*Sealed = AllocateMemory(Size + #BakaShrot_Cipher_Overhead, #PB_Memory_NoClear)
If Not *Sealed
ProcedureReturn 0
EndIf
If Not BakaShrot_Cipher_EncryptTo(*Cipher, *Data, Size, *Sealed)
FreeMemory(*Sealed)
ProcedureReturn 0
EndIf
*OutSize\i = Size + #BakaShrot_Cipher_Overhead
ProcedureReturn *Sealed
EndProcedure
; Checks and decrypts *Sealed (Size bytes, as BakaShrot_Cipher_Encrypt()
; made it on the other end) into a freshly allocated buffer, the data's size
; in *OutSize\i (0 or more, the buffer is at least 1 byte).
; Returns 0 if it isn't the next buffer expected (replayed, reordered, one
; missing), was tampered with, made with another key, sent by this end, or
; is too short; also if *Cipher isn't set up, or out of memory. Nothing
; changes then, but the connection can't be trusted anymore: abort it.
; The caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_Cipher_Decrypt(*Cipher.BakaShrot_Cipher, *Sealed, Size.i, *OutSize.Integer)
Protected *Data, DataSize.i, Nonce.BakaShrot_CipherNonce, Genuine.i
If Not *Cipher\IsReady Or Not *Sealed Or Size < #BakaShrot_Cipher_Overhead
ProcedureReturn 0
EndIf
; Only the next one: a replayed, reordered or missing buffer stops here.
If PeekQ(*Sealed) <> *Cipher\ReceiveSequence
ProcedureReturn 0
EndIf
DataSize = Size - #BakaShrot_Cipher_Overhead
If DataSize > 0
*Data = AllocateMemory(DataSize, #PB_Memory_NoClear)
Else
*Data = AllocateMemory(1)
EndIf
If Not *Data
ProcedureReturn 0
EndIf
BakaShrot_Cipher_MakeNonce(@Nonce, *Cipher\ReceiveDirection, *Cipher\ReceiveSequence)
Genuine = Bool(crypto_aead_xchacha20poly1305_ietf_decrypt(*Data, 0, 0, *Sealed + #BakaShrot_Cipher_SequenceSize, Size - #BakaShrot_Cipher_SequenceSize,
*Sealed, #BakaShrot_Cipher_SequenceSize, @Nonce, @*Cipher\ReceiveKey[0]) = 0)
If Not Genuine
FreeMemory(*Data)
ProcedureReturn 0
EndIf
*Cipher\ReceiveSequence + 1
*OutSize\i = DataSize
ProcedureReturn *Data
EndProcedure
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,345 @@
;{- Code Header
; ==- Basic Info -================================
; Name: Libsodium.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; BakaShrot Cryptography
;
; Ed25519 signatures via libsodium (this does NOT reimplement any
; cryptographic primitive).
;
; EncodeData signs a buffer with the sending node's own private key.
; DecodeData checks that signature against the claimed sender's public key.
; (Misnamed: they sign and verify, nothing is encoded or decoded.)
;
; The signatures prove each end's identity in the handshake. The sealed
; boxes, key exchange and XChaCha20-Poly1305 below encrypt the connections:
; Session.pbi and Cipher.pbi use them, nothing else should.
; What's done, what isn't, and the plan to abstract it:
; Design/Cryptography.md.
;
; Key material:
; - Public key: #BakaShrot_Ed25519_PublicKeySize (32) raw bytes.
; - Private key: #BakaShrot_Ed25519_PrivateKeySize (64) raw bytes.
; (libsodium's Ed25519 secret key already embeds the seed and the public
; key, which is why it is twice the size of the public key.)
; A node's private key lives in BakaShrot_CoreConfig\PrivateKey (Config.pbi);
; the public key it hands out to peers lives in each
; BakaShrot_PeerConfig\PublicKey. Both are stored as Base64 text in the ini
; file - see EncodeKeyToString()/DecodeKeyFromString() below.
;
; Setup required to build/run this:
; - Windows: the official libsodium MSVC release's dynamic build, extracted
; to Libs/libsodium/<x64|x86>/ by Build.ps1, and "libsodium.dll"
; alongside the executable.
; - Linux: libsodium-dev (Debian/Ubuntu) or libsodium-devel (Fedora)
; installed, so "-lsodium" resolves at link time and
; libsodium.so.* is available at runtime.
; libsodium itself is the same standard, audited library on both platforms,
; so signatures made on one are verifiable on the other without change.
; ============================================================================
#BakaShrot_Ed25519_PublicKeySize = 32
#BakaShrot_Ed25519_PrivateKeySize = 64
#BakaShrot_Ed25519_SignatureSize = 64
; XChaCha20-Poly1305 (IETF), libsodium's crypto_aead_xchacha20poly1305_ietf_*:
; encryption and authentication of a buffer with a shared key, used by
; Commons/Cryptography/Cipher.pbi.
#BakaShrot_XChaCha20Poly1305_KeySize = 32
#BakaShrot_XChaCha20Poly1305_NonceSize = 24
#BakaShrot_XChaCha20Poly1305_TagSize = 16
; X25519 (crypto_box_seal, crypto_kx_*): sealed Hellos and the key exchange,
; used by Commons/Cryptography/Session.pbi.
#BakaShrot_X25519_PublicKeySize = 32
#BakaShrot_X25519_SecretKeySize = 32
#BakaShrot_SealedBoxOverhead = 48
#BakaShrot_KxSessionKeySize = 32
; Windows: the dynamic build's import library, libsodium.dll must be next to
; the program. Both are extracted from Libs/libsodium-*-msvc.zip by Build.ps1.
CompilerIf #PB_Compiler_OS = #PB_OS_Windows And #PB_Compiler_Processor = #PB_Processor_x64
ImportC "../../Libs/libsodium/x64/libsodium.lib"
CompilerElseIf #PB_Compiler_OS = #PB_OS_Windows
ImportC "../../Libs/libsodium/x86/libsodium.lib"
CompilerElse
ImportC "-lsodium"
CompilerEndIf
; Must be called once (any number of extra calls are harmless) before any
; other function below is used. Returns 0 on success, 1 if it was already
; initialized, -1 if libsodium failed to self-check (e.g. no RNG available).
sodium_init.l()
; Fills *PublicKey (32 bytes) and *PrivateKey (64 bytes) with a fresh,
; cryptographically random Ed25519 keypair.
crypto_sign_keypair.l(*PublicKey, *PrivateKey)
; Writes a #BakaShrot_Ed25519_SignatureSize-byte signature of *Message
; (MessageLength bytes) to *Signature, made with *PrivateKey.
crypto_sign_detached.l(*Signature, *SignatureLength, *Message, MessageLength.q, *PrivateKey)
; Returns 0 if *Signature is a valid signature of *Message (MessageLength
; bytes) made by the holder of the private key matching *PublicKey;
; non-zero otherwise (forged, corrupted, or signed different data).
crypto_sign_verify_detached.l(*Signature, *Message, MessageLength.q, *PublicKey)
; Encrypts *Message (MessageLength bytes) into *Ciphertext (MessageLength +
; #BakaShrot_XChaCha20Poly1305_TagSize bytes, the tag at the end), with
; *Key (32 bytes) and *Nonce (24 bytes, never twice with the same key).
; *AdditionalData (AdLength bytes, may be 0) is authenticated, not
; encrypted. *Nsec is always 0. Always returns 0.
crypto_aead_xchacha20poly1305_ietf_encrypt.l(*Ciphertext, *CiphertextLength, *Message, MessageLength.q, *AdditionalData, AdLength.q, *Nsec, *Nonce, *Key)
; Checks and decrypts *Ciphertext (CiphertextLength bytes, tag included)
; into *Message (CiphertextLength - TagSize bytes). Returns 0 if it's
; genuine, -1 if it was tampered with, or made with another key, nonce or
; additional data: *Message must not be used then.
crypto_aead_xchacha20poly1305_ietf_decrypt.l(*Message, *MessageLength, *Nsec, *Ciphertext, CiphertextLength.q, *AdditionalData, AdLength.q, *Nonce, *Key)
; Fills *Key (32 bytes) with a random XChaCha20-Poly1305 key.
crypto_aead_xchacha20poly1305_ietf_keygen(*Key)
; Zeroes Length bytes at *Memory, in a way the compiler can't optimize out:
; for wiping keys.
sodium_memzero(*Memory, Length.i)
; Copies the public key embedded in *PrivateKey (64 bytes) into *PublicKey
; (32 bytes). Always returns 0.
crypto_sign_ed25519_sk_to_pk.l(*PublicKey, *PrivateKey)
; The X25519 key (32 bytes) matching an Ed25519 public key (32 bytes) or
; private key (64 bytes), so one identity key both signs and receives
; sealed boxes. The public one returns -1 if it isn't a valid key.
crypto_sign_ed25519_pk_to_curve25519.l(*X25519PublicKey, *Ed25519PublicKey)
crypto_sign_ed25519_sk_to_curve25519.l(*X25519SecretKey, *Ed25519PrivateKey)
; Encrypts *Message (MessageLength bytes) for the holder of *PublicKey
; (X25519) into *Ciphertext (MessageLength + 48 bytes), with a throwaway
; key pair: only *PublicKey's holder can open it, and it doesn't tell who
; sealed it. Returns 0, -1 on failure.
crypto_box_seal.l(*Ciphertext, *Message, MessageLength.q, *PublicKey)
; Opens *Ciphertext (CiphertextLength bytes) sealed for *PublicKey into
; *Message (CiphertextLength - 48 bytes). Returns 0, or -1 if it wasn't
; sealed for this key or was tampered with.
crypto_box_seal_open.l(*Message, *Ciphertext, CiphertextLength.q, *PublicKey, *SecretKey)
; Fills *PublicKey and *SecretKey (32 bytes each) with a fresh X25519 key
; pair, for one key exchange. Returns 0.
crypto_kx_keypair.l(*PublicKey, *SecretKey)
; Both ends of a key exchange get the same two 32-byte keys from their own
; key pair and the other end's public key: *Rx decrypts what this end
; receives, *Tx encrypts what it sends (the client's Tx is the server's
; Rx). Return -1 if the other end's public key isn't acceptable.
crypto_kx_client_session_keys.l(*Rx, *Tx, *ClientPublicKey, *ClientSecretKey, *ServerPublicKey)
crypto_kx_server_session_keys.l(*Rx, *Tx, *ServerPublicKey, *ServerSecretKey, *ClientPublicKey)
; SHA-256, a piece at a time: _init() a state (crypto_hash_sha256_statebytes()
; bytes), _update() it with each piece, _final() writes the 32-byte hash.
; For the attachments' checksums, see BakaShrot_Sha256_* below.
crypto_hash_sha256_statebytes.i()
crypto_hash_sha256_init.l(*State)
crypto_hash_sha256_update.l(*State, *Data, DataLength.q)
crypto_hash_sha256_final.l(*State, *Hash)
; SHA-256 of DataLength bytes at *Data in one go, the 32-byte hash into
; *Hash. Certificates' fingerprints and key ids (X509.pbi).
crypto_hash_sha256.l(*Hash, *Data, DataLength.q)
; Fills *Buffer with Size bytes from the OS's secure generator.
; Certificates' serial numbers.
randombytes_buf(*Buffer, Size.i)
; The Ed25519 key pair of a 32-byte seed, which is what PKCS#8 private
; key files hold, and the seed of a 64-byte private key. Both return 0.
crypto_sign_seed_keypair.l(*PublicKey, *PrivateKey, *Seed)
crypto_sign_ed25519_sk_to_seed.l(*Seed, *PrivateKey)
; Base64 (Variant #BakaShrot_Base64_Original for PEM), constant-time.
; _encoded_len() is the size *Base64 needs, terminator included.
; bin2base64 writes a terminated ASCII string, returns *Base64.
; base642bin skips the characters of the ASCII string *Ignore (" \r\n"),
; and returns -1 if anything else isn't Base64 or *Binary is too small
; (*End = 0: all of it must decode). The size it wrote goes in *BinaryLength.
sodium_base64_encoded_len.i(BinaryLength.i, Variant.l)
sodium_bin2base64.i(*Base64, MaxLength.i, *Binary, BinaryLength.i, Variant.l)
sodium_base642bin.l(*Binary, MaxLength.i, *Base64, Base64Length.i, *Ignore, *BinaryLength, *End, Variant.l)
; Hex, lowercase, constant-time; same conventions as Base64 above.
sodium_bin2hex.i(*Hex, MaxLength.i, *Binary, BinaryLength.i)
sodium_hex2bin.l(*Binary, MaxLength.i, *Hex, HexLength.i, *Ignore, *BinaryLength, *End)
EndImport
; sodium_base64_VARIANT_ORIGINAL: the standard alphabet, with padding.
#BakaShrot_Base64_Original = 1
; Must be called once at startup, before GenerateKeyPair/EncodeData/DecodeData.
; Returns #False if libsodium could not initialize - treat that as fatal,
; there is no safe fallback to running without it.
Procedure.i InitCryptography()
ProcedureReturn Bool(sodium_init() >= 0)
EndProcedure
; Generates a new Ed25519 keypair for provisioning a node.
; *PublicKey must point to #BakaShrot_Ed25519_PublicKeySize bytes,
; *PrivateKey to #BakaShrot_Ed25519_PrivateKeySize bytes.
Procedure GenerateKeyPair(*PublicKey, *PrivateKey)
crypto_sign_keypair(*PublicKey, *PrivateKey)
EndProcedure
; Fills *PublicKey (#BakaShrot_Ed25519_PublicKeySize bytes) with the public
; key matching *PrivateKey (#BakaShrot_Ed25519_PrivateKeySize bytes), so a
; node only needs its private key in its config.
Procedure GetPublicKeyFromPrivateKey(*PrivateKey, *PublicKey)
crypto_sign_ed25519_sk_to_pk(*PublicKey, *PrivateKey)
EndProcedure
; Signs *Data (DataLength bytes) with *PrivateKey (this node's own private
; key, #BakaShrot_Ed25519_PrivateKeySize bytes).
; Writes the signature to *Signature, which must point to
; #BakaShrot_Ed25519_SignatureSize bytes. *Data itself is left untouched.
Procedure.i EncodeData(*Data, DataLength.i, *PrivateKey, *Signature)
Protected SignatureLength.q
ProcedureReturn Bool(crypto_sign_detached(*Signature, @SignatureLength, *Data, DataLength, *PrivateKey) = 0)
EndProcedure
; Verifies that *Signature (#BakaShrot_Ed25519_SignatureSize bytes) is a
; valid signature of *Data (DataLength bytes), made by the holder of the
; private key matching *PublicKey (the claimed sender's public key, from
; BakaShrot_PeerConfig\PublicKey).
; Returns #True only if the signature checks out. On #False, reject the
; packet outright - do not process it, do not fall back to trusting it.
Procedure.i DecodeData(*Data, DataLength.i, *PublicKey, *Signature)
ProcedureReturn Bool(crypto_sign_verify_detached(*Signature, *Data, DataLength, *PublicKey) = 0)
EndProcedure
; SHA-256 of data given a piece at a time (an attachment's parts): Start, Add
; each piece, then Finish writes the 32-byte hash.
#BakaShrot_Sha256_HashSize = 32
Structure BakaShrot_Sha256
; crypto_hash_sha256_state is 104 bytes, checked by Start.
State.a[128]
EndStructure
; Returns #False if libsodium's state doesn't fit (a libsodium change).
Procedure.i BakaShrot_Sha256_Start(*Hash.BakaShrot_Sha256)
If crypto_hash_sha256_statebytes() > SizeOf(BakaShrot_Sha256)
ProcedureReturn #False
EndIf
ProcedureReturn Bool(crypto_hash_sha256_init(*Hash) = 0)
EndProcedure
Procedure BakaShrot_Sha256_Add(*Hash.BakaShrot_Sha256, *Data, Size.i)
If Size > 0
crypto_hash_sha256_update(*Hash, *Data, Size)
EndIf
EndProcedure
Procedure BakaShrot_Sha256_Finish(*Hash.BakaShrot_Sha256, *Out)
crypto_hash_sha256_final(*Hash, *Out)
EndProcedure
; Encodes KeySize raw bytes at *Key as a Base64 string, for storing a key in
; the ini file (PrivateKey / PublicKey fields in Config.pbi).
Procedure.s EncodeKeyToString(*Key, KeySize.i)
ProcedureReturn Base64Encoder(*Key, KeySize)
EndProcedure
; Decodes KeyString back into KeySize raw bytes at *Key.
; Returns #False (and leaves *Key untouched) if KeyString is not valid
; Base64 or does not decode to exactly KeySize bytes - a malformed or
; truncated key in the config file must never be silently accepted as one
; that's merely different.
Procedure.i DecodeKeyFromString(KeyString.s, *Key, KeySize.i)
; PureBasic's own docs warn the output buffer must have some slack over
; the exact decoded size or the decoder can overflow it - at least 25%
; extra and never under 64 bytes, hence the margin below.
Protected *Buffer, BufferSize.i, DecodedSize.i
BufferSize = (KeySize * 5) / 4 + 64
*Buffer = AllocateMemory(BufferSize)
DecodedSize = Base64Decoder(KeyString, *Buffer, BufferSize)
If DecodedSize = KeySize
CopyMemory(*Buffer, *Key, KeySize)
EndIf
FreeMemory(*Buffer)
ProcedureReturn Bool(DecodedSize = KeySize)
EndProcedure
; Usage example. Only compiled when this file is run directly (F5 in the
; IDE), not when it's included as a module by the rest of the project.
CompilerIf #PB_Compiler_IsMainFile
If Not InitCryptography()
Debug "Failed to initialize libsodium."
Else
Define *PublicKey = AllocateMemory(#BakaShrot_Ed25519_PublicKeySize)
Define *PrivateKey = AllocateMemory(#BakaShrot_Ed25519_PrivateKeySize)
Define *Signature = AllocateMemory(#BakaShrot_Ed25519_SignatureSize)
Define Message.s = ~"{\"messageData\": {\"MsgType\": \"hello\"}}"
Define MessageLength = StringByteLength(Message, #PB_Ascii)
Define *MessageBytes = AllocateMemory(MessageLength)
PokeS(*MessageBytes, Message, -1, #PB_Ascii)
GenerateKeyPair(*PublicKey, *PrivateKey)
Debug "PublicKey: " + EncodeKeyToString(*PublicKey, #BakaShrot_Ed25519_PublicKeySize)
Debug "PrivateKey: " + EncodeKeyToString(*PrivateKey, #BakaShrot_Ed25519_PrivateKeySize)
If EncodeData(*MessageBytes, MessageLength, *PrivateKey, *Signature)
Debug "Signed ok. Signature: " + EncodeKeyToString(*Signature, #BakaShrot_Ed25519_SignatureSize)
If DecodeData(*MessageBytes, MessageLength, *PublicKey, *Signature)
Debug "Verified ok, as expected."
Else
Debug "FAILED to verify a genuine signature - something is broken."
EndIf
; Tamper with one byte and make sure verification then rejects it.
PokeB(*MessageBytes, PeekB(*MessageBytes) ! 1)
If DecodeData(*MessageBytes, MessageLength, *PublicKey, *Signature)
Debug "FAILED: tampered data was accepted as genuine."
Else
Debug "Tampered data correctly rejected."
EndIf
Else
Debug "Failed to sign data."
EndIf
FreeMemory(*PublicKey)
FreeMemory(*PrivateKey)
FreeMemory(*Signature)
FreeMemory(*MessageBytes)
EndIf
CompilerEndIf
+203
View File
@@ -0,0 +1,203 @@
;{- Code Header
; ==- Basic Info -================================
; Name: Session.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; BakaShrot Session
;
; The handshake's cryptography, so the connections only call these
; (the handshake itself is in Commons/Networking/Connections.pbi):
;
; - The Hello is sealed for the server's identity key: crypto_box_seal,
; for the X25519 key matching the server's Ed25519 one. Only that
; server can read it, and someone watching doesn't learn who connects.
; BakaShrot_Session_SealHello() / _OpenHello().
; - Each end makes a key pair for this one connection (crypto_kx). The
; client's public half travels in the sealed Hello, the server's in the
; ChallengeRequest; both ends sign them with their identity keys
; (Connections.pbi), so nobody in the middle can swap them.
; BakaShrot_Session_NewKeyPair().
; - From its own pair and the other end's public half, each end gets a
; key per direction and sets its BakaShrot_Cipher (Cipher.pbi) up with
; them: every packet after the ChallengeRequest is encrypted.
; BakaShrot_Session_StartClient() / _StartServer().
;
; The key pair's secret and the derived keys are wiped once the cipher has
; them: a recorded connection can't be decrypted later, even with the
; identity keys (forward secrecy).
;
; libsodium does all of it (Libsodium.pbi), InitCryptography() must have
; been called.
; ============================================================================
XIncludeFile "Cipher.pbi"
#BakaShrot_Session_PublicKeySize = #BakaShrot_X25519_PublicKeySize
Structure BakaShrot_SessionKey
Bytes.a[32]
EndStructure
; One end's key pair for one connection.
Structure BakaShrot_SessionKeyPair
PublicKey.a[#BakaShrot_X25519_PublicKeySize]
SecretKey.a[#BakaShrot_X25519_SecretKeySize]
EndStructure
; A server's keys to open the Hellos sealed for it, from its Ed25519
; private key. Read-only once loaded, every client thread may use them.
Structure BakaShrot_HelloKeys
PublicKey.a[#BakaShrot_X25519_PublicKeySize]
SecretKey.a[#BakaShrot_X25519_SecretKeySize]
EndStructure
Structure BakaShrot_SessionDirections
Rx.a[#BakaShrot_KxSessionKeySize]
Tx.a[#BakaShrot_KxSessionKeySize]
EndStructure
; Fills *Keys from *PrivateKey (Ed25519, #BakaShrot_Ed25519_PrivateKeySize
; bytes), for a server to open the Hellos sealed for its public key.
; Returns #False if it isn't a usable key.
Procedure.i BakaShrot_Session_LoadHelloKeys(*Keys.BakaShrot_HelloKeys, *PrivateKey)
Protected Ed25519PublicKey.BakaShrot_SessionKey, IsValid.i
crypto_sign_ed25519_sk_to_pk(@Ed25519PublicKey, *PrivateKey)
IsValid = Bool(crypto_sign_ed25519_pk_to_curve25519(@*Keys\PublicKey[0], @Ed25519PublicKey) = 0)
If IsValid
IsValid = Bool(crypto_sign_ed25519_sk_to_curve25519(@*Keys\SecretKey[0], *PrivateKey) = 0)
EndIf
If Not IsValid
sodium_memzero(*Keys, SizeOf(BakaShrot_HelloKeys))
EndIf
ProcedureReturn IsValid
EndProcedure
; Wipes *Keys.
Procedure BakaShrot_Session_ClearHelloKeys(*Keys.BakaShrot_HelloKeys)
sodium_memzero(*Keys, SizeOf(BakaShrot_HelloKeys))
EndProcedure
; Seals *Data (Size bytes, at least 1) for the server whose Ed25519 public
; key is *ServerPublicKey (#BakaShrot_Ed25519_PublicKeySize bytes), into a
; freshly allocated buffer of Size + #BakaShrot_SealedBoxOverhead bytes,
; its size in *OutSize\i.
; Returns 0 if *ServerPublicKey isn't a valid key, or out of memory. The
; caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_Session_SealHello(*ServerPublicKey, *Data, Size.i, *OutSize.Integer)
Protected BoxPublicKey.BakaShrot_SessionKey, *Sealed
If Not *ServerPublicKey Or Not *Data Or Size < 1
ProcedureReturn 0
EndIf
If crypto_sign_ed25519_pk_to_curve25519(@BoxPublicKey, *ServerPublicKey) <> 0
ProcedureReturn 0
EndIf
*Sealed = AllocateMemory(Size + #BakaShrot_SealedBoxOverhead, #PB_Memory_NoClear)
If Not *Sealed
ProcedureReturn 0
EndIf
If crypto_box_seal(*Sealed, *Data, Size, @BoxPublicKey) <> 0
FreeMemory(*Sealed)
ProcedureReturn 0
EndIf
*OutSize\i = Size + #BakaShrot_SealedBoxOverhead
ProcedureReturn *Sealed
EndProcedure
; Opens *Sealed (Size bytes), sealed by BakaShrot_Session_SealHello() for
; *Keys' server, into a freshly allocated buffer, its size in *OutSize\i.
; Returns 0 if it wasn't sealed for this server, was tampered with, is too
; short, or out of memory. The caller owns the returned buffer - free it
; with FreeMemory.
Procedure.i BakaShrot_Session_OpenHello(*Keys.BakaShrot_HelloKeys, *Sealed, Size.i, *OutSize.Integer)
Protected *Data, DataSize.i
If Not *Sealed Or Size <= #BakaShrot_SealedBoxOverhead
ProcedureReturn 0
EndIf
DataSize = Size - #BakaShrot_SealedBoxOverhead
*Data = AllocateMemory(DataSize, #PB_Memory_NoClear)
If Not *Data
ProcedureReturn 0
EndIf
If crypto_box_seal_open(*Data, *Sealed, Size, @*Keys\PublicKey[0], @*Keys\SecretKey[0]) <> 0
FreeMemory(*Data)
ProcedureReturn 0
EndIf
*OutSize\i = DataSize
ProcedureReturn *Data
EndProcedure
; Fills *KeyPair with a fresh key pair, for one connection. Its PublicKey
; goes to the other end.
Procedure BakaShrot_Session_NewKeyPair(*KeyPair.BakaShrot_SessionKeyPair)
crypto_kx_keypair(@*KeyPair\PublicKey[0], @*KeyPair\SecretKey[0])
EndProcedure
; Wipes *KeyPair.
Procedure BakaShrot_Session_ClearKeyPair(*KeyPair.BakaShrot_SessionKeyPair)
sodium_memzero(*KeyPair, SizeOf(BakaShrot_SessionKeyPair))
EndProcedure
; Sets *Cipher up for the client's end of the connection, from the client's
; *KeyPair and the server's public half (*ServerSessionKey,
; #BakaShrot_Session_PublicKeySize bytes). *KeyPair is wiped either way.
; Returns #False if the server's half isn't acceptable: abort then.
Procedure.i BakaShrot_Session_StartClient(*Cipher.BakaShrot_Cipher, *KeyPair.BakaShrot_SessionKeyPair, *ServerSessionKey)
Protected Keys.BakaShrot_SessionDirections, IsReady.i
BakaShrot_Cipher_Clear(*Cipher)
If crypto_kx_client_session_keys(@Keys\Rx[0], @Keys\Tx[0], @*KeyPair\PublicKey[0], @*KeyPair\SecretKey[0], *ServerSessionKey) = 0
IsReady = BakaShrot_Cipher_InitWithKeys(*Cipher, @Keys\Tx[0], @Keys\Rx[0])
EndIf
sodium_memzero(@Keys, SizeOf(BakaShrot_SessionDirections))
BakaShrot_Session_ClearKeyPair(*KeyPair)
ProcedureReturn IsReady
EndProcedure
; Same for the server's end, from the server's *KeyPair and the client's
; public half (*ClientSessionKey).
Procedure.i BakaShrot_Session_StartServer(*Cipher.BakaShrot_Cipher, *KeyPair.BakaShrot_SessionKeyPair, *ClientSessionKey)
Protected Keys.BakaShrot_SessionDirections, IsReady.i
BakaShrot_Cipher_Clear(*Cipher)
If crypto_kx_server_session_keys(@Keys\Rx[0], @Keys\Tx[0], @*KeyPair\PublicKey[0], @*KeyPair\SecretKey[0], *ClientSessionKey) = 0
IsReady = BakaShrot_Cipher_InitWithKeys(*Cipher, @Keys\Tx[0], @Keys\Rx[0])
EndIf
sodium_memzero(@Keys, SizeOf(BakaShrot_SessionDirections))
BakaShrot_Session_ClearKeyPair(*KeyPair)
ProcedureReturn IsReady
EndProcedure
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,475 @@
;{- Code Header
; ==- Basic Info -================================
; Name: Connections.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; BakaShrot Connections
;
; What both ends need to keep track of a connection and authenticate it.
;
; Handshake, anything out of order or unexpected aborts the connection.
; The client must already know the server's public key (client.ini's
; ServerPublicKey, a peer section's PublicKey).
; C->S Hello Sealed for the server's public key, only it can
; read it (Session.pbi): the client's identity and
; public key, and the public half of its key pair
; for this connection.
; The server checks they're registered together.
; S->C ChallengeRequest In plain text: random challenge (Base64) and
; nonce, the public half of the server's key pair
; for this connection, and the server's signature
; of the handshake (BakaShrot_MakeHandshakeTranscript()).
; The client checks it with the server's public
; key: it's the right server, and nobody swapped
; the halves. Both ends now have this connection's
; keys, every packet from here on is encrypted
; (Cipher.pbi).
; C->S ChallengeResponse The client's signature of the handshake, and
; the nonce echoed back.
; S->C AuthAccepted The client is authenticated.
;
; Requests, only once authenticated, each one gets one answer:
; C->S PushMessage -> S->C MessagePushed or RequestRefused
; C->S GetLatestMessage -> S->C LatestMessage or RequestRefused
; C->S GetMessages -> S->C Messages (maybe none) or RequestRefused
; C->S QueryRequest -> S->C QueryResult or RequestRefused
; C->S ResolveName -> S->C NameResolved or RequestRefused
; C->S ListNames -> S->C NamesList
; C->S UploadStart -> S->C UploadStarted or RequestRefused
; C->S UploadChunk -> S->C ChunkStored or RequestRefused
; then a PushMessage with the UploadId attaches it to the message
; C->S GetAttachment -> S->C AttachmentChunk or RequestRefused
; Topics and nodes are given by name or id, see Names.pbi.
; A refusal keeps the connection open, a malformed or unexpected packet
; still aborts it.
;
; Replication, only from a peer (see Server/Networking/Peers.pbi), over the
; link it opened to the server:
; P->S SyncStateRequest -> S->P SyncState or RequestRefused
; P->S ReplicateMessages -> S->P MessagePushed (last id) or RequestRefused
; once the messages are caught up:
; P->S MissingAttachmentsRequest -> S->P MissingAttachments or RequestRefused
; P->S ReplicateAttachmentChunk -> S->P ChunkStored or RequestRefused
;
;
; Framing: every packet is sent as its size (4 bytes, little-endian),
; followed by the packet itself, so the receiver knows where it ends.
; Once the connection's cipher is set up, the packet is encrypted first
; (#BakaShrot_Cipher_Overhead bytes more), the size isn't: see
; BakaShrot_SendPacket() and BakaShrot_OpenFrame().
; Up to #BakaShrot_MaxHandshakePacketSize until the other end authenticated,
; then up to #BakaShrot_MaxPacketSize (BakaShrot_Inbox_Lift()): anyone can
; connect, only those with a key get to make the other end hold big frames.
; ============================================================================
XIncludeFile "../Cryptography/Session.pbi"
XIncludeFile "Packets/HelloPacket.pbi"
XIncludeFile "Packets/ChallengeRequestPacket.pbi"
XIncludeFile "Packets/ChallengeResponsePacket.pbi"
XIncludeFile "Packets/AuthAcceptedPacket.pbi"
XIncludeFile "Packets/PushMessagePacket.pbi"
XIncludeFile "Packets/MessagePushedPacket.pbi"
XIncludeFile "Packets/GetLatestMessagePacket.pbi"
XIncludeFile "Packets/LatestMessagePacket.pbi"
XIncludeFile "Packets/RequestRefusedPacket.pbi"
XIncludeFile "Packets/SyncStateRequestPacket.pbi"
XIncludeFile "Packets/SyncStatePacket.pbi"
XIncludeFile "Packets/ReplicateMessagesPacket.pbi"
XIncludeFile "Packets/QueryRequestPacket.pbi"
XIncludeFile "Packets/QueryResultPacket.pbi"
XIncludeFile "Packets/ResolveNamePacket.pbi"
XIncludeFile "Packets/NameResolvedPacket.pbi"
XIncludeFile "Packets/ListNamesPacket.pbi"
XIncludeFile "Packets/NamesListPacket.pbi"
XIncludeFile "Packets/GetMessagesPacket.pbi"
XIncludeFile "Packets/MessagesPacket.pbi"
XIncludeFile "Packets/UploadStartPacket.pbi"
XIncludeFile "Packets/UploadStartedPacket.pbi"
XIncludeFile "Packets/UploadChunkPacket.pbi"
XIncludeFile "Packets/ChunkStoredPacket.pbi"
XIncludeFile "Packets/GetAttachmentPacket.pbi"
XIncludeFile "Packets/AttachmentChunkPacket.pbi"
XIncludeFile "Packets/MissingAttachmentsRequestPacket.pbi"
XIncludeFile "Packets/MissingAttachmentsPacket.pbi"
XIncludeFile "Packets/ReplicateAttachmentChunkPacket.pbi"
; Reads the type of a received packet, to know which decoder to use.
; Returns #BakaShrot_PacketType_None if the packet's base fields are invalid.
Procedure.i BakaShrot_GetPacketType(*Packet, PacketSize.i)
Protected *View.MsgPackData, Base.BakaShrot_PacketBase, IsValid.i
*View = MsgPackWrapMsgBuffer(*Packet, PacketSize)
If Not *View
ProcedureReturn #BakaShrot_PacketType_None
EndIf
IsValid = BakaShrot_ReadPacketBase(@Base, *View)
MsgPackFree(*View, #False)
If Not IsValid
ProcedureReturn #BakaShrot_PacketType_None
EndIf
ProcedureReturn Base\PacketType
EndProcedure
Enumeration BakaShrot_ConnectionStatuses
; Connected, the Hello hasn't been sent/received yet.
#BakaShrot_ConnectionStatus_New
; The challenge was issued, its response hasn't been sent/received yet.
#BakaShrot_ConnectionStatus_Challenged
#BakaShrot_ConnectionStatus_Authenticated
#BakaShrot_ConnectionStatus_Disconnected
#BakaShrot_ConnectionStatus_Aborted
EndEnumeration
CompilerIf #BakaShrot_SessionKeySize <> #BakaShrot_Session_PublicKeySize Or #BakaShrot_HandshakeSignatureSize <> #BakaShrot_Ed25519_SignatureSize
CompilerError "Packets.pbi's handshake sizes don't match the cryptography's."
CompilerEndIf
Structure BakaShrot_ConnectionMetadata
Status.i
; Server side only, trusted once Status is Authenticated: the node from
; the Hello, and the default topic of its pushes from its client
; section's DefaultTopic (-1 without one: pushes must name their topic),
; both as the server's own ids.
DefaultTopicId.l
NodeId.u
; The client's Ed25519 public key, on both sides.
PublicKey.a[#BakaShrot_Ed25519_PublicKeySize]
; The server's Ed25519 public key, on both sides.
ServerPublicKey.a[#BakaShrot_Ed25519_PublicKeySize]
; TempKey to prevent replay attacks, fresh random data for every connection.
Challenge.a[#BakaShrot_ChallengeSize]
Nonce.a[#BakaShrot_NonceSize]
; Public halves of both ends' key pairs for this connection.
ClientSessionKey.a[#BakaShrot_SessionKeySize]
ServerSessionKey.a[#BakaShrot_SessionKeySize]
; Set up once both ends have their keys (after the ChallengeRequest),
; then every packet is encrypted with it. Wiped when the connection ends.
Cipher.BakaShrot_Cipher
EndStructure
; What each end signs: proves it holds its identity key, for this
; connection (the challenge, the nonce, both key pairs), to this other end.
; Label tells which end signed it, so one end's signature can't be sent
; back as the other's.
#BakaShrot_TranscriptLabelSize = 16
#BakaShrot_TranscriptServerLabel = "BakaShrot3 srv"
#BakaShrot_TranscriptClientLabel = "BakaShrot3 cli"
Structure BakaShrot_HandshakeTranscript
Label.a[#BakaShrot_TranscriptLabelSize]
ClientPublicKey.a[#BakaShrot_Ed25519_PublicKeySize]
ServerPublicKey.a[#BakaShrot_Ed25519_PublicKeySize]
ClientSessionKey.a[#BakaShrot_SessionKeySize]
ServerSessionKey.a[#BakaShrot_SessionKeySize]
Challenge.a[#BakaShrot_ChallengeSize]
Nonce.a[#BakaShrot_NonceSize]
EndStructure
Structure BakaShrot_ChallengeProof
Message.BakaShrot_HandshakeTranscript
Signature.a[#BakaShrot_Ed25519_SignatureSize]
EndStructure
; Fills *Proof\Message from *Metadata, as signed by one end: Label is
; #BakaShrot_TranscriptServerLabel or #BakaShrot_TranscriptClientLabel.
Procedure BakaShrot_MakeHandshakeTranscript(*Metadata.BakaShrot_ConnectionMetadata, Label.s, *Proof.BakaShrot_ChallengeProof)
FillMemory(@*Proof\Message, SizeOf(BakaShrot_HandshakeTranscript), 0)
PokeS(@*Proof\Message\Label[0], Label, #BakaShrot_TranscriptLabelSize - 1, #PB_Ascii)
CopyMemory(@*Metadata\PublicKey[0], @*Proof\Message\ClientPublicKey[0], #BakaShrot_Ed25519_PublicKeySize)
CopyMemory(@*Metadata\ServerPublicKey[0], @*Proof\Message\ServerPublicKey[0], #BakaShrot_Ed25519_PublicKeySize)
CopyMemory(@*Metadata\ClientSessionKey[0], @*Proof\Message\ClientSessionKey[0], #BakaShrot_SessionKeySize)
CopyMemory(@*Metadata\ServerSessionKey[0], @*Proof\Message\ServerSessionKey[0], #BakaShrot_SessionKeySize)
CopyMemory(@*Metadata\Challenge[0], @*Proof\Message\Challenge[0], #BakaShrot_ChallengeSize)
CopyMemory(@*Metadata\Nonce[0], @*Proof\Message\Nonce[0], #BakaShrot_NonceSize)
EndProcedure
; Signs *Proof\Message with *PrivateKey into *Proof\Signature.
Procedure.i BakaShrot_SignHandshake(*Proof.BakaShrot_ChallengeProof, *PrivateKey)
ProcedureReturn EncodeData(@*Proof\Message, SizeOf(BakaShrot_HandshakeTranscript), *PrivateKey, @*Proof\Signature[0])
EndProcedure
; #True if *Proof\Signature is *PublicKey's holder's signature of *Proof\Message.
Procedure.i BakaShrot_VerifyHandshake(*Proof.BakaShrot_ChallengeProof, *PublicKey)
ProcedureReturn DecodeData(@*Proof\Message, SizeOf(BakaShrot_HandshakeTranscript), *PublicKey, @*Proof\Signature[0])
EndProcedure
; Wipes what's secret in *Metadata, once the connection is over.
Procedure BakaShrot_ClearConnectionMetadata(*Metadata.BakaShrot_ConnectionMetadata)
BakaShrot_Cipher_Clear(@*Metadata\Cipher)
EndProcedure
; --- Framing -----------------------------------------------------------------
#BakaShrot_FrameHeaderSize = 4
; Biggest packet before the other end is authenticated. The handshake's are a
; few hundred bytes.
#BakaShrot_MaxHandshakePacketSize = 4096
; A buffer this big or more is freed once emptied, instead of kept for the
; next packets.
#BakaShrot_InboxKeptCapacity = 256 * 1024
; How long a send waits for the other end to make room, without a single
; byte going out, before it gives up. Same as how long a client waits for
; each packet (#BakaShrot_Outbound_Timeout).
#BakaShrot_SendStallTimeout = 10000
Enumeration BakaShrot_InboxResults
#BakaShrot_Inbox_Incomplete
#BakaShrot_Inbox_Packet
#BakaShrot_Inbox_Invalid
EndEnumeration
; Received data that hasn't been read as packets yet: Size bytes, from
; Buffer + Start.
Structure BakaShrot_Inbox
*Buffer
Start.i
Size.i
Capacity.i
; Biggest packet accepted: #BakaShrot_MaxHandshakePacketSize while 0,
; #BakaShrot_MaxPacketSize once lifted.
MaxPacketSize.i
EndStructure
; Biggest packet *Inbox accepts.
Procedure.i BakaShrot_Inbox_MaxPacketSize(*Inbox.BakaShrot_Inbox)
If *Inbox\MaxPacketSize
ProcedureReturn *Inbox\MaxPacketSize
EndIf
ProcedureReturn #BakaShrot_MaxHandshakePacketSize
EndProcedure
; Biggest amount of received data waiting to be read as packets, anything
; more aborts the connection: two of the biggest packets.
Procedure.i BakaShrot_Inbox_MaxSize(*Inbox.BakaShrot_Inbox)
ProcedureReturn 2 * (#BakaShrot_FrameHeaderSize + BakaShrot_Inbox_MaxPacketSize(*Inbox))
EndProcedure
; Accepts packets up to #BakaShrot_MaxPacketSize (encrypted) from now on. Call
; it once the other end is authenticated, before it can send anything big:
; on the server, before sending AuthAccepted.
Procedure BakaShrot_Inbox_Lift(*Inbox.BakaShrot_Inbox)
*Inbox\MaxPacketSize = #BakaShrot_MaxPacketSize + #BakaShrot_Cipher_Overhead
EndProcedure
; Sends *Packet as one frame, encrypted with *Cipher, or in plain text if
; *Cipher is 0: only the Hello (sealed on its own) and the ChallengeRequest.
; Returns #False if the packet is too big, *Cipher isn't set up, or the data
; couldn't be sent.
; PureBasic's sockets don't block: SendNetworkData() returns -1 once the
; system's send buffer is full (EAGAIN on Linux, a few hundred KB), so -1 is
; retried until nothing went out for #BakaShrot_SendStallTimeout. PureBasic
; doesn't tell that from a broken connection, which then takes that long to
; give up on.
Procedure.i BakaShrot_SendPacket(ConnectionId.i, *Packet, PacketSize.i, *Cipher.BakaShrot_Cipher)
Protected *Frame, FrameSize.i, PayloadSize.i, Offset.i, Sent.i, LastProgress.i
If PacketSize < 1 Or PacketSize > #BakaShrot_MaxPacketSize
ProcedureReturn #False
EndIf
PayloadSize = PacketSize
If *Cipher
If Not *Cipher\IsReady
ProcedureReturn #False
EndIf
PayloadSize + #BakaShrot_Cipher_Overhead
EndIf
FrameSize = #BakaShrot_FrameHeaderSize + PayloadSize
*Frame = AllocateMemory(FrameSize, #PB_Memory_NoClear)
If Not *Frame
ProcedureReturn #False
EndIf
PokeL(*Frame, PayloadSize)
If *Cipher
If Not BakaShrot_Cipher_EncryptTo(*Cipher, *Packet, PacketSize, *Frame + #BakaShrot_FrameHeaderSize)
FreeMemory(*Frame)
ProcedureReturn #False
EndIf
Else
CopyMemory(*Packet, *Frame + #BakaShrot_FrameHeaderSize, PacketSize)
EndIf
LastProgress = ElapsedMilliseconds()
While Offset < FrameSize
Sent = SendNetworkData(ConnectionId, *Frame + Offset, FrameSize - Offset)
If Sent > 0
Offset + Sent
LastProgress = ElapsedMilliseconds()
ElseIf ElapsedMilliseconds() - LastProgress > #BakaShrot_SendStallTimeout
FreeMemory(*Frame)
ProcedureReturn #False
Else
; Full, until the other end reads some of it.
Delay(1)
EndIf
Wend
FreeMemory(*Frame)
ProcedureReturn #True
EndProcedure
; Adds received data at the end of *Inbox.
; Returns #False if it would go over BakaShrot_Inbox_MaxSize() or memory ran out.
Procedure.i BakaShrot_Inbox_Append(*Inbox.BakaShrot_Inbox, *Data, DataSize.i)
Protected *NewBuffer, Needed.i, MaxSize.i, NewCapacity.i
Needed = *Inbox\Size + DataSize
MaxSize = BakaShrot_Inbox_MaxSize(*Inbox)
If Needed > MaxSize
ProcedureReturn #False
EndIf
; Out of room at the end: moves what's left to the front, but only if it
; isn't bigger than the room that frees, so each byte gets moved about
; once. Otherwise the buffer grows instead, doubling: moving 32 MB under
; the server's mutex for every 64 KB received, near the limit, would stall
; every client. At worst it reaches twice BakaShrot_Inbox_MaxSize().
If *Inbox\Start + Needed > *Inbox\Capacity And *Inbox\Start > 0 And *Inbox\Size <= *Inbox\Start
MoveMemory(*Inbox\Buffer + *Inbox\Start, *Inbox\Buffer, *Inbox\Size)
*Inbox\Start = 0
EndIf
If *Inbox\Start + Needed > *Inbox\Capacity
NewCapacity = *Inbox\Capacity * 2
If NewCapacity < *Inbox\Start + Needed
NewCapacity = *Inbox\Start + Needed
EndIf
If NewCapacity > *Inbox\Start + MaxSize
NewCapacity = *Inbox\Start + MaxSize
EndIf
If *Inbox\Buffer
*NewBuffer = ReAllocateMemory(*Inbox\Buffer, NewCapacity, #PB_Memory_NoClear)
Else
*NewBuffer = AllocateMemory(NewCapacity, #PB_Memory_NoClear)
EndIf
If Not *NewBuffer
ProcedureReturn #False
EndIf
*Inbox\Buffer = *NewBuffer
*Inbox\Capacity = NewCapacity
EndIf
CopyMemory(*Data, *Inbox\Buffer + *Inbox\Start + *Inbox\Size, DataSize)
*Inbox\Size + DataSize
ProcedureReturn #True
EndProcedure
; Takes the first complete packet out of *Inbox.
; Returns:
; #BakaShrot_Inbox_Packet *OutPacket\i receives the packet (free it with FreeMemory), *OutSize\i its size.
; #BakaShrot_Inbox_Incomplete The next packet hasn't fully arrived yet.
; #BakaShrot_Inbox_Invalid The frame's size is invalid (too big for now included), or memory ran out. Abort the connection.
Procedure.i BakaShrot_Inbox_TakePacket(*Inbox.BakaShrot_Inbox, *OutPacket.Integer, *OutSize.Integer)
Protected PacketSize.i, *Packet, *Frame
If *Inbox\Size < #BakaShrot_FrameHeaderSize
ProcedureReturn #BakaShrot_Inbox_Incomplete
EndIf
; Checked as soon as the size arrived, not once the whole frame did.
*Frame = *Inbox\Buffer + *Inbox\Start
PacketSize = PeekL(*Frame) & $FFFFFFFF
If PacketSize < 1 Or PacketSize > BakaShrot_Inbox_MaxPacketSize(*Inbox)
ProcedureReturn #BakaShrot_Inbox_Invalid
EndIf
If *Inbox\Size < #BakaShrot_FrameHeaderSize + PacketSize
ProcedureReturn #BakaShrot_Inbox_Incomplete
EndIf
*Packet = AllocateMemory(PacketSize, #PB_Memory_NoClear)
If Not *Packet
ProcedureReturn #BakaShrot_Inbox_Invalid
EndIf
CopyMemory(*Frame + #BakaShrot_FrameHeaderSize, *Packet, PacketSize)
; What's left stays where it is, Append() moves it when it needs room.
*Inbox\Start + #BakaShrot_FrameHeaderSize + PacketSize
*Inbox\Size - (#BakaShrot_FrameHeaderSize + PacketSize)
If *Inbox\Size = 0
*Inbox\Start = 0
If *Inbox\Capacity >= #BakaShrot_InboxKeptCapacity
FreeMemory(*Inbox\Buffer)
*Inbox\Buffer = 0
*Inbox\Capacity = 0
EndIf
EndIf
*OutPacket\i = *Packet
*OutSize\i = PacketSize
ProcedureReturn #BakaShrot_Inbox_Packet
EndProcedure
; Turns a frame's content taken out of an inbox (*Frame, FrameSize bytes)
; into the packet: decrypts it with *Cipher once it's set up, as it must
; be from the ChallengeResponse on, else it's the packet already.
; Returns the packet (free it with FreeMemory), its size in *OutSize\i, or
; 0 if it doesn't decrypt: abort the connection. *Frame is freed or
; returned either way.
Procedure.i BakaShrot_OpenFrame(*Cipher.BakaShrot_Cipher, *Frame, FrameSize.i, *OutSize.Integer)
Protected *Packet
If Not *Cipher\IsReady
*OutSize\i = FrameSize
ProcedureReturn *Frame
EndIf
*Packet = BakaShrot_Cipher_Decrypt(*Cipher, *Frame, FrameSize, *OutSize)
FreeMemory(*Frame)
If *Packet And *OutSize\i < 1
; Never sent: BakaShrot_SendPacket() refuses empty packets.
FreeMemory(*Packet)
*Packet = 0
EndIf
ProcedureReturn *Packet
EndProcedure
; Frees *Inbox's data, and puts its limit back to the handshake's.
Procedure BakaShrot_Inbox_Clear(*Inbox.BakaShrot_Inbox)
If *Inbox\Buffer
FreeMemory(*Inbox\Buffer)
EndIf
*Inbox\Buffer = 0
*Inbox\Start = 0
*Inbox\Size = 0
*Inbox\Capacity = 0
*Inbox\MaxPacketSize = 0
EndProcedure
+169
View File
@@ -0,0 +1,169 @@
;{- Code Header
; ==- Basic Info -================================
; Name: Names.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; BakaShrot Names
;
; Topics and nodes have a numeric id (0-65535) on each server, and a name
; that's the same on every server: replication sends names, and each server
; translates them to its own ids (see Server/Storage/Names.pbi).
;
; Wherever a topic or node is given (config, requests, tools), it's a "ref":
; - a name: 1-64 characters out of A-Z a-z 0-9 _ . -, not only digits,
; compared without case ("Logs" is "logs"),
; - or an id written in digits, 0-65535, which is always that id.
; A topic or node without a name is known by its id in digits, "7".
; ============================================================================
#BakaShrot_MaxNameLength = 64
#BakaShrot_MaxId = 65535
; #True if Text is made of digits only (and isn't empty).
Procedure.i BakaShrot_IsDigits(Text.s)
Protected i.i, c.i
If Text = ""
ProcedureReturn #False
EndIf
For i = 1 To Len(Text)
c = Asc(Mid(Text, i, 1))
If c < '0' Or c > '9'
ProcedureReturn #False
EndIf
Next
ProcedureReturn #True
EndProcedure
; #True if Name can be a topic or node name: see the top of this file.
Procedure.i BakaShrot_IsValidName(Name.s)
Protected i.i, c.i
If Name = "" Or Len(Name) > #BakaShrot_MaxNameLength Or BakaShrot_IsDigits(Name)
ProcedureReturn #False
EndIf
For i = 1 To Len(Name)
c = Asc(Mid(Name, i, 1))
If Not ((c >= 'a' And c <= 'z') Or (c >= 'A' And c <= 'Z') Or (c >= '0' And c <= '9') Or c = '_' Or c = '.' Or c = '-')
ProcedureReturn #False
EndIf
Next
ProcedureReturn #True
EndProcedure
; The id a ref written in digits stands for, or -1 if it isn't one (a name,
; or out of range). Leading zeros are refused, "007" isn't "7".
Procedure.i BakaShrot_RefToId(Ref.s)
Protected Id.i
If Not BakaShrot_IsDigits(Ref) Or Len(Ref) > 5
ProcedureReturn -1
EndIf
Id = Val(Ref)
If Str(Id) <> Ref Or Id > #BakaShrot_MaxId
ProcedureReturn -1
EndIf
ProcedureReturn Id
EndProcedure
; #True if Ref is a valid name or a valid id in digits.
Procedure.i BakaShrot_IsValidRef(Ref.s)
ProcedureReturn Bool(BakaShrot_RefToId(Ref) >= 0 Or BakaShrot_IsValidName(Ref))
EndProcedure
; #True if Ref designates the topic or node Id, named Name ("" if unnamed).
Procedure.i BakaShrot_RefMatches(Ref.s, Id.i, Name.s)
If BakaShrot_IsDigits(Ref)
ProcedureReturn Bool(BakaShrot_RefToId(Ref) = Id)
EndIf
ProcedureReturn Bool(Name <> "" And LCase(Ref) = LCase(Name))
EndProcedure
; --- Wildcards ---------------------------------------------------------------
; Server-side lists of topics and nodes (topic lists, SendNodes, ...) also
; take patterns, like file names: "*" any characters (none included), "?"
; exactly one, everything else itself, without case. "sensors.*",
; "kitchen-??", "*". A pattern only matches names, never ids in digits.
; #True if Pattern is a valid pattern: has a * or a ?, and otherwise only
; characters a name can have.
Procedure.i BakaShrot_IsValidPattern(Pattern.s)
Protected i.i, c.i
If Pattern = "" Or Len(Pattern) > #BakaShrot_MaxNameLength
ProcedureReturn #False
EndIf
If Not FindString(Pattern, "*") And Not FindString(Pattern, "?")
ProcedureReturn #False
EndIf
For i = 1 To Len(Pattern)
c = Asc(Mid(Pattern, i, 1))
If Not ((c >= 'a' And c <= 'z') Or (c >= 'A' And c <= 'Z') Or (c >= '0' And c <= '9') Or c = '_' Or c = '.' Or c = '-' Or c = '*' Or c = '?')
ProcedureReturn #False
EndIf
Next
ProcedureReturn #True
EndProcedure
; #True if Name matches Pattern (see above), without case. Ids in digits
; never match.
Procedure.i BakaShrot_GlobMatch(Pattern.s, Name.s)
Protected p.i = 1, n.i = 1, StarP.i = 0, StarN.i = 0
Protected PLen.i, NLen.i, pc.s
If Not BakaShrot_IsValidName(Name)
ProcedureReturn #False
EndIf
Pattern = LCase(Pattern)
Name = LCase(Name)
PLen = Len(Pattern)
NLen = Len(Name)
; Greedy with backtracking to the last "*": linear enough for 64 characters.
While n <= NLen
If p <= PLen
pc = Mid(Pattern, p, 1)
Else
pc = ""
EndIf
If pc = "*"
StarP = p
StarN = n
p + 1
ElseIf pc <> "" And (pc = "?" Or pc = Mid(Name, n, 1))
p + 1
n + 1
ElseIf StarP
p = StarP + 1
StarN + 1
n = StarN
Else
ProcedureReturn #False
EndIf
Wend
While p <= PLen And Mid(Pattern, p, 1) = "*"
p + 1
Wend
ProcedureReturn Bool(p > PLen)
EndProcedure
+368
View File
@@ -0,0 +1,368 @@
;{- Code Header
; ==- Basic Info -================================
; Name: Outbound.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; BakaShrot Outbound connections
;
; The client side of a connection: connecting to a server and running the
; handshake from Connections.pbi as the one being authenticated, then
; sending requests (BakaShrot_Outbound_Send()) and waiting for the answers
; (BakaShrot_Outbound_WaitPacket()), encrypted for this connection.
; Used by the client DLL, and by the server to link to its peers.
;
; A BakaShrot_Outbound must only be used by one thread at a time.
; ============================================================================
XIncludeFile "Connections.pbi"
XIncludeFile "SocketWait.pbi"
#BakaShrot_Outbound_ReceiveBufferSize = 65536
; How long the server gets to send each packet, handshake or answer.
#BakaShrot_Outbound_Timeout = 10000
; Who to authenticate as.
Structure BakaShrot_OutboundIdentity
; The node it writes as, a name or an id in digits (Names.pbi), resolved
; by the server, which must allow it for this key.
Node.s
; Ed25519 public key (Base64), sent in the Hello.
PublicKey.s
; Ed25519 private key, #BakaShrot_Ed25519_PrivateKeySize bytes, used to
; answer the challenge. Must stay valid while connecting.
*PrivateKey
EndStructure
Structure BakaShrot_Outbound
; 0 when not connected.
ConnectionId.i
Inbox.BakaShrot_Inbox
Metadata.BakaShrot_ConnectionMetadata
; Optional, set by the owner: while it points to a non-zero value, waits
; for the server's packets give up right away, as if they timed out.
; Lets a server stop its peer links without waiting out their timeouts.
*StopRequested.Integer
; Why BakaShrot_Outbound_Connect() failed, a #BakaShrot_Error_* of
; Client/BakaShrot_ErrorCodes.pbi, 0 once it succeeded.
LastError.l
EndStructure
; Closes *Outbound's connection, if any, and sets its status to Status.
Procedure BakaShrot_Outbound_Close(*Outbound.BakaShrot_Outbound, Status.i)
If *Outbound\ConnectionId
CloseNetworkConnection(*Outbound\ConnectionId)
EndIf
*Outbound\ConnectionId = 0
BakaShrot_Inbox_Clear(@*Outbound\Inbox)
BakaShrot_ClearConnectionMetadata(@*Outbound\Metadata)
*Outbound\Metadata\Status = Status
EndProcedure
; Sends *Packet to the server, encrypted for this connection.
; Returns #False if it couldn't be sent: close the connection then.
Procedure.i BakaShrot_Outbound_Send(*Outbound.BakaShrot_Outbound, *Packet, PacketSize.i)
If Not *Outbound\ConnectionId
ProcedureReturn #False
EndIf
ProcedureReturn BakaShrot_SendPacket(*Outbound\ConnectionId, *Packet, PacketSize, @*Outbound\Metadata\Cipher)
EndProcedure
; Waits for the next packet from the server, for up to TimeoutMs, decrypted
; once the connection's cipher is set up.
; Returns the packet (free it with FreeMemory) with its size in *OutSize\i,
; or 0 if the server disconnected, sent an invalid frame, one that doesn't
; decrypt or too much data, timed out, or the owner asked to stop (see
; *StopRequested).
Procedure.i BakaShrot_Outbound_WaitPacket(*Outbound.BakaShrot_Outbound, *OutSize.Integer, TimeoutMs.i)
Protected *Packet = 0, *Buffer, Result.i, Received.i, StartTime.i, WaitMs.i
*Buffer = AllocateMemory(#BakaShrot_Outbound_ReceiveBufferSize)
If Not *Buffer
ProcedureReturn 0
EndIf
StartTime = ElapsedMilliseconds()
Repeat
Result = BakaShrot_Inbox_TakePacket(@*Outbound\Inbox, @*Packet, *OutSize)
If Result = #BakaShrot_Inbox_Packet Or Result = #BakaShrot_Inbox_Invalid
Break
EndIf
If ElapsedMilliseconds() - StartTime > TimeoutMs
Break
EndIf
If *Outbound\StopRequested
If *Outbound\StopRequested\i
Break
EndIf
EndIf
Select NetworkClientEvent(*Outbound\ConnectionId)
Case #PB_NetworkEvent_Data
Received = ReceiveNetworkData(*Outbound\ConnectionId, *Buffer, #BakaShrot_Outbound_ReceiveBufferSize)
If Received <= 0
Break
EndIf
If Not BakaShrot_Inbox_Append(@*Outbound\Inbox, *Buffer, Received)
Break
EndIf
Case #PB_NetworkEvent_Disconnect
Break
Default
; Sleeps until the server sends something, waking up at least
; every 50 ms to check the timeout and *StopRequested.
WaitMs = TimeoutMs - (ElapsedMilliseconds() - StartTime)
If WaitMs > 50
WaitMs = 50
EndIf
If WaitMs < 1
WaitMs = 1
EndIf
BakaShrot_WaitSocket(ConnectionID(*Outbound\ConnectionId), WaitMs)
EndSelect
ForEver
FreeMemory(*Buffer)
If *Packet
*Packet = BakaShrot_OpenFrame(@*Outbound\Metadata\Cipher, *Packet, *OutSize\i, *OutSize)
EndIf
ProcedureReturn *Packet
EndProcedure
; Connects to Host:Port and authenticates as *Identity, to the server whose
; Ed25519 public key is *ServerPublicKey (#BakaShrot_Ed25519_PublicKeySize
; bytes): sends the Hello sealed for that key, checks the server's
; signature in the challenge it gets back, sets up the connection's cipher,
; signs the handshake, then waits for the server to accept it.
; Fails if already connected, if *Identity's public key isn't valid Base64,
; if the server can't prove it holds *ServerPublicKey's private key, or if
; anything in the handshake is out of order or unexpected, in which case
; the connection is closed.
Procedure.i BakaShrot_Outbound_Connect(*Outbound.BakaShrot_Outbound, Host.s, Port.i, *Identity.BakaShrot_OutboundIdentity, *ServerPublicKey)
Protected *Packet, PacketSize.Integer, *View.MsgPackData, Sent.i, *Sealed, SealedSize.Integer
Protected Hello.BakaShrot_AuthHello
Protected *Request.BakaShrot_ChallengeRequest
Protected Response.BakaShrot_ChallengeResponse
Protected *Accepted.BakaShrot_AuthAccepted
Protected Proof.BakaShrot_ChallengeProof
Protected KeyPair.BakaShrot_SessionKeyPair
Protected ChallengeDecoded.i, ServerProved.i
*Outbound\LastError = #BakaShrot_Error_None
If *Outbound\ConnectionId
*Outbound\LastError = #BakaShrot_Error_AlreadyConnected
ProcedureReturn #False
EndIf
If Not *ServerPublicKey Or Port < 1 Or Port > 65535
*Outbound\LastError = #BakaShrot_Error_InvalidArgument
ProcedureReturn #False
EndIf
; Only needed before PureBasic 6.00.
CompilerIf #PB_Compiler_Version < 600
If Not InitNetwork()
*Outbound\LastError = #BakaShrot_Error_Internal
ProcedureReturn #False
EndIf
CompilerEndIf
If Not InitCryptography()
*Outbound\LastError = #BakaShrot_Error_Internal
ProcedureReturn #False
EndIf
BakaShrot_ClearConnectionMetadata(@*Outbound\Metadata)
ClearStructure(@*Outbound\Metadata, BakaShrot_ConnectionMetadata)
If Not DecodeKeyFromString(*Identity\PublicKey, @*Outbound\Metadata\PublicKey[0], #BakaShrot_Ed25519_PublicKeySize)
*Outbound\Metadata\Status = #BakaShrot_ConnectionStatus_Aborted
*Outbound\LastError = #BakaShrot_Error_InvalidArgument
ProcedureReturn #False
EndIf
CopyMemory(*ServerPublicKey, @*Outbound\Metadata\ServerPublicKey[0], #BakaShrot_Ed25519_PublicKeySize)
*Outbound\ConnectionId = OpenNetworkConnection(Host, Port, #PB_Network_TCP | #PB_Network_IPv4)
If Not *Outbound\ConnectionId
*Outbound\Metadata\Status = #BakaShrot_ConnectionStatus_Aborted
*Outbound\LastError = #BakaShrot_Error_ConnectFailed
ProcedureReturn #False
EndIf
*Outbound\Metadata\Status = #BakaShrot_ConnectionStatus_New
; This connection's key pair, the public half goes in the Hello.
BakaShrot_Session_NewKeyPair(@KeyPair)
CopyMemory(@KeyPair\PublicKey[0], @*Outbound\Metadata\ClientSessionKey[0], #BakaShrot_SessionKeySize)
; 1. Hello, sealed for the server
Hello\ClientNode = *Identity\Node
Hello\ClientPubKeyB64 = *Identity\PublicKey
CopyMemory(@KeyPair\PublicKey[0], @Hello\ClientSessionKey[0], #BakaShrot_SessionKeySize)
*Outbound\LastError = #BakaShrot_Error_Internal
*Packet = BakaShrot_HelloPacket_Encode(@Hello, @PacketSize)
If Not *Packet
Goto ConnectFailed
EndIf
*Sealed = BakaShrot_Session_SealHello(*ServerPublicKey, *Packet, PacketSize\i, @SealedSize)
FreeMemory(*Packet)
If Not *Sealed
Goto ConnectFailed
EndIf
*Outbound\LastError = #BakaShrot_Error_ConnectFailed
Sent = BakaShrot_SendPacket(*Outbound\ConnectionId, *Sealed, SealedSize\i, 0)
FreeMemory(*Sealed)
If Not Sent
Goto ConnectFailed
EndIf
; 2. Challenge request, in plain text. No answer: the server closed the
; connection, it couldn't open the Hello or doesn't allow this key and
; node (or speaks another protocol version).
*Outbound\LastError = #BakaShrot_Error_AuthRejected
*Packet = BakaShrot_Outbound_WaitPacket(*Outbound, @PacketSize, #BakaShrot_Outbound_Timeout)
If Not *Packet
Goto ConnectFailed
EndIf
*Outbound\LastError = #BakaShrot_Error_ProtocolError
*Request = 0
*View = MsgPackWrapMsgBuffer(*Packet, PacketSize\i)
If *View
*Request = BakaShrot_ChallengeRequestPacket_Decode(*View)
MsgPackFree(*View, #False)
EndIf
FreeMemory(*Packet)
If Not *Request
Goto ConnectFailed
EndIf
ChallengeDecoded = DecodeKeyFromString(*Request\ChallengeB64, @*Outbound\Metadata\Challenge[0], #BakaShrot_ChallengeSize)
CopyMemory(@*Request\Nonce[0], @*Outbound\Metadata\Nonce[0], #BakaShrot_NonceSize)
CopyMemory(@*Request\ServerSessionKey[0], @*Outbound\Metadata\ServerSessionKey[0], #BakaShrot_SessionKeySize)
CopyMemory(@*Request\ServerSignature[0], @Proof\Signature[0], #BakaShrot_Ed25519_SignatureSize)
FreeStructure(*Request)
If Not ChallengeDecoded
Goto ConnectFailed
EndIf
; Only the server holding *ServerPublicKey's private key could sign this
; connection's halves and challenge.
BakaShrot_MakeHandshakeTranscript(@*Outbound\Metadata, #BakaShrot_TranscriptServerLabel, @Proof)
ServerProved = BakaShrot_VerifyHandshake(@Proof, *ServerPublicKey)
If Not ServerProved
*Outbound\LastError = #BakaShrot_Error_ServerNotVerified
Goto ConnectFailed
EndIf
; Every packet is encrypted from now on.
*Outbound\LastError = #BakaShrot_Error_Internal
If Not BakaShrot_Session_StartClient(@*Outbound\Metadata\Cipher, @KeyPair, @*Outbound\Metadata\ServerSessionKey[0])
Goto ConnectFailed
EndIf
*Outbound\Metadata\Status = #BakaShrot_ConnectionStatus_Challenged
; 3. Challenge response
BakaShrot_MakeHandshakeTranscript(@*Outbound\Metadata, #BakaShrot_TranscriptClientLabel, @Proof)
If Not BakaShrot_SignHandshake(@Proof, *Identity\PrivateKey)
Goto ConnectFailed
EndIf
Response\ChallengeResponseB64 = EncodeKeyToString(@Proof\Signature[0], #BakaShrot_Ed25519_SignatureSize)
CopyMemory(@*Outbound\Metadata\Nonce[0], @Response\Nonce[0], #BakaShrot_NonceSize)
*Packet = BakaShrot_ChallengeResponsePacket_Encode(@Response, @PacketSize)
If Not *Packet
Goto ConnectFailed
EndIf
*Outbound\LastError = #BakaShrot_Error_AuthRejected
Sent = BakaShrot_Outbound_Send(*Outbound, *Packet, PacketSize\i)
FreeMemory(*Packet)
If Not Sent
Goto ConnectFailed
EndIf
; 4. Accepted. No answer: the server didn't accept this key's signature.
*Packet = BakaShrot_Outbound_WaitPacket(*Outbound, @PacketSize, #BakaShrot_Outbound_Timeout)
If Not *Packet
Goto ConnectFailed
EndIf
*Outbound\LastError = #BakaShrot_Error_ProtocolError
*Accepted = 0
*View = MsgPackWrapMsgBuffer(*Packet, PacketSize\i)
If *View
*Accepted = BakaShrot_AuthAcceptedPacket_Decode(*View)
MsgPackFree(*View, #False)
EndIf
FreeMemory(*Packet)
If Not *Accepted
Goto ConnectFailed
EndIf
FreeStructure(*Accepted)
; The server's answers may be big from now on.
BakaShrot_Inbox_Lift(@*Outbound\Inbox)
*Outbound\Metadata\Status = #BakaShrot_ConnectionStatus_Authenticated
*Outbound\LastError = #BakaShrot_Error_None
ProcedureReturn #True
ConnectFailed:
BakaShrot_Session_ClearKeyPair(@KeyPair)
BakaShrot_Outbound_Close(*Outbound, #BakaShrot_ConnectionStatus_Aborted)
ProcedureReturn #False
EndProcedure
; Returns #True while *Outbound is connected, notices when the server closed
; the connection.
; Data the server sent is left to read, only a disconnect is acted upon.
Procedure.i BakaShrot_Outbound_IsConnected(*Outbound.BakaShrot_Outbound)
If Not *Outbound\ConnectionId
ProcedureReturn #False
EndIf
If NetworkClientEvent(*Outbound\ConnectionId) = #PB_NetworkEvent_Disconnect
BakaShrot_Outbound_Close(*Outbound, #BakaShrot_ConnectionStatus_Disconnected)
ProcedureReturn #False
EndIf
ProcedureReturn #True
EndProcedure
+229
View File
@@ -0,0 +1,229 @@
;{- Code Header
; ==- Basic Info -================================
; Name: Packets.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
XIncludeFile "../../Includes/PB-MessagePack/Includes/MessagePack.pbi"
XIncludeFile "Names.pbi"
; The refusal codes (RequestRefused) and the client's error codes.
XIncludeFile "../../Client/BakaShrot_ErrorCodes.pbi"
; Represents the root of all BakaShrot packets.
; Any packets below this size MUST be thrown out.
Structure BakaShrot_PacketBase
Magic.l
Version.l
PacketType.l
EndStructure
; Fixed values every BakaShrot_PacketBase must carry. Checked on decode so a
; packet from a different protocol/version is thrown out instead of being
; misparsed.
#BakaShrot_ProtocolMagic = $42534854 ; "BSHT"
; 2: topics and nodes by name (Commons/Networking/Names.pbi), see Design/Packets.md.
; 3: the Hello sealed for the server, a key per connection, everything after
; the ChallengeRequest encrypted (Connections.pbi). Messages carry when
; they were pushed (PushedAt).
; 4: attachments (Design/Attachments.md).
; 5: the Hello carries the client's node only: its default topic is the
; server's to say (DefaultTopic in its client section).
; 6: RequestRefused carries a Code (Client/BakaShrot_ErrorCodes.pbi).
#BakaShrot_ProtocolVersion = 6
; Size in bytes of the nonce sent in a challenge request and echoed in its response.
; It MUST be filled with CryptRandomData(), never reused, and be checked against the one the
; server issued for that connection, so a captured response can't be replayed.
#BakaShrot_NonceSize = 32
; Size in bytes of the random challenge sent Base64-encoded in a challenge request.
; The client proves it holds its private key by signing the challenge followed by the nonce.
#BakaShrot_ChallengeSize = 32
; Size in bytes of the public half of a connection's key pair, sent by the
; client in its Hello and by the server in its ChallengeRequest
; (#BakaShrot_Session_PublicKeySize, Commons/Cryptography/Session.pbi).
#BakaShrot_SessionKeySize = 32
; Size in bytes of the server's signature in a ChallengeRequest
; (#BakaShrot_Ed25519_SignatureSize).
#BakaShrot_HandshakeSignatureSize = 64
; When a message was pushed: milliseconds since 1970-01-01 00:00:00 UTC, set
; by the server it was pushed to, and kept as is by every server it's
; replicated to. Anything outside 1 to #BakaShrot_MaxTimestamp (9999-12-31)
; is invalid on the wire.
#BakaShrot_MaxTimestamp = 253402300799999
Procedure.i BakaShrot_IsValidTimestamp(Timestamp.q)
ProcedureReturn Bool(Timestamp >= 1 And Timestamp <= #BakaShrot_MaxTimestamp)
EndProcedure
; Attachments (Design/Attachments.md): at most one per message, sent and
; stored in parts of #BakaShrot_AttachmentChunkSize bytes (the last one what's
; left), checked with their SHA-256. #BakaShrot_MaxAttachmentSize is the
; protocol's limit, each server sets its own ([BakaShrot.Server]
; MaxAttachmentSize).
#BakaShrot_AttachmentChunkSize = 1048576
#BakaShrot_MaxAttachmentSize = 1099511627776
#BakaShrot_MaxAttachmentChunks = #BakaShrot_MaxAttachmentSize / #BakaShrot_AttachmentChunkSize
#BakaShrot_Sha256Size = 32
; How many parts Size bytes take.
Procedure.q BakaShrot_AttachmentChunkCount(Size.q)
ProcedureReturn (Size + #BakaShrot_AttachmentChunkSize - 1) / #BakaShrot_AttachmentChunkSize
EndProcedure
; How big part Index of Size bytes is, 0 if there's no such part.
Procedure.i BakaShrot_AttachmentChunkBytes(Size.q, Index.q)
Protected Left.q = Size - Index * #BakaShrot_AttachmentChunkSize
If Index < 0 Or Left <= 0
ProcedureReturn 0
ElseIf Left > #BakaShrot_AttachmentChunkSize
ProcedureReturn #BakaShrot_AttachmentChunkSize
EndIf
ProcedureReturn Left
EndProcedure
; Biggest packet accepted on the wire once authenticated, anything bigger
; aborts the connection. Before that, only #BakaShrot_MaxHandshakePacketSize
; (Connections.pbi).
#BakaShrot_MaxPacketSize = 16 * 1024 * 1024
; Biggest message a client may push (its JSON, in UTF-8 bytes). Leaves room
; for the fields around it, so a stored message fits in every packet that
; carries one: LatestMessage, a ReplicateMessages batch of one.
#BakaShrot_MaxMessageSize = #BakaShrot_MaxPacketSize - 4096
Enumeration BakaShrot_PacketTypes
; Safety fallback value, should be dropped when encountered
#BakaShrot_PacketType_None = 0
; 1-3 were used by the removed AuthenticationPacket.pbi, don't reuse them.
#BakaShrot_PacketType_ClientHello = 4
#BakaShrot_PacketType_ChallengeRequest = 5
#BakaShrot_PacketType_ChallengeResponse = 6
#BakaShrot_PacketType_AuthAccepted = 7
; Only accepted once authenticated.
#BakaShrot_PacketType_PushMessage = 8
#BakaShrot_PacketType_MessagePushed = 9
#BakaShrot_PacketType_GetLatestMessage = 10
#BakaShrot_PacketType_LatestMessage = 11
#BakaShrot_PacketType_RequestRefused = 12
; Replication, only accepted from peers once authenticated.
#BakaShrot_PacketType_SyncStateRequest = 13
#BakaShrot_PacketType_SyncState = 14
#BakaShrot_PacketType_ReplicateMessages = 15
; Raw read-only SQL, only accepted once authenticated, from clients allowed to.
#BakaShrot_PacketType_QueryRequest = 16
#BakaShrot_PacketType_QueryResult = 17
; Name <-> id of a topic or node, only accepted once authenticated.
#BakaShrot_PacketType_ResolveName = 18
#BakaShrot_PacketType_NameResolved = 19
; Every topic or node the client may see, only accepted once authenticated.
#BakaShrot_PacketType_ListNames = 20
#BakaShrot_PacketType_NamesList = 21
; A run of messages of a topic/node, only accepted once authenticated.
#BakaShrot_PacketType_GetMessages = 22
#BakaShrot_PacketType_Messages = 23
; Attachments, only accepted once authenticated: uploading one (before
; its PushMessage), and reading one, in parts.
#BakaShrot_PacketType_UploadStart = 24
#BakaShrot_PacketType_UploadStarted = 25
#BakaShrot_PacketType_UploadChunk = 26
#BakaShrot_PacketType_ChunkStored = 27
#BakaShrot_PacketType_GetAttachment = 28
#BakaShrot_PacketType_AttachmentChunk = 29
; Replicating attachments, only accepted from peers, once their messages are.
#BakaShrot_PacketType_MissingAttachmentsRequest = 30
#BakaShrot_PacketType_MissingAttachments = 31
#BakaShrot_PacketType_ReplicateAttachmentChunk = 32
EndEnumeration
; Checks and reads the given MsgPack data into a packet structure's common fields.
; The caller can handle the MsgPack data validation however it see fit.
; On success, the structure's fields will be populated, and the MsgPack structure will be ready to ready the packet's remaining fields.
; On failure, all data should be discarded and be treated as tainted.
Procedure.b BakaShrot_ReadPacketBase(*PacketStruct.BakaShrot_PacketBase, *MsgPackData.MsgPackData)
; Returns true on success, false otherwise
; The caller will usually drop all data and tell the remote client to fuck off if this fails.
Protected TempValue.q
If Not *PacketStruct Or Not *MsgPackData
ProcedureReturn #False
EndIf
; Magic
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
ProcedureReturn #False
EndIf
TempValue = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or TempValue <> #BakaShrot_ProtocolMagic
ProcedureReturn #False
EndIf
*PacketStruct\Magic = TempValue
; Version
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
ProcedureReturn #False
EndIf
TempValue = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or TempValue <> #BakaShrot_ProtocolVersion
ProcedureReturn #False
EndIf
*PacketStruct\Version = TempValue
; PacketType
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
ProcedureReturn #False
EndIf
TempValue = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or TempValue <= #BakaShrot_PacketType_None Or TempValue > 2147483647
ProcedureReturn #False
EndIf
*PacketStruct\PacketType = TempValue
ProcedureReturn #True
EndProcedure
; Writes a packet structure's common fields into the given MsgPack data.
; On success, the MsgPack structure will be ready to write the packet's remaining fields.
; On failure, the MsgPack data should be discarded and be treated as tainted.
Procedure.b BakaShrot_WritePacketBase(*PacketStruct.BakaShrot_PacketBase, *MsgPackData.MsgPackData)
; Returns true on success, false otherwise
If MsgPackWriteInteger(*MsgPackData, *PacketStruct\Magic) <> #MsgPack_Error_Success
ProcedureReturn #False
EndIf
If MsgPackWriteInteger(*MsgPackData, *PacketStruct\Version) <> #MsgPack_Error_Success
ProcedureReturn #False
EndIf
If MsgPackWriteInteger(*MsgPackData, *PacketStruct\PacketType) <> #MsgPack_Error_Success
ProcedureReturn #False
EndIf
ProcedureReturn #True
EndProcedure
@@ -0,0 +1,212 @@
;{- Code Header
; ==- Basic Info -================================
; Name: AttachmentChunkPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; S2C, answers a GetAttachment: part ChunkIndex of the attachment of
; TopicId:NodeId#MessageId (the server's ids), Size bytes in all, in parts of
; #BakaShrot_AttachmentChunkSize, whose SHA-256 is Sha256.
Structure BakaShrot_AttachmentChunk Extends BakaShrot_PacketBase
TopicId.l
NodeId.l
MessageId.q
Size.q
Sha256.a[#BakaShrot_Sha256Size]
ChunkIndex.l
*Data
DataSize.l
EndStructure
; Encodes *Chunk into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_AttachmentChunkPacket_Encode(*Chunk.BakaShrot_AttachmentChunk, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Chunk\Magic = #BakaShrot_ProtocolMagic
*Chunk\Version = #BakaShrot_ProtocolVersion
*Chunk\PacketType = #BakaShrot_PacketType_AttachmentChunk
If *Chunk\TopicId < 0 Or *Chunk\TopicId > #BakaShrot_MaxId Or *Chunk\NodeId < 0 Or *Chunk\NodeId > #BakaShrot_MaxId Or *Chunk\MessageId < 1 Or *Chunk\Size < 1 Or *Chunk\Size > #BakaShrot_MaxAttachmentSize Or *Chunk\ChunkIndex < 0 Or *Chunk\ChunkIndex > #BakaShrot_MaxAttachmentChunks Or Not *Chunk\Data Or *Chunk\DataSize < 1 Or *Chunk\DataSize > #BakaShrot_AttachmentChunkSize
ProcedureReturn 0
EndIf
*MsgPackData = MsgPackCreate(#BakaShrot_AttachmentChunkSize + 256)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Chunk, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Chunk\TopicId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Chunk\NodeId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Chunk\MessageId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Chunk\Size) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteBinary(*MsgPackData, @*Chunk\Sha256[0], #BakaShrot_Sha256Size) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Chunk\ChunkIndex) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteBinary(*MsgPackData, *Chunk\Data, *Chunk\DataSize) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Frees a decoded *Chunk and the data it holds.
Procedure BakaShrot_AttachmentChunkPacket_Free(*Chunk.BakaShrot_AttachmentChunk)
If Not *Chunk
ProcedureReturn
EndIf
If *Chunk\Data
FreeMemory(*Chunk\Data)
EndIf
FreeStructure(*Chunk)
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with BakaShrot_AttachmentChunkPacket_Free().
Procedure.i BakaShrot_AttachmentChunkPacket_Decode(*MsgPackData.MsgPackData)
Protected *Chunk.BakaShrot_AttachmentChunk, Value.q, ReadSize.q
*Chunk = AllocateStructure(BakaShrot_AttachmentChunk)
If Not *Chunk
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Chunk, *MsgPackData) Or *Chunk\PacketType <> #BakaShrot_PacketType_AttachmentChunk
Goto DecodeFailed
EndIf
; TopicId
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > #BakaShrot_MaxId
Goto DecodeFailed
EndIf
*Chunk\TopicId = Value
; NodeId
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > #BakaShrot_MaxId
Goto DecodeFailed
EndIf
*Chunk\NodeId = Value
; MessageId
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 1
Goto DecodeFailed
EndIf
*Chunk\MessageId = Value
; Size
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 1 Or Value > #BakaShrot_MaxAttachmentSize
Goto DecodeFailed
EndIf
*Chunk\Size = Value
; Sha256
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary
Goto DecodeFailed
EndIf
; Anything bigger than the struct's array is rejected by MsgPackReadBinary, anything smaller by the size check.
ReadSize = MsgPackReadBinary(*MsgPackData, @*Chunk\Sha256[0], #BakaShrot_Sha256Size)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or ReadSize <> #BakaShrot_Sha256Size
Goto DecodeFailed
EndIf
; ChunkIndex
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > #BakaShrot_MaxAttachmentChunks
Goto DecodeFailed
EndIf
*Chunk\ChunkIndex = Value
; Data
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary
Goto DecodeFailed
EndIf
; A copy, freed with the packet (_Free()).
*Chunk\Data = MsgPackCopyBinary(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not *Chunk\Data
Goto DecodeFailed
EndIf
*Chunk\DataSize = MemorySize(*Chunk\Data)
If *Chunk\DataSize > #BakaShrot_AttachmentChunkSize
Goto DecodeFailed
EndIf
ProcedureReturn *Chunk
; Everything read so far is tainted, drop it.
DecodeFailed:
BakaShrot_AttachmentChunkPacket_Free(*Chunk)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,82 @@
;{- Code Header
; ==- Basic Info -================================
; Name: AuthAcceptedPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; S2C, tells the client its challenge response was accepted and it is now authenticated.
; Only carries the base fields.
Structure BakaShrot_AuthAccepted Extends BakaShrot_PacketBase
EndStructure
; Encodes *Accepted into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_AuthAcceptedPacket_Encode(*Accepted.BakaShrot_AuthAccepted, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Accepted\Magic = #BakaShrot_ProtocolMagic
*Accepted\Version = #BakaShrot_ProtocolVersion
*Accepted\PacketType = #BakaShrot_PacketType_AuthAccepted
*MsgPackData = MsgPackCreate(16)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Accepted, *MsgPackData)
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_AuthAcceptedPacket_Decode(*MsgPackData.MsgPackData)
Protected *Accepted.BakaShrot_AuthAccepted
*Accepted = AllocateStructure(BakaShrot_AuthAccepted)
If Not *Accepted
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Accepted, *MsgPackData) Or *Accepted\PacketType <> #BakaShrot_PacketType_AuthAccepted
FreeStructure(*Accepted)
ProcedureReturn 0
EndIf
ProcedureReturn *Accepted
EndProcedure
@@ -0,0 +1,148 @@
;{- Code Header
; ==- Basic Info -================================
; Name: ChallengeRequestPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; S2C challenge the client must sign with its private key, the last packet sent in plain text.
; Nonce is fresh random data tied to this connection, the client must echo it back in its response.
; ServerSessionKey: the public half of the server's key pair for this connection.
; ServerSignature: the server's signature of the handshake so far, made with its identity key
; (BakaShrot_MakeHandshakeTranscript(), Connections.pbi), so the client knows it's the right server.
Structure BakaShrot_ChallengeRequest Extends BakaShrot_PacketBase
ChallengeB64.s
Nonce.a[#BakaShrot_NonceSize]
ServerSessionKey.a[#BakaShrot_SessionKeySize]
ServerSignature.a[#BakaShrot_HandshakeSignatureSize]
EndStructure
; Encodes *Request into a freshly allocated buffer, its base fields are set by this procedure.
; *Request\Nonce must already be filled by the caller with CryptRandomData().
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_ChallengeRequestPacket_Encode(*Request.BakaShrot_ChallengeRequest, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Request\Magic = #BakaShrot_ProtocolMagic
*Request\Version = #BakaShrot_ProtocolVersion
*Request\PacketType = #BakaShrot_PacketType_ChallengeRequest
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Request, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Request\ChallengeB64) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteBinary(*MsgPackData, @*Request\Nonce[0], #BakaShrot_NonceSize) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteBinary(*MsgPackData, @*Request\ServerSessionKey[0], #BakaShrot_SessionKeySize) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteBinary(*MsgPackData, @*Request\ServerSignature[0], #BakaShrot_HandshakeSignatureSize) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_ChallengeRequestPacket_Decode(*MsgPackData.MsgPackData)
Protected *Request.BakaShrot_ChallengeRequest
Protected ReadSize.q
*Request = AllocateStructure(BakaShrot_ChallengeRequest)
If Not *Request
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Request, *MsgPackData) Or *Request\PacketType <> #BakaShrot_PacketType_ChallengeRequest
Goto DecodeFailed
EndIf
; ChallengeB64
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Request\ChallengeB64 = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; Nonce
; Anything bigger than the struct's array is rejected by MsgPackReadBinary, anything smaller by the size check.
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary
Goto DecodeFailed
EndIf
ReadSize = MsgPackReadBinary(*MsgPackData, @*Request\Nonce[0], #BakaShrot_NonceSize)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or ReadSize <> #BakaShrot_NonceSize
Goto DecodeFailed
EndIf
; ServerSessionKey
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary
Goto DecodeFailed
EndIf
ReadSize = MsgPackReadBinary(*MsgPackData, @*Request\ServerSessionKey[0], #BakaShrot_SessionKeySize)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or ReadSize <> #BakaShrot_SessionKeySize
Goto DecodeFailed
EndIf
; ServerSignature
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary
Goto DecodeFailed
EndIf
ReadSize = MsgPackReadBinary(*MsgPackData, @*Request\ServerSignature[0], #BakaShrot_HandshakeSignatureSize)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or ReadSize <> #BakaShrot_HandshakeSignatureSize
Goto DecodeFailed
EndIf
ProcedureReturn *Request
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Request)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,118 @@
;{- Code Header
; ==- Basic Info -================================
; Name: ChallengeResponsePacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; C2S response with the handshake (challenge included) signed by the client's private key
; (BakaShrot_MakeHandshakeTranscript(), Connections.pbi). Sent encrypted, as everything after it.
; Nonce is the one received in the challenge request, echoed back as-is.
; The server MUST compare it with the nonce it issued for this connection and drop the client on mismatch.
Structure BakaShrot_ChallengeResponse Extends BakaShrot_PacketBase
ChallengeResponseB64.s
Nonce.a[#BakaShrot_NonceSize]
EndStructure
; Encodes *Response into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_ChallengeResponsePacket_Encode(*Response.BakaShrot_ChallengeResponse, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Response\Magic = #BakaShrot_ProtocolMagic
*Response\Version = #BakaShrot_ProtocolVersion
*Response\PacketType = #BakaShrot_PacketType_ChallengeResponse
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Response, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Response\ChallengeResponseB64) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteBinary(*MsgPackData, @*Response\Nonce[0], #BakaShrot_NonceSize) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_ChallengeResponsePacket_Decode(*MsgPackData.MsgPackData)
Protected *Response.BakaShrot_ChallengeResponse
Protected ReadSize.q
*Response = AllocateStructure(BakaShrot_ChallengeResponse)
If Not *Response
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Response, *MsgPackData) Or *Response\PacketType <> #BakaShrot_PacketType_ChallengeResponse
Goto DecodeFailed
EndIf
; ChallengeResponseB64
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Response\ChallengeResponseB64 = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; Nonce
; Anything bigger than the struct's array is rejected by MsgPackReadBinary, anything smaller by the size check.
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary
Goto DecodeFailed
EndIf
ReadSize = MsgPackReadBinary(*MsgPackData, @*Response\Nonce[0], #BakaShrot_NonceSize)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or ReadSize <> #BakaShrot_NonceSize
Goto DecodeFailed
EndIf
ProcedureReturn *Response
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Response)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,121 @@
;{- Code Header
; ==- Basic Info -================================
; Name: ChunkStoredPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; S2C (and S2P), answers an UploadChunk (or a ReplicateAttachmentChunk): Received
; bytes are stored so far. Complete is 1 once they all are, and their SHA-256
; checked out.
Structure BakaShrot_ChunkStored Extends BakaShrot_PacketBase
Received.q
Complete.l
EndStructure
; Encodes *Stored into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_ChunkStoredPacket_Encode(*Stored.BakaShrot_ChunkStored, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Stored\Magic = #BakaShrot_ProtocolMagic
*Stored\Version = #BakaShrot_ProtocolVersion
*Stored\PacketType = #BakaShrot_PacketType_ChunkStored
If *Stored\Received < 0 Or *Stored\Received > #BakaShrot_MaxAttachmentSize Or *Stored\Complete < 0 Or *Stored\Complete > 1
ProcedureReturn 0
EndIf
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Stored, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Stored\Received) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Stored\Complete) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_ChunkStoredPacket_Decode(*MsgPackData.MsgPackData)
Protected *Stored.BakaShrot_ChunkStored, Value.q
*Stored = AllocateStructure(BakaShrot_ChunkStored)
If Not *Stored
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Stored, *MsgPackData) Or *Stored\PacketType <> #BakaShrot_PacketType_ChunkStored
Goto DecodeFailed
EndIf
; Received
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > #BakaShrot_MaxAttachmentSize
Goto DecodeFailed
EndIf
*Stored\Received = Value
; Complete
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > 1
Goto DecodeFailed
EndIf
*Stored\Complete = Value
ProcedureReturn *Stored
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Stored)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,151 @@
;{- Code Header
; ==- Basic Info -================================
; Name: GetAttachmentPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; C2S, asks for part ChunkIndex (0 for the first) of the attachment of a message.
; Topic, Node: each a name or an id in digits, as GetMessages'. ReadTopics must
; allow the topic.
; Answered with an AttachmentChunk, or a RequestRefused (no such message, no
; attachment, or not here yet: replicated attachments come after their message).
Structure BakaShrot_GetAttachment Extends BakaShrot_PacketBase
Topic.s
Node.s
MessageId.q
ChunkIndex.l
EndStructure
; Encodes *Request into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_GetAttachmentPacket_Encode(*Request.BakaShrot_GetAttachment, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Request\Magic = #BakaShrot_ProtocolMagic
*Request\Version = #BakaShrot_ProtocolVersion
*Request\PacketType = #BakaShrot_PacketType_GetAttachment
If *Request\MessageId < 1 Or *Request\ChunkIndex < 0 Or *Request\ChunkIndex > #BakaShrot_MaxAttachmentChunks
ProcedureReturn 0
EndIf
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Request, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Request\Topic) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Request\Node) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Request\MessageId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Request\ChunkIndex) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_GetAttachmentPacket_Decode(*MsgPackData.MsgPackData)
Protected *Request.BakaShrot_GetAttachment, Value.q
*Request = AllocateStructure(BakaShrot_GetAttachment)
If Not *Request
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Request, *MsgPackData) Or *Request\PacketType <> #BakaShrot_PacketType_GetAttachment
Goto DecodeFailed
EndIf
; Topic
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Request\Topic = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; Node
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Request\Node = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; MessageId
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 1
Goto DecodeFailed
EndIf
*Request\MessageId = Value
; ChunkIndex
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > #BakaShrot_MaxAttachmentChunks
Goto DecodeFailed
EndIf
*Request\ChunkIndex = Value
ProcedureReturn *Request
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Request)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,116 @@
;{- Code Header
; ==- Basic Info -================================
; Name: GetLatestMessagePacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; C2S, asks for the latest message stored for a topic/node combination.
; Topic, Node: each a name or an id in digits (Commons/Networking/Names.pbi).
; The client's [BakaShrot.Client.<name>] ReadTopics must allow the topic.
; Answered with a LatestMessage or a RequestRefused.
Structure BakaShrot_GetLatestMessage Extends BakaShrot_PacketBase
Topic.s
Node.s
EndStructure
; Encodes *Request into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_GetLatestMessagePacket_Encode(*Request.BakaShrot_GetLatestMessage, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Request\Magic = #BakaShrot_ProtocolMagic
*Request\Version = #BakaShrot_ProtocolVersion
*Request\PacketType = #BakaShrot_PacketType_GetLatestMessage
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Request, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Request\Topic) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Request\Node) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_GetLatestMessagePacket_Decode(*MsgPackData.MsgPackData)
Protected *Request.BakaShrot_GetLatestMessage
*Request = AllocateStructure(BakaShrot_GetLatestMessage)
If Not *Request
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Request, *MsgPackData) Or *Request\PacketType <> #BakaShrot_PacketType_GetLatestMessage
Goto DecodeFailed
EndIf
; Topic
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Request\Topic = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; Node
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Request\Node = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
ProcedureReturn *Request
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Request)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,155 @@
;{- Code Header
; ==- Basic Info -================================
; Name: GetMessagesPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; Most messages a GetMessages may ask for.
#BakaShrot_MaxGetMessages = 10000
; C2S, asks for the messages of a topic/node combination stored after
; AfterMessageId (0 for the first ones), in message id order, at most Limit
; (1-#BakaShrot_MaxGetMessages) of them.
; Topic, Node: each a name or an id in digits (Commons/Networking/Names.pbi).
; The client's [BakaShrot.Client.<name>] ReadTopics must allow the topic.
; Answered with a Messages (maybe with none) or a RequestRefused.
Structure BakaShrot_GetMessages Extends BakaShrot_PacketBase
Topic.s
Node.s
AfterMessageId.q
Limit.l
EndStructure
; Encodes *Request into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_GetMessagesPacket_Encode(*Request.BakaShrot_GetMessages, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Request\Magic = #BakaShrot_ProtocolMagic
*Request\Version = #BakaShrot_ProtocolVersion
*Request\PacketType = #BakaShrot_PacketType_GetMessages
If *Request\AfterMessageId < 0 Or *Request\Limit < 1 Or *Request\Limit > #BakaShrot_MaxGetMessages
ProcedureReturn 0
EndIf
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Request, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Request\Topic) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Request\Node) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Request\AfterMessageId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Request\Limit) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_GetMessagesPacket_Decode(*MsgPackData.MsgPackData)
Protected *Request.BakaShrot_GetMessages
Protected Value.q
*Request = AllocateStructure(BakaShrot_GetMessages)
If Not *Request
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Request, *MsgPackData) Or *Request\PacketType <> #BakaShrot_PacketType_GetMessages
Goto DecodeFailed
EndIf
; Topic
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Request\Topic = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; Node
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Request\Node = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; AfterMessageId
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
*Request\AfterMessageId = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Request\AfterMessageId < 0
Goto DecodeFailed
EndIf
; Limit
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 1 Or Value > #BakaShrot_MaxGetMessages
Goto DecodeFailed
EndIf
*Request\Limit = Value
ProcedureReturn *Request
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Request)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,134 @@
;{- Code Header
; ==- Basic Info -================================
; Name: HelloPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; C2S auth request, sent sealed for the server's public key (Connections.pbi).
; ClientNode: who the client is, the node it writes as, a name or an id in
; digits (Commons/Networking/Names.pbi), resolved by the server in its own
; names. Its default topic is the server's to say, not the client's.
; ClientSessionKey: the public half of the client's key pair for this
; connection (Commons/Cryptography/Session.pbi).
Structure BakaShrot_AuthHello Extends BakaShrot_PacketBase
ClientNode.s
ClientPubKeyB64.s
ClientSessionKey.a[#BakaShrot_SessionKeySize]
EndStructure
; Encodes *Hello into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_HelloPacket_Encode(*Hello.BakaShrot_AuthHello, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Hello\Magic = #BakaShrot_ProtocolMagic
*Hello\Version = #BakaShrot_ProtocolVersion
*Hello\PacketType = #BakaShrot_PacketType_ClientHello
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Hello, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Hello\ClientNode) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Hello\ClientPubKeyB64) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteBinary(*MsgPackData, @*Hello\ClientSessionKey[0], #BakaShrot_SessionKeySize) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_HelloPacket_Decode(*MsgPackData.MsgPackData)
Protected *Hello.BakaShrot_AuthHello
Protected ReadSize.q
*Hello = AllocateStructure(BakaShrot_AuthHello)
If Not *Hello
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Hello, *MsgPackData) Or *Hello\PacketType <> #BakaShrot_PacketType_ClientHello
Goto DecodeFailed
EndIf
; ClientNode
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Hello\ClientNode = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; ClientPubKeyB64
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Hello\ClientPubKeyB64 = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; ClientSessionKey
; Anything bigger than the struct's array is rejected by MsgPackReadBinary, anything smaller by the size check.
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary
Goto DecodeFailed
EndIf
ReadSize = MsgPackReadBinary(*MsgPackData, @*Hello\ClientSessionKey[0], #BakaShrot_SessionKeySize)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or ReadSize <> #BakaShrot_SessionKeySize
Goto DecodeFailed
EndIf
ProcedureReturn *Hello
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Hello)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,215 @@
;{- Code Header
; ==- Basic Info -================================
; Name: LatestMessagePacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; S2C, answers a GetLatestMessage with the latest message of that topic/node combination.
; TopicId, NodeId: the server's own ids for them.
; TopicName, NodeName: their names, or their ids in digits if they have none.
; PushedAt: when it was pushed, see Packets.pbi.
Structure BakaShrot_LatestMessage Extends BakaShrot_PacketBase
TopicId.l
NodeId.l
TopicName.s
NodeName.s
MessageId.q
PushedAt.q
JsonData.s
; Its attachment's size in bytes, 0 for none, and whether this server has
; all of it yet (a replicated one comes after its message).
AttachmentSize.q
AttachmentReady.l
EndStructure
; Encodes *Latest into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_LatestMessagePacket_Encode(*Latest.BakaShrot_LatestMessage, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Latest\Magic = #BakaShrot_ProtocolMagic
*Latest\Version = #BakaShrot_ProtocolVersion
*Latest\PacketType = #BakaShrot_PacketType_LatestMessage
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Latest, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Latest\TopicId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Latest\NodeId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Latest\TopicName) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Latest\NodeName) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Latest\MessageId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Latest\PushedAt) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Latest\JsonData) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Latest\AttachmentSize) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Latest\AttachmentReady) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_LatestMessagePacket_Decode(*MsgPackData.MsgPackData)
Protected *Latest.BakaShrot_LatestMessage
Protected Value.q
*Latest = AllocateStructure(BakaShrot_LatestMessage)
If Not *Latest
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Latest, *MsgPackData) Or *Latest\PacketType <> #BakaShrot_PacketType_LatestMessage
Goto DecodeFailed
EndIf
; TopicId
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > 65535
Goto DecodeFailed
EndIf
*Latest\TopicId = Value
; NodeId
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > 65535
Goto DecodeFailed
EndIf
*Latest\NodeId = Value
; TopicName
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Latest\TopicName = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; NodeName
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Latest\NodeName = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; MessageId
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
*Latest\MessageId = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Latest\MessageId < 1
Goto DecodeFailed
EndIf
; PushedAt
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
*Latest\PushedAt = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidTimestamp(*Latest\PushedAt)
Goto DecodeFailed
EndIf
; JsonData
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Latest\JsonData = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; AttachmentSize
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
*Latest\AttachmentSize = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Latest\AttachmentSize < 0 Or *Latest\AttachmentSize > #BakaShrot_MaxAttachmentSize
Goto DecodeFailed
EndIf
; AttachmentReady
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
*Latest\AttachmentReady = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Latest\AttachmentReady < 0 Or *Latest\AttachmentReady > 1
Goto DecodeFailed
EndIf
ProcedureReturn *Latest
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Latest)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,104 @@
;{- Code Header
; ==- Basic Info -================================
; Name: ListNamesPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
XIncludeFile "ResolveNamePacket.pbi"
; C2S, asks for every topic or node the server has, with their ids and names.
; Kind: #BakaShrot_NameKind_Topic or #BakaShrot_NameKind_Node.
; Topics: only those the client may push to or read, unless it may query.
; Answered with a NamesList.
Structure BakaShrot_ListNames Extends BakaShrot_PacketBase
Kind.l
EndStructure
; Encodes *Request into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_ListNamesPacket_Encode(*Request.BakaShrot_ListNames, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Request\Magic = #BakaShrot_ProtocolMagic
*Request\Version = #BakaShrot_ProtocolVersion
*Request\PacketType = #BakaShrot_PacketType_ListNames
*MsgPackData = MsgPackCreate(32)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Request, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Request\Kind) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_ListNamesPacket_Decode(*MsgPackData.MsgPackData)
Protected *Request.BakaShrot_ListNames
Protected Value.q
*Request = AllocateStructure(BakaShrot_ListNames)
If Not *Request
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Request, *MsgPackData) Or *Request\PacketType <> #BakaShrot_PacketType_ListNames
Goto DecodeFailed
EndIf
; Kind
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or (Value <> #BakaShrot_NameKind_Topic And Value <> #BakaShrot_NameKind_Node)
Goto DecodeFailed
EndIf
*Request\Kind = Value
ProcedureReturn *Request
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Request)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,99 @@
;{- Code Header
; ==- Basic Info -================================
; Name: MessagePushedPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; S2C, answers a PushMessage with the id the message was stored under.
Structure BakaShrot_MessagePushed Extends BakaShrot_PacketBase
MessageId.q
EndStructure
; Encodes *Pushed into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_MessagePushedPacket_Encode(*Pushed.BakaShrot_MessagePushed, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Pushed\Magic = #BakaShrot_ProtocolMagic
*Pushed\Version = #BakaShrot_ProtocolVersion
*Pushed\PacketType = #BakaShrot_PacketType_MessagePushed
*MsgPackData = MsgPackCreate(32)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Pushed, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Pushed\MessageId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_MessagePushedPacket_Decode(*MsgPackData.MsgPackData)
Protected *Pushed.BakaShrot_MessagePushed
*Pushed = AllocateStructure(BakaShrot_MessagePushed)
If Not *Pushed
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Pushed, *MsgPackData) Or *Pushed\PacketType <> #BakaShrot_PacketType_MessagePushed
Goto DecodeFailed
EndIf
; MessageId
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
*Pushed\MessageId = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Pushed\MessageId < 1
Goto DecodeFailed
EndIf
ProcedureReturn *Pushed
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Pushed)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,277 @@
;{- Code Header
; ==- Basic Info -================================
; Name: MessagesPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
XIncludeFile "GetMessagesPacket.pbi"
; One message of a Messages answer.
Structure BakaShrot_MessagesEntry
MessageId.q
; When it was pushed, see Packets.pbi.
PushedAt.q
; Its attachment's size in bytes, 0 for none, and whether this server has
; all of it yet (a replicated one comes after its message).
AttachmentSize.q
AttachmentReady.l
JsonData.s
EndStructure
; About how big a Messages answer gets: messages are added while they fit
; in it, and a bigger one goes alone (up to #BakaShrot_MaxMessageSize).
#BakaShrot_MessagesBatchBytes = 1024 * 1024
; Encoded size of the answer's own fields, and of each message on top of its
; JSON, rounded up. Used to stop an answer before it gets over #BakaShrot_MaxPacketSize.
#BakaShrot_MessagesOverhead = 64 + 2 * (#BakaShrot_MaxNameLength + 2)
#BakaShrot_MessagesMessageOverhead = 40
; S2C, answers a GetMessages with the messages of that topic/node combination
; stored after the asked id, in message id order: as many as were asked for,
; or fewer if they didn't fit in about #BakaShrot_MessagesBatchBytes. None
; if there are no more.
; TopicId, NodeId: the server's own ids for them.
; TopicName, NodeName: their names, or their ids in digits if they have none.
; More: 1 if more messages follow the last one, ask again after it.
; On the wire: topic id, node id, topic name, node name, more, message
; count, then each message's id and JSON.
Structure BakaShrot_Messages Extends BakaShrot_PacketBase
TopicId.l
NodeId.l
TopicName.s
NodeName.s
More.l
List Messages.BakaShrot_MessagesEntry()
EndStructure
; Encodes *Answer into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_MessagesPacket_Encode(*Answer.BakaShrot_Messages, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Answer\Magic = #BakaShrot_ProtocolMagic
*Answer\Version = #BakaShrot_ProtocolVersion
*Answer\PacketType = #BakaShrot_PacketType_Messages
If ListSize(*Answer\Messages()) > #BakaShrot_MaxGetMessages
ProcedureReturn 0
EndIf
*MsgPackData = MsgPackCreate(256)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Answer, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Answer\TopicId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Answer\NodeId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Answer\TopicName) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Answer\NodeName) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, Bool(*Answer\More)) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Messages
If MsgPackWriteInteger(*MsgPackData, ListSize(*Answer\Messages())) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
ForEach *Answer\Messages()
If MsgPackWriteInteger(*MsgPackData, *Answer\Messages()\MessageId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Answer\Messages()\PushedAt) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Answer\Messages()\JsonData) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Answer\Messages()\AttachmentSize) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Answer\Messages()\AttachmentReady) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
Next
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; Message ids must be 1 or more, and strictly increasing.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_MessagesPacket_Decode(*MsgPackData.MsgPackData)
Protected *Answer.BakaShrot_Messages
Protected Value.q, Count.q, i.q, PreviousMessageId.q
*Answer = AllocateStructure(BakaShrot_Messages)
If Not *Answer
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Answer, *MsgPackData) Or *Answer\PacketType <> #BakaShrot_PacketType_Messages
Goto DecodeFailed
EndIf
; TopicId
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > 65535
Goto DecodeFailed
EndIf
*Answer\TopicId = Value
; NodeId
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > 65535
Goto DecodeFailed
EndIf
*Answer\NodeId = Value
; TopicName
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Answer\TopicName = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; NodeName
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Answer\NodeName = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; More
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > 1
Goto DecodeFailed
EndIf
*Answer\More = Value
; Message count
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Count = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Count < 0 Or Count > #BakaShrot_MaxGetMessages
Goto DecodeFailed
EndIf
; Messages
PreviousMessageId = 0
For i = 1 To Count
AddElement(*Answer\Messages())
; MessageId
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
*Answer\Messages()\MessageId = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Answer\Messages()\MessageId <= PreviousMessageId
Goto DecodeFailed
EndIf
PreviousMessageId = *Answer\Messages()\MessageId
; PushedAt
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
*Answer\Messages()\PushedAt = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidTimestamp(*Answer\Messages()\PushedAt)
Goto DecodeFailed
EndIf
; JsonData
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Answer\Messages()\JsonData = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; AttachmentSize
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
*Answer\Messages()\AttachmentSize = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Answer\Messages()\AttachmentSize < 0 Or *Answer\Messages()\AttachmentSize > #BakaShrot_MaxAttachmentSize
Goto DecodeFailed
EndIf
; AttachmentReady
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
*Answer\Messages()\AttachmentReady = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Answer\Messages()\AttachmentReady < 0 Or *Answer\Messages()\AttachmentReady > 1
Goto DecodeFailed
EndIf
Next
ProcedureReturn *Answer
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Answer)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,173 @@
;{- Code Header
; ==- Basic Info -================================
; Name: MissingAttachmentsPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; Most attachments one MissingAttachments lists, the next check-in asks again.
#BakaShrot_MaxMissingAttachments = 256
; One attachment the server is missing: of Topic:Node#MessageId (names, never
; digits), from part NextChunk on (0 if it has none of it yet).
Structure BakaShrot_MissingAttachment
Topic.s
Node.s
MessageId.q
NextChunk.l
EndStructure
; S2P, answers a MissingAttachmentsRequest: attachments of messages the server
; has, that it takes from this peer, and doesn't have all of yet. Maybe none.
; On the wire: the count, then each one's topic, node, message id and next chunk.
Structure BakaShrot_MissingAttachments Extends BakaShrot_PacketBase
List Attachments.BakaShrot_MissingAttachment()
EndStructure
; Encodes *Answer into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_MissingAttachmentsPacket_Encode(*Answer.BakaShrot_MissingAttachments, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Answer\Magic = #BakaShrot_ProtocolMagic
*Answer\Version = #BakaShrot_ProtocolVersion
*Answer\PacketType = #BakaShrot_PacketType_MissingAttachments
If ListSize(*Answer\Attachments()) > #BakaShrot_MaxMissingAttachments
ProcedureReturn 0
EndIf
*MsgPackData = MsgPackCreate(256)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Answer, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, ListSize(*Answer\Attachments())) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
ForEach *Answer\Attachments()
If MsgPackWriteString(*MsgPackData, *Answer\Attachments()\Topic) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Answer\Attachments()\Node) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Answer\Attachments()\MessageId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Answer\Attachments()\NextChunk) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
Next
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_MissingAttachmentsPacket_Decode(*MsgPackData.MsgPackData)
Protected *Answer.BakaShrot_MissingAttachments
Protected Value.q, Count.q, i.q
*Answer = AllocateStructure(BakaShrot_MissingAttachments)
If Not *Answer
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Answer, *MsgPackData) Or *Answer\PacketType <> #BakaShrot_PacketType_MissingAttachments
Goto DecodeFailed
EndIf
; Count
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Count = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Count < 0 Or Count > #BakaShrot_MaxMissingAttachments
Goto DecodeFailed
EndIf
For i = 1 To Count
AddElement(*Answer\Attachments())
; Topic
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Answer\Attachments()\Topic = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidName(*Answer\Attachments()\Topic)
Goto DecodeFailed
EndIf
; Node
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Answer\Attachments()\Node = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidName(*Answer\Attachments()\Node)
Goto DecodeFailed
EndIf
; MessageId
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
*Answer\Attachments()\MessageId = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Answer\Attachments()\MessageId < 1
Goto DecodeFailed
EndIf
; NextChunk
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > #BakaShrot_MaxAttachmentChunks
Goto DecodeFailed
EndIf
*Answer\Attachments()\NextChunk = Value
Next
ProcedureReturn *Answer
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Answer)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,88 @@
;{- Code Header
; ==- Basic Info -================================
; Name: MissingAttachmentsRequestPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; P2S, asks which attachments the server is still missing from this peer, once
; the messages are caught up. Only the base fields.
; Answered with a MissingAttachments, or a RequestRefused.
Structure BakaShrot_MissingAttachmentsRequest Extends BakaShrot_PacketBase
EndStructure
; Encodes *Request into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_MissingAttachmentsRequestPacket_Encode(*Request.BakaShrot_MissingAttachmentsRequest, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Request\Magic = #BakaShrot_ProtocolMagic
*Request\Version = #BakaShrot_ProtocolVersion
*Request\PacketType = #BakaShrot_PacketType_MissingAttachmentsRequest
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Request, *MsgPackData)
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_MissingAttachmentsRequestPacket_Decode(*MsgPackData.MsgPackData)
Protected *Request.BakaShrot_MissingAttachmentsRequest
*Request = AllocateStructure(BakaShrot_MissingAttachmentsRequest)
If Not *Request
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Request, *MsgPackData) Or *Request\PacketType <> #BakaShrot_PacketType_MissingAttachmentsRequest
Goto DecodeFailed
EndIf
ProcedureReturn *Request
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Request)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,133 @@
;{- Code Header
; ==- Basic Info -================================
; Name: NameResolvedPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
XIncludeFile "ResolveNamePacket.pbi"
; S2C, answers a ResolveName.
; Kind: the one asked about, #BakaShrot_NameKind_Topic or #BakaShrot_NameKind_Node.
; Id: the server's own id for it, 0-65535.
; Name: its name, "" if it has none.
Structure BakaShrot_NameResolved Extends BakaShrot_PacketBase
Kind.l
Id.l
Name.s
EndStructure
; Encodes *Answer into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_NameResolvedPacket_Encode(*Answer.BakaShrot_NameResolved, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Answer\Magic = #BakaShrot_ProtocolMagic
*Answer\Version = #BakaShrot_ProtocolVersion
*Answer\PacketType = #BakaShrot_PacketType_NameResolved
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Answer, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Answer\Kind) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Answer\Id) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Answer\Name) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_NameResolvedPacket_Decode(*MsgPackData.MsgPackData)
Protected *Answer.BakaShrot_NameResolved
Protected Value.q
*Answer = AllocateStructure(BakaShrot_NameResolved)
If Not *Answer
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Answer, *MsgPackData) Or *Answer\PacketType <> #BakaShrot_PacketType_NameResolved
Goto DecodeFailed
EndIf
; Kind
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or (Value <> #BakaShrot_NameKind_Topic And Value <> #BakaShrot_NameKind_Node)
Goto DecodeFailed
EndIf
*Answer\Kind = Value
; Id
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > #BakaShrot_MaxId
Goto DecodeFailed
EndIf
*Answer\Id = Value
; Name
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Answer\Name = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
ProcedureReturn *Answer
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Answer)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,194 @@
;{- Code Header
; ==- Basic Info -================================
; Name: NamesListPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
XIncludeFile "ResolveNamePacket.pbi"
; One topic or node of a NamesList.
; Origin: where its name comes from, "config" (named in the config) or "id"
; (unnamed, Name is ""). See Server/Storage/Names.pbi.
Structure BakaShrot_NameEntry
Id.l
Name.s
Origin.s
EndStructure
#BakaShrot_MaxNamesListEntries = 65536
; S2C, answers a ListNames, by id.
; Kind: the one asked about. Truncated: 1 if there were more than fit in one
; packet, the first ones by id are listed.
; On the wire: Kind, Truncated, entry count, then each entry's id, name and origin.
Structure BakaShrot_NamesList Extends BakaShrot_PacketBase
Kind.l
Truncated.l
List Entries.BakaShrot_NameEntry()
EndStructure
; Encoded size of the packet's own fields, and of each entry on top of its
; name and origin, rounded up. Used to cut a list before it gets over
; #BakaShrot_MaxPacketSize.
#BakaShrot_NamesListOverhead = 64
#BakaShrot_NamesListEntryOverhead = 16
; Encodes *List into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_NamesListPacket_Encode(*List.BakaShrot_NamesList, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*List\Magic = #BakaShrot_ProtocolMagic
*List\Version = #BakaShrot_ProtocolVersion
*List\PacketType = #BakaShrot_PacketType_NamesList
If ListSize(*List\Entries()) > #BakaShrot_MaxNamesListEntries
ProcedureReturn 0
EndIf
*MsgPackData = MsgPackCreate(256)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*List, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *List\Kind) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, Bool(*List\Truncated)) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, ListSize(*List\Entries())) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
ForEach *List\Entries()
If MsgPackWriteInteger(*MsgPackData, *List\Entries()\Id) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *List\Entries()\Name) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *List\Entries()\Origin) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
Next
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_NamesListPacket_Decode(*MsgPackData.MsgPackData)
Protected *List.BakaShrot_NamesList
Protected Value.q, Count.q, i.q
*List = AllocateStructure(BakaShrot_NamesList)
If Not *List
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*List, *MsgPackData) Or *List\PacketType <> #BakaShrot_PacketType_NamesList
Goto DecodeFailed
EndIf
; Kind
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or (Value <> #BakaShrot_NameKind_Topic And Value <> #BakaShrot_NameKind_Node)
Goto DecodeFailed
EndIf
*List\Kind = Value
; Truncated
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > 1
Goto DecodeFailed
EndIf
*List\Truncated = Value
; Entries
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Count = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Count < 0 Or Count > #BakaShrot_MaxNamesListEntries
Goto DecodeFailed
EndIf
For i = 1 To Count
AddElement(*List\Entries())
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > #BakaShrot_MaxId
Goto DecodeFailed
EndIf
*List\Entries()\Id = Value
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*List\Entries()\Name = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*List\Entries()\Origin = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
Next
ProcedureReturn *List
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*List)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,133 @@
;{- Code Header
; ==- Basic Info -================================
; Name: PushMessagePacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; C2S, asks the server to store a JSON message.
; Topic: where to push it, a name or an id in digits (Commons/Networking/Names.pbi),
; "" for the topic of the client's authenticated identity. The client's
; [BakaShrot.Client.<name>] PushTopics must allow it.
; The node is always the client's authenticated one, the client can't pick it.
; UploadId: the attachment uploaded for it (UploadStart, all of it stored), 0 for none.
; Answered with a MessagePushed or a RequestRefused.
Structure BakaShrot_PushMessage Extends BakaShrot_PacketBase
Topic.s
JsonData.s
UploadId.q
EndStructure
; Encodes *Push into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_PushMessagePacket_Encode(*Push.BakaShrot_PushMessage, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Push\Magic = #BakaShrot_ProtocolMagic
*Push\Version = #BakaShrot_ProtocolVersion
*Push\PacketType = #BakaShrot_PacketType_PushMessage
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Push, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Push\Topic) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Push\JsonData) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If *Push\UploadId < 0 Or MsgPackWriteInteger(*MsgPackData, *Push\UploadId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_PushMessagePacket_Decode(*MsgPackData.MsgPackData)
Protected *Push.BakaShrot_PushMessage
*Push = AllocateStructure(BakaShrot_PushMessage)
If Not *Push
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Push, *MsgPackData) Or *Push\PacketType <> #BakaShrot_PacketType_PushMessage
Goto DecodeFailed
EndIf
; Topic
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Push\Topic = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; JsonData
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Push\JsonData = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; UploadId
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
*Push\UploadId = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Push\UploadId < 0
Goto DecodeFailed
EndIf
ProcedureReturn *Push
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Push)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,101 @@
;{- Code Header
; ==- Basic Info -================================
; Name: QueryRequestPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; C2S, a raw SQL query to run read-only on the server's database.
; Must be a single SELECT (or WITH ... SELECT), anything after the first statement is ignored.
; Answered with a QueryResult or a RequestRefused.
Structure BakaShrot_QueryRequest Extends BakaShrot_PacketBase
Sql.s
EndStructure
; Encodes *Request into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_QueryRequestPacket_Encode(*Request.BakaShrot_QueryRequest, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Request\Magic = #BakaShrot_ProtocolMagic
*Request\Version = #BakaShrot_ProtocolVersion
*Request\PacketType = #BakaShrot_PacketType_QueryRequest
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Request, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Request\Sql) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_QueryRequestPacket_Decode(*MsgPackData.MsgPackData)
Protected *Request.BakaShrot_QueryRequest
*Request = AllocateStructure(BakaShrot_QueryRequest)
If Not *Request
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Request, *MsgPackData) Or *Request\PacketType <> #BakaShrot_PacketType_QueryRequest
Goto DecodeFailed
EndIf
; Sql
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Request\Sql = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
ProcedureReturn *Request
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Request)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,101 @@
;{- Code Header
; ==- Basic Info -================================
; Name: QueryResultPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; S2C, answers a QueryRequest with its rows, as JSON:
; {"columns": ["name", ...], "rows": [["value", ...], ...]}
; Every value is a string, or null for NULL: PureBasic doesn't report SQLite's column types.
Structure BakaShrot_QueryResult Extends BakaShrot_PacketBase
JsonResult.s
EndStructure
; Encodes *Result into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_QueryResultPacket_Encode(*Result.BakaShrot_QueryResult, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Result\Magic = #BakaShrot_ProtocolMagic
*Result\Version = #BakaShrot_ProtocolVersion
*Result\PacketType = #BakaShrot_PacketType_QueryResult
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Result, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Result\JsonResult) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_QueryResultPacket_Decode(*MsgPackData.MsgPackData)
Protected *Result.BakaShrot_QueryResult
*Result = AllocateStructure(BakaShrot_QueryResult)
If Not *Result
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Result, *MsgPackData) Or *Result\PacketType <> #BakaShrot_PacketType_QueryResult
Goto DecodeFailed
EndIf
; JsonResult
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Result\JsonResult = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
ProcedureReturn *Result
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Result)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,181 @@
;{- Code Header
; ==- Basic Info -================================
; Name: ReplicateAttachmentChunkPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; P2S, part ChunkIndex of the attachment of Topic:Node#MessageId (names, never
; digits), a message the server already has, as MissingAttachments asked for.
; The size and SHA-256 came with the message (ReplicateMessages).
; Answered with a ChunkStored, or a RequestRefused.
Structure BakaShrot_ReplicateAttachmentChunk Extends BakaShrot_PacketBase
Topic.s
Node.s
MessageId.q
ChunkIndex.l
*Data
DataSize.l
EndStructure
; Encodes *Chunk into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_ReplicateAttachmentChunkPacket_Encode(*Chunk.BakaShrot_ReplicateAttachmentChunk, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Chunk\Magic = #BakaShrot_ProtocolMagic
*Chunk\Version = #BakaShrot_ProtocolVersion
*Chunk\PacketType = #BakaShrot_PacketType_ReplicateAttachmentChunk
If Not BakaShrot_IsValidName(*Chunk\Topic) Or Not BakaShrot_IsValidName(*Chunk\Node) Or *Chunk\MessageId < 1 Or *Chunk\ChunkIndex < 0 Or *Chunk\ChunkIndex > #BakaShrot_MaxAttachmentChunks Or Not *Chunk\Data Or *Chunk\DataSize < 1 Or *Chunk\DataSize > #BakaShrot_AttachmentChunkSize
ProcedureReturn 0
EndIf
*MsgPackData = MsgPackCreate(#BakaShrot_AttachmentChunkSize + 256)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Chunk, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Chunk\Topic) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Chunk\Node) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Chunk\MessageId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Chunk\ChunkIndex) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteBinary(*MsgPackData, *Chunk\Data, *Chunk\DataSize) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Frees a decoded *Chunk and the data it holds.
Procedure BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk.BakaShrot_ReplicateAttachmentChunk)
If Not *Chunk
ProcedureReturn
EndIf
If *Chunk\Data
FreeMemory(*Chunk\Data)
EndIf
FreeStructure(*Chunk)
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with BakaShrot_ReplicateAttachmentChunkPacket_Free().
Procedure.i BakaShrot_ReplicateAttachmentChunkPacket_Decode(*MsgPackData.MsgPackData)
Protected *Chunk.BakaShrot_ReplicateAttachmentChunk, Value.q
*Chunk = AllocateStructure(BakaShrot_ReplicateAttachmentChunk)
If Not *Chunk
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Chunk, *MsgPackData) Or *Chunk\PacketType <> #BakaShrot_PacketType_ReplicateAttachmentChunk
Goto DecodeFailed
EndIf
; Topic
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Chunk\Topic = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidName(*Chunk\Topic)
Goto DecodeFailed
EndIf
; Node
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Chunk\Node = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidName(*Chunk\Node)
Goto DecodeFailed
EndIf
; MessageId
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 1
Goto DecodeFailed
EndIf
*Chunk\MessageId = Value
; ChunkIndex
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > #BakaShrot_MaxAttachmentChunks
Goto DecodeFailed
EndIf
*Chunk\ChunkIndex = Value
; Data
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary
Goto DecodeFailed
EndIf
; A copy, freed with the packet (_Free()).
*Chunk\Data = MsgPackCopyBinary(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not *Chunk\Data
Goto DecodeFailed
EndIf
*Chunk\DataSize = MemorySize(*Chunk\Data)
If *Chunk\DataSize > #BakaShrot_AttachmentChunkSize
Goto DecodeFailed
EndIf
ProcedureReturn *Chunk
; Everything read so far is tainted, drop it.
DecodeFailed:
BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,242 @@
;{- Code Header
; ==- Basic Info -================================
; Name: ReplicateMessagesPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; One message of a ReplicateMessages batch.
; PushedAt: when it was pushed to its origin (Packets.pbi), stored as is.
; AttachmentSize, AttachmentSha256: its attachment's, 0 for none. The data
; itself follows on its own, once the messages are caught up
; (MissingAttachments, ReplicateAttachmentChunk).
Structure BakaShrot_ReplicatedMessage
MessageId.q
PushedAt.q
JsonData.s
AttachmentSize.q
AttachmentSha256.a[#BakaShrot_Sha256Size]
EndStructure
; Most messages a batch may carry, whatever the sender's PeerBatchSize.
; #BakaShrot_ReplicateBatchBytes usually stops a batch well before that.
#BakaShrot_MaxReplicateBatch = 10000
; About how big a batch gets: messages are added while they fit in it, and
; a bigger one goes alone (up to #BakaShrot_MaxMessageSize). Small enough to
; keep each batch's transaction and memory short, like when 64 KB was the
; biggest packet.
#BakaShrot_ReplicateBatchBytes = 65536
; Encoded size of a batch's own fields, and of each message on top of its
; JSON, rounded up. Used to stop a batch before it gets over #BakaShrot_MaxPacketSize.
#BakaShrot_ReplicateBatchOverhead = 64 + 2 * (#BakaShrot_MaxNameLength + 2)
#BakaShrot_ReplicateMessageOverhead = 70
; Peer -> Server, messages the server is missing for one topic/node, in
; message id order, with the message ids they were stored under on their
; origin. Topic and Node are names, never ids (Commons/Networking/Names.pbi):
; the server stores them under its own ids for those names, and refuses
; names it doesn't know.
; On the wire: topic, node, message count, then each message's id, PushedAt,
; JSON, attachment size and SHA-256.
; Answered with a MessagePushed carrying the last message's id, or a RequestRefused.
Structure BakaShrot_ReplicateMessages Extends BakaShrot_PacketBase
Topic.s
Node.s
List Messages.BakaShrot_ReplicatedMessage()
EndStructure
; Encodes *Batch into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_ReplicateMessagesPacket_Encode(*Batch.BakaShrot_ReplicateMessages, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Batch\Magic = #BakaShrot_ProtocolMagic
*Batch\Version = #BakaShrot_ProtocolVersion
*Batch\PacketType = #BakaShrot_PacketType_ReplicateMessages
If ListSize(*Batch\Messages()) < 1 Or ListSize(*Batch\Messages()) > #BakaShrot_MaxReplicateBatch
ProcedureReturn 0
EndIf
*MsgPackData = MsgPackCreate(256)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Batch, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Batch\Topic) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Batch\Node) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Messages
If MsgPackWriteInteger(*MsgPackData, ListSize(*Batch\Messages())) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
ForEach *Batch\Messages()
If MsgPackWriteInteger(*MsgPackData, *Batch\Messages()\MessageId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Batch\Messages()\PushedAt) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Batch\Messages()\JsonData) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Batch\Messages()\AttachmentSize) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Empty without an attachment.
If *Batch\Messages()\AttachmentSize > 0
If MsgPackWriteBinary(*MsgPackData, @*Batch\Messages()\AttachmentSha256[0], #BakaShrot_Sha256Size) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
ElseIf MsgPackWriteBinary(*MsgPackData, @*Batch\Messages()\AttachmentSha256[0], 0) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
Next
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; Message ids must be 1 or more, and strictly increasing.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_ReplicateMessagesPacket_Decode(*MsgPackData.MsgPackData)
Protected *Batch.BakaShrot_ReplicateMessages
Protected Value.q, Count.q, i.q, PreviousMessageId.q, ReadSize.q
*Batch = AllocateStructure(BakaShrot_ReplicateMessages)
If Not *Batch
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Batch, *MsgPackData) Or *Batch\PacketType <> #BakaShrot_PacketType_ReplicateMessages
Goto DecodeFailed
EndIf
; Topic
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Batch\Topic = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidName(*Batch\Topic)
Goto DecodeFailed
EndIf
; Node
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Batch\Node = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidName(*Batch\Node)
Goto DecodeFailed
EndIf
; Message count
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Count = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Count < 1 Or Count > #BakaShrot_MaxReplicateBatch
Goto DecodeFailed
EndIf
; Messages
PreviousMessageId = 0
For i = 1 To Count
AddElement(*Batch\Messages())
; MessageId
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
*Batch\Messages()\MessageId = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Batch\Messages()\MessageId <= PreviousMessageId
Goto DecodeFailed
EndIf
PreviousMessageId = *Batch\Messages()\MessageId
; PushedAt
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
*Batch\Messages()\PushedAt = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidTimestamp(*Batch\Messages()\PushedAt)
Goto DecodeFailed
EndIf
; JsonData
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Batch\Messages()\JsonData = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; AttachmentSize
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
*Batch\Messages()\AttachmentSize = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Batch\Messages()\AttachmentSize < 0 Or *Batch\Messages()\AttachmentSize > #BakaShrot_MaxAttachmentSize
Goto DecodeFailed
EndIf
; AttachmentSha256: 32 bytes with an attachment, empty without.
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary
Goto DecodeFailed
EndIf
ReadSize = MsgPackReadBinary(*MsgPackData, @*Batch\Messages()\AttachmentSha256[0], #BakaShrot_Sha256Size)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or (ReadSize <> #BakaShrot_Sha256Size And *Batch\Messages()\AttachmentSize > 0) Or (ReadSize <> 0 And *Batch\Messages()\AttachmentSize = 0)
Goto DecodeFailed
EndIf
Next
ProcedureReturn *Batch
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Batch)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,121 @@
;{- Code Header
; ==- Basic Info -================================
; Name: RequestRefusedPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; S2C, answers a request the server won't fulfill, the connection stays open.
; Code: what kind of refusal, 1-#BakaShrot_Refused_Max, one of the
; #BakaShrot_Refused_* in Client/BakaShrot_ErrorCodes.pbi: what clients act
; on (protocol 6). Reason is only meant for logs and humans.
Structure BakaShrot_RequestRefused Extends BakaShrot_PacketBase
Code.l
Reason.s
EndStructure
; Encodes *Refused into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_RequestRefusedPacket_Encode(*Refused.BakaShrot_RequestRefused, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Refused\Magic = #BakaShrot_ProtocolMagic
*Refused\Version = #BakaShrot_ProtocolVersion
*Refused\PacketType = #BakaShrot_PacketType_RequestRefused
If Not BakaShrot_IsRefusalCode(*Refused\Code)
ProcedureReturn 0
EndIf
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Refused, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Refused\Code) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Refused\Reason) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_RequestRefusedPacket_Decode(*MsgPackData.MsgPackData)
Protected *Refused.BakaShrot_RequestRefused, Value.q
*Refused = AllocateStructure(BakaShrot_RequestRefused)
If Not *Refused
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Refused, *MsgPackData) Or *Refused\PacketType <> #BakaShrot_PacketType_RequestRefused
Goto DecodeFailed
EndIf
; Code
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsRefusalCode(Value)
Goto DecodeFailed
EndIf
*Refused\Code = Value
; Reason
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Refused\Reason = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
ProcedureReturn *Refused
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Refused)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,124 @@
;{- Code Header
; ==- Basic Info -================================
; Name: ResolveNamePacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; What a ResolveName / NameResolved is about.
#BakaShrot_NameKind_Topic = 1
#BakaShrot_NameKind_Node = 2
; C2S, asks for the server's id and name of a topic or node.
; Kind: #BakaShrot_NameKind_Topic or #BakaShrot_NameKind_Node.
; Ref: a name or an id in digits (Commons/Networking/Names.pbi).
; Answered with a NameResolved, or a RequestRefused if the server doesn't
; know it, or if it's a topic the client may neither push to nor read
; (unless it may query, which reads everything anyway).
Structure BakaShrot_ResolveName Extends BakaShrot_PacketBase
Kind.l
Ref.s
EndStructure
; Encodes *Request into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_ResolveNamePacket_Encode(*Request.BakaShrot_ResolveName, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Request\Magic = #BakaShrot_ProtocolMagic
*Request\Version = #BakaShrot_ProtocolVersion
*Request\PacketType = #BakaShrot_PacketType_ResolveName
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Request, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Request\Kind) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Request\Ref) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_ResolveNamePacket_Decode(*MsgPackData.MsgPackData)
Protected *Request.BakaShrot_ResolveName
Protected Value.q
*Request = AllocateStructure(BakaShrot_ResolveName)
If Not *Request
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Request, *MsgPackData) Or *Request\PacketType <> #BakaShrot_PacketType_ResolveName
Goto DecodeFailed
EndIf
; Kind
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or (Value <> #BakaShrot_NameKind_Topic And Value <> #BakaShrot_NameKind_Node)
Goto DecodeFailed
EndIf
*Request\Kind = Value
; Ref
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Request\Ref = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
ProcedureReturn *Request
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Request)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,296 @@
;{- Code Header
; ==- Basic Info -================================
; Name: SyncStatePacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; Highest message id a node has for a topic/node id combination.
Structure BakaShrot_SyncPair
TopicId.l
NodeId.l
MessageId.q
EndStructure
; One of the sender's ids, and what it's called: its name, or its id in
; digits if it has none (Commons/Networking/Names.pbi).
Structure BakaShrot_SyncName
Id.l
Name.s
EndStructure
; Biggest lists accepted, the packet size limit keeps the real ones well under it.
#BakaShrot_MaxSyncTopics = 65536
#BakaShrot_MaxSyncNodes = 65536
#BakaShrot_MaxSyncPairs = 65536
#BakaShrot_MaxSyncPatterns = 4096
; Server -> Peer, answers a SyncStateRequest, at every check-in. Ids are the
; sender's own, names are what the peer matches them by: each server has its
; own ids. Only named topics and nodes replicate, and only those named on
; both servers: this is how the peer learns which names this server knows,
; so it never sends anything this server would refuse.
; Topics: the named topics it takes from this peer (its AcceptTopics).
; Nodes: the named nodes it takes from this peer (its AcceptNodes).
; TopicPatterns, NodePatterns: the wildcards ("*", "sensors.*") of its
; AcceptTopics / AcceptNodes: it also takes names it doesn't have yet if
; they match one (Commons/Networking/Names.pbi).
; Pairs: the highest message id it has for each topic/node of those.
; A combination that isn't listed has no message yet.
; Names are names, never ids in digits.
; On the wire: topic count, each topic's id and name, node count, each
; node's id and name, topic pattern count, each pattern, node pattern
; count, each pattern, pair count, then each pair's topic id, node id and
; message id.
Structure BakaShrot_SyncState Extends BakaShrot_PacketBase
List Topics.BakaShrot_SyncName()
List Nodes.BakaShrot_SyncName()
List TopicPatterns.s()
List NodePatterns.s()
List Pairs.BakaShrot_SyncPair()
EndStructure
; Writes a list of ids and names, with its count first.
Procedure.i BakaShrot_SyncStatePacket_WriteNames(*MsgPackData.MsgPackData, List Names.BakaShrot_SyncName())
If MsgPackWriteInteger(*MsgPackData, ListSize(Names())) <> #MsgPack_Error_Success
ProcedureReturn #False
EndIf
ForEach Names()
If MsgPackWriteInteger(*MsgPackData, Names()\Id) <> #MsgPack_Error_Success
ProcedureReturn #False
EndIf
If MsgPackWriteString(*MsgPackData, Names()\Name) <> #MsgPack_Error_Success
ProcedureReturn #False
EndIf
Next
ProcedureReturn #True
EndProcedure
; Writes a list of patterns, with its count first.
Procedure.i BakaShrot_SyncStatePacket_WritePatterns(*MsgPackData.MsgPackData, List Patterns.s())
If MsgPackWriteInteger(*MsgPackData, ListSize(Patterns())) <> #MsgPack_Error_Success
ProcedureReturn #False
EndIf
ForEach Patterns()
If MsgPackWriteString(*MsgPackData, Patterns()) <> #MsgPack_Error_Success
ProcedureReturn #False
EndIf
Next
ProcedureReturn #True
EndProcedure
; Encodes *State into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_SyncStatePacket_Encode(*State.BakaShrot_SyncState, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*State\Magic = #BakaShrot_ProtocolMagic
*State\Version = #BakaShrot_ProtocolVersion
*State\PacketType = #BakaShrot_PacketType_SyncState
If ListSize(*State\Topics()) > #BakaShrot_MaxSyncTopics Or ListSize(*State\Nodes()) > #BakaShrot_MaxSyncNodes Or ListSize(*State\Pairs()) > #BakaShrot_MaxSyncPairs
ProcedureReturn 0
EndIf
If ListSize(*State\TopicPatterns()) > #BakaShrot_MaxSyncPatterns Or ListSize(*State\NodePatterns()) > #BakaShrot_MaxSyncPatterns
ProcedureReturn 0
EndIf
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*State, *MsgPackData)
Goto EncodeFailed
EndIf
If Not BakaShrot_SyncStatePacket_WriteNames(*MsgPackData, *State\Topics())
Goto EncodeFailed
EndIf
If Not BakaShrot_SyncStatePacket_WriteNames(*MsgPackData, *State\Nodes())
Goto EncodeFailed
EndIf
If Not BakaShrot_SyncStatePacket_WritePatterns(*MsgPackData, *State\TopicPatterns())
Goto EncodeFailed
EndIf
If Not BakaShrot_SyncStatePacket_WritePatterns(*MsgPackData, *State\NodePatterns())
Goto EncodeFailed
EndIf
; Pairs
If MsgPackWriteInteger(*MsgPackData, ListSize(*State\Pairs())) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
ForEach *State\Pairs()
If MsgPackWriteInteger(*MsgPackData, *State\Pairs()\TopicId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *State\Pairs()\NodeId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *State\Pairs()\MessageId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
Next
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Reads one integer within Minimum-Maximum into *Value\q.
; Returns #False if it's not an integer, couldn't be read, or is out of range.
Procedure.i BakaShrot_SyncStatePacket_ReadInteger(*MsgPackData.MsgPackData, *Value.Quad, Minimum.q, Maximum.q)
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
ProcedureReturn #False
EndIf
*Value\q = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Value\q < Minimum Or *Value\q > Maximum
ProcedureReturn #False
EndIf
ProcedureReturn #True
EndProcedure
; Reads a list of ids and names, with its count first. Every name must be a
; valid name, not an id in digits.
; Returns #False if anything is invalid.
Procedure.i BakaShrot_SyncStatePacket_ReadNames(*MsgPackData.MsgPackData, List Names.BakaShrot_SyncName(), MaxCount.i)
Protected Count.q, Value.q, i.q
If Not BakaShrot_SyncStatePacket_ReadInteger(*MsgPackData, @Count, 0, MaxCount)
ProcedureReturn #False
EndIf
For i = 1 To Count
AddElement(Names())
If Not BakaShrot_SyncStatePacket_ReadInteger(*MsgPackData, @Value, 0, #BakaShrot_MaxId)
ProcedureReturn #False
EndIf
Names()\Id = Value
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
ProcedureReturn #False
EndIf
Names()\Name = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidName(Names()\Name)
ProcedureReturn #False
EndIf
Next
ProcedureReturn #True
EndProcedure
; Reads a list of patterns, with its count first. Each one must be a valid
; pattern, see Commons/Networking/Names.pbi.
; Returns #False if anything is invalid.
Procedure.i BakaShrot_SyncStatePacket_ReadPatterns(*MsgPackData.MsgPackData, List Patterns.s())
Protected Count.q, i.q
If Not BakaShrot_SyncStatePacket_ReadInteger(*MsgPackData, @Count, 0, #BakaShrot_MaxSyncPatterns)
ProcedureReturn #False
EndIf
For i = 1 To Count
AddElement(Patterns())
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
ProcedureReturn #False
EndIf
Patterns() = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidPattern(Patterns())
ProcedureReturn #False
EndIf
Next
ProcedureReturn #True
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_SyncStatePacket_Decode(*MsgPackData.MsgPackData)
Protected *State.BakaShrot_SyncState
Protected Count.q, Value.q, i.q
*State = AllocateStructure(BakaShrot_SyncState)
If Not *State
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*State, *MsgPackData) Or *State\PacketType <> #BakaShrot_PacketType_SyncState
Goto DecodeFailed
EndIf
If Not BakaShrot_SyncStatePacket_ReadNames(*MsgPackData, *State\Topics(), #BakaShrot_MaxSyncTopics)
Goto DecodeFailed
EndIf
If Not BakaShrot_SyncStatePacket_ReadNames(*MsgPackData, *State\Nodes(), #BakaShrot_MaxSyncNodes)
Goto DecodeFailed
EndIf
If Not BakaShrot_SyncStatePacket_ReadPatterns(*MsgPackData, *State\TopicPatterns())
Goto DecodeFailed
EndIf
If Not BakaShrot_SyncStatePacket_ReadPatterns(*MsgPackData, *State\NodePatterns())
Goto DecodeFailed
EndIf
; Pairs
If Not BakaShrot_SyncStatePacket_ReadInteger(*MsgPackData, @Count, 0, #BakaShrot_MaxSyncPairs)
Goto DecodeFailed
EndIf
For i = 1 To Count
AddElement(*State\Pairs())
If Not BakaShrot_SyncStatePacket_ReadInteger(*MsgPackData, @Value, 0, #BakaShrot_MaxId)
Goto DecodeFailed
EndIf
*State\Pairs()\TopicId = Value
If Not BakaShrot_SyncStatePacket_ReadInteger(*MsgPackData, @Value, 0, #BakaShrot_MaxId)
Goto DecodeFailed
EndIf
*State\Pairs()\NodeId = Value
If Not BakaShrot_SyncStatePacket_ReadInteger(*MsgPackData, @Value, 1, 9223372036854775807)
Goto DecodeFailed
EndIf
*State\Pairs()\MessageId = Value
Next
ProcedureReturn *State
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*State)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,82 @@
;{- Code Header
; ==- Basic Info -================================
; Name: SyncStateRequestPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; Peer -> Server, asks for the server's sync state, to know which messages it's missing.
; Answered with a SyncState or a RequestRefused. Only carries the base fields.
Structure BakaShrot_SyncStateRequest Extends BakaShrot_PacketBase
EndStructure
; Encodes *Request into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_SyncStateRequestPacket_Encode(*Request.BakaShrot_SyncStateRequest, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Request\Magic = #BakaShrot_ProtocolMagic
*Request\Version = #BakaShrot_ProtocolVersion
*Request\PacketType = #BakaShrot_PacketType_SyncStateRequest
*MsgPackData = MsgPackCreate(16)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Request, *MsgPackData)
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_SyncStateRequestPacket_Decode(*MsgPackData.MsgPackData)
Protected *Request.BakaShrot_SyncStateRequest
*Request = AllocateStructure(BakaShrot_SyncStateRequest)
If Not *Request
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Request, *MsgPackData) Or *Request\PacketType <> #BakaShrot_PacketType_SyncStateRequest
FreeStructure(*Request)
ProcedureReturn 0
EndIf
ProcedureReturn *Request
EndProcedure
@@ -0,0 +1,151 @@
;{- Code Header
; ==- Basic Info -================================
; Name: UploadChunkPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; C2S, the next part of an upload: ChunkIndex (0 for the first) of UploadId.
; Answered with a ChunkStored, or a RequestRefused (the upload is then dropped).
Structure BakaShrot_UploadChunk Extends BakaShrot_PacketBase
UploadId.q
ChunkIndex.l
*Data
DataSize.l
EndStructure
; Encodes *Chunk into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_UploadChunkPacket_Encode(*Chunk.BakaShrot_UploadChunk, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Chunk\Magic = #BakaShrot_ProtocolMagic
*Chunk\Version = #BakaShrot_ProtocolVersion
*Chunk\PacketType = #BakaShrot_PacketType_UploadChunk
If *Chunk\UploadId < 1 Or *Chunk\ChunkIndex < 0 Or *Chunk\ChunkIndex > #BakaShrot_MaxAttachmentChunks Or Not *Chunk\Data Or *Chunk\DataSize < 1 Or *Chunk\DataSize > #BakaShrot_AttachmentChunkSize
ProcedureReturn 0
EndIf
*MsgPackData = MsgPackCreate(#BakaShrot_AttachmentChunkSize + 256)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Chunk, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Chunk\UploadId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Chunk\ChunkIndex) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteBinary(*MsgPackData, *Chunk\Data, *Chunk\DataSize) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Frees a decoded *Chunk and the data it holds.
Procedure BakaShrot_UploadChunkPacket_Free(*Chunk.BakaShrot_UploadChunk)
If Not *Chunk
ProcedureReturn
EndIf
If *Chunk\Data
FreeMemory(*Chunk\Data)
EndIf
FreeStructure(*Chunk)
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with BakaShrot_UploadChunkPacket_Free().
Procedure.i BakaShrot_UploadChunkPacket_Decode(*MsgPackData.MsgPackData)
Protected *Chunk.BakaShrot_UploadChunk, Value.q
*Chunk = AllocateStructure(BakaShrot_UploadChunk)
If Not *Chunk
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Chunk, *MsgPackData) Or *Chunk\PacketType <> #BakaShrot_PacketType_UploadChunk
Goto DecodeFailed
EndIf
; UploadId
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 1
Goto DecodeFailed
EndIf
*Chunk\UploadId = Value
; ChunkIndex
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > #BakaShrot_MaxAttachmentChunks
Goto DecodeFailed
EndIf
*Chunk\ChunkIndex = Value
; Data
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary
Goto DecodeFailed
EndIf
; A copy, freed with the packet (_Free()).
*Chunk\Data = MsgPackCopyBinary(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not *Chunk\Data
Goto DecodeFailed
EndIf
*Chunk\DataSize = MemorySize(*Chunk\Data)
If *Chunk\DataSize > #BakaShrot_AttachmentChunkSize
Goto DecodeFailed
EndIf
ProcedureReturn *Chunk
; Everything read so far is tainted, drop it.
DecodeFailed:
BakaShrot_UploadChunkPacket_Free(*Chunk)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,138 @@
;{- Code Header
; ==- Basic Info -================================
; Name: UploadStartPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; C2S, starts uploading an attachment, before pushing the message it goes with
; (PushMessage's UploadId): Size bytes (1 to #BakaShrot_MaxAttachmentSize, and the
; server's [BakaShrot.Server] MaxAttachmentSize), whose SHA-256 is Sha256.
; Topic: where the message will be pushed, as PushMessage's: "" for the client's
; own. The client's PushTopics must allow it.
; Answered with an UploadStarted, or a RequestRefused.
Structure BakaShrot_UploadStart Extends BakaShrot_PacketBase
Topic.s
Size.q
Sha256.a[#BakaShrot_Sha256Size]
EndStructure
; Encodes *Start into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_UploadStartPacket_Encode(*Start.BakaShrot_UploadStart, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Start\Magic = #BakaShrot_ProtocolMagic
*Start\Version = #BakaShrot_ProtocolVersion
*Start\PacketType = #BakaShrot_PacketType_UploadStart
If *Start\Size < 1 Or *Start\Size > #BakaShrot_MaxAttachmentSize
ProcedureReturn 0
EndIf
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Start, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Start\Topic) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Start\Size) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteBinary(*MsgPackData, @*Start\Sha256[0], #BakaShrot_Sha256Size) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_UploadStartPacket_Decode(*MsgPackData.MsgPackData)
Protected *Start.BakaShrot_UploadStart, Value.q, ReadSize.q
*Start = AllocateStructure(BakaShrot_UploadStart)
If Not *Start
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Start, *MsgPackData) Or *Start\PacketType <> #BakaShrot_PacketType_UploadStart
Goto DecodeFailed
EndIf
; Topic
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Start\Topic = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; Size
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 1 Or Value > #BakaShrot_MaxAttachmentSize
Goto DecodeFailed
EndIf
*Start\Size = Value
; Sha256
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary
Goto DecodeFailed
EndIf
; Anything bigger than the struct's array is rejected by MsgPackReadBinary, anything smaller by the size check.
ReadSize = MsgPackReadBinary(*MsgPackData, @*Start\Sha256[0], #BakaShrot_Sha256Size)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or ReadSize <> #BakaShrot_Sha256Size
Goto DecodeFailed
EndIf
ProcedureReturn *Start
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Start)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,120 @@
;{- Code Header
; ==- Basic Info -================================
; Name: UploadStartedPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; S2C, answers an UploadStart: send the data with UploadChunks for UploadId, in
; order, ChunkSize bytes each (the last one what's left).
Structure BakaShrot_UploadStarted Extends BakaShrot_PacketBase
UploadId.q
ChunkSize.l
EndStructure
; Encodes *Started into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_UploadStartedPacket_Encode(*Started.BakaShrot_UploadStarted, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Started\Magic = #BakaShrot_ProtocolMagic
*Started\Version = #BakaShrot_ProtocolVersion
*Started\PacketType = #BakaShrot_PacketType_UploadStarted
If *Started\UploadId < 1 Or *Started\ChunkSize < 1 Or *Started\ChunkSize > #BakaShrot_AttachmentChunkSize
ProcedureReturn 0
EndIf
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Started, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Started\UploadId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Started\ChunkSize) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_UploadStartedPacket_Decode(*MsgPackData.MsgPackData)
Protected *Started.BakaShrot_UploadStarted, Value.q
*Started = AllocateStructure(BakaShrot_UploadStarted)
If Not *Started
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Started, *MsgPackData) Or *Started\PacketType <> #BakaShrot_PacketType_UploadStarted
Goto DecodeFailed
EndIf
; UploadId
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 1
Goto DecodeFailed
EndIf
*Started\UploadId = Value
; ChunkSize
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 1 Or Value > #BakaShrot_AttachmentChunkSize
Goto DecodeFailed
EndIf
*Started\ChunkSize = Value
ProcedureReturn *Started
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Started)
ProcedureReturn 0
EndProcedure
+141
View File
@@ -0,0 +1,141 @@
;{- Code Header
; ==- Basic Info -================================
; Name: SocketWait.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; BakaShrot Socket waits
;
; Sleeps until one of a few sockets has something to read (data, a new
; connection, or a disconnect), instead of polling NetworkClientEvent() /
; NetworkServerEvent() with Delay():
; BakaShrot_SocketSet_Clear(@Set)
; BakaShrot_SocketSet_Add(@Set, ConnectionID(Connection)) ; or ServerID()
; BakaShrot_SocketSet_Wait(@Set, TimeoutMs)
; ... then NetworkClientEvent() / NetworkServerEvent() as usual.
; Only call it once those returned #PB_NetworkEvent_None: PureBasic may
; already hold events it hasn't returned yet, that select() can't see.
;
; Windows: select() from ws2_32. Elsewhere: a plain Delay(1) for now.
; ============================================================================
; Most sockets in one wait, the others are left out (they're still served,
; just with up to TimeoutMs of delay).
#BakaShrot_SocketSet_MaxSockets = 1024
CompilerIf #PB_Compiler_OS = #PB_OS_Windows
; Same layout as Winsock's fd_set, with a bigger array: Winsock reads
; Count entries, whatever FD_SETSIZE says.
Structure BakaShrot_SocketSet
Count.l
CompilerIf #PB_Compiler_Processor = #PB_Processor_x64
Padding.l
CompilerEndIf
Sockets.i[#BakaShrot_SocketSet_MaxSockets]
EndStructure
Structure BakaShrot_TimeVal
Seconds.l
Microseconds.l
EndStructure
Prototype.l BakaShrot_Select_Prototype(Ignored.l, *ReadSet, *WriteSet, *ErrorSet, *Timeout)
Global BakaShrot_Select.BakaShrot_Select_Prototype = 0
Global BakaShrot_SelectLoaded.i = #False
Global BakaShrot_SelectMutex.i = CreateMutex()
Procedure BakaShrot_SocketSet_Load()
Protected Library.i
LockMutex(BakaShrot_SelectMutex)
If Not BakaShrot_SelectLoaded
Library = OpenLibrary(#PB_Any, "ws2_32.dll")
If Library
BakaShrot_Select = GetFunction(Library, "select")
EndIf
BakaShrot_SelectLoaded = #True
EndIf
UnlockMutex(BakaShrot_SelectMutex)
EndProcedure
Procedure BakaShrot_SocketSet_Clear(*Set.BakaShrot_SocketSet)
*Set\Count = 0
EndProcedure
Procedure BakaShrot_SocketSet_Add(*Set.BakaShrot_SocketSet, Socket.i)
If Socket And *Set\Count < #BakaShrot_SocketSet_MaxSockets
*Set\Sockets[*Set\Count] = Socket
*Set\Count + 1
EndIf
EndProcedure
; Waits until a socket of *Set is readable, for up to TimeoutMs.
; Returns #True if one is (or select() failed, to be safe), #False if it
; timed out. *Set is overwritten, clear and fill it again before reusing it.
Procedure.i BakaShrot_SocketSet_Wait(*Set.BakaShrot_SocketSet, TimeoutMs.i)
Protected Timeout.BakaShrot_TimeVal, Result.l
If Not BakaShrot_SelectLoaded
BakaShrot_SocketSet_Load()
EndIf
If Not BakaShrot_Select Or *Set\Count = 0
Delay(1)
ProcedureReturn #True
EndIf
Timeout\Seconds = TimeoutMs / 1000
Timeout\Microseconds = (TimeoutMs % 1000) * 1000
Result = BakaShrot_Select(0, *Set, 0, 0, @Timeout)
If Result < 0
; A socket closed meanwhile by another thread, most likely.
Delay(1)
ProcedureReturn #True
EndIf
ProcedureReturn Bool(Result > 0)
EndProcedure
CompilerElse
Structure BakaShrot_SocketSet
Count.l
EndStructure
Procedure BakaShrot_SocketSet_Clear(*Set.BakaShrot_SocketSet)
*Set\Count = 0
EndProcedure
Procedure BakaShrot_SocketSet_Add(*Set.BakaShrot_SocketSet, Socket.i)
*Set\Count + 1
EndProcedure
Procedure.i BakaShrot_SocketSet_Wait(*Set.BakaShrot_SocketSet, TimeoutMs.i)
Delay(1)
ProcedureReturn #True
EndProcedure
CompilerEndIf
; Waits until Socket is readable, for up to TimeoutMs.
Procedure.i BakaShrot_WaitSocket(Socket.i, TimeoutMs.i)
Protected Set.BakaShrot_SocketSet
BakaShrot_SocketSet_Clear(@Set)
BakaShrot_SocketSet_Add(@Set, Socket)
ProcedureReturn BakaShrot_SocketSet_Wait(@Set, TimeoutMs)
EndProcedure
+86
View File
@@ -0,0 +1,86 @@
;{- Code Header
; ==- Basic Info -================================
; Name: Signal.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; BakaShrot Signal
;
; Wakes up a thread waiting for something, instead of it polling with Delay():
; Waiter: BakaShrot_Signal_Wait(Signal, TimeoutMs), then checks for work.
; Waker: does the work's setup, then BakaShrot_Signal_Set(Signal).
; Signals don't stack: several Set() before a Wait() wake it once, so the
; waiter must handle everything that's there once woken. A Set() before the
; Wait() isn't lost, the Wait() returns right away.
;
; Windows: an auto-reset event. Elsewhere: a semaphore polled every ms, until
; something better is needed there.
; ============================================================================
CompilerIf #PB_Compiler_OS = #PB_OS_Windows
; Returns 0 on failure.
Procedure.i BakaShrot_Signal_Create()
; Auto-reset, not set.
ProcedureReturn CreateEvent_(0, #False, #False, 0)
EndProcedure
Procedure BakaShrot_Signal_Set(Signal.i)
SetEvent_(Signal)
EndProcedure
; Waits until Signal is set, for up to TimeoutMs.
; Returns #True if it was set, #False if it timed out.
Procedure.i BakaShrot_Signal_Wait(Signal.i, TimeoutMs.i)
; WAIT_OBJECT_0
ProcedureReturn Bool(WaitForSingleObject_(Signal, TimeoutMs) = 0)
EndProcedure
Procedure BakaShrot_Signal_Free(Signal.i)
CloseHandle_(Signal)
EndProcedure
CompilerElse
Procedure.i BakaShrot_Signal_Create()
ProcedureReturn CreateSemaphore(0)
EndProcedure
Procedure BakaShrot_Signal_Set(Signal.i)
SignalSemaphore(Signal)
EndProcedure
Procedure.i BakaShrot_Signal_Wait(Signal.i, TimeoutMs.i)
Protected StartTime.i = ElapsedMilliseconds()
Repeat
If TrySemaphore(Signal)
; Doesn't stack, like the Windows version.
While TrySemaphore(Signal)
Wend
ProcedureReturn #True
EndIf
If ElapsedMilliseconds() - StartTime >= TimeoutMs
ProcedureReturn #False
EndIf
Delay(1)
ForEver
EndProcedure
Procedure BakaShrot_Signal_Free(Signal.i)
FreeSemaphore(Signal)
EndProcedure
CompilerEndIf
+162
View File
@@ -0,0 +1,162 @@
# Attachments
A message can have **one attachment**: any bytes (a file, a photo, a dump),
of any size up to the server's `MaxAttachmentSize` (default 1 GB, at most
1 TB). Most messages have none. The message's JSON can say what it is: the
attachment itself has no name or type, only its size and SHA-256.
Protocol version 4. Code: `Server/Storage/Attachments.pbi` (storage),
`Server/Networking/Networking.pbi` (requests), `Server/Networking/Peers.pbi`
(replication), `Client/BakaShrot_Client.pbi` (DLL).
## The rules
- **Sent and stored in parts** of 1 MB (`#BakaShrot_AttachmentChunkSize`, the
last one what's left), one request each: neither end ever holds a whole
attachment in memory (a 512 MB one: the server peaked at 15 MB).
- **Checked with its SHA-256**, given before the first part: the server
checks it once all parts are in (uploads and replicated ones alike), the
client when it reads one back.
- **A message is only stored once all of its attachment is.** The client
uploads it first, then pushes the message with the upload's id: readers
never see a message whose attachment is missing on the server it was
pushed to. Messages stay immutable.
- **Replicated after the messages**, separately: a peer gets the message
first (with the attachment's size and SHA-256), then its data once the
messages are caught up. So on the other servers, a message can be there
before its attachment: `AttachmentReady` tells.
- **Deleted with its message** (the retention): its parts go a few at a
time, in the background.
## Pushing one
```
C -> S UploadStart(topic, size, sha256) same permissions as pushing to that
topic, size <= MaxAttachmentSize
S -> C UploadStarted(upload id, 1 MB)
C -> S UploadChunk(upload id, 0, data) in order, each the right size
S -> C ChunkStored(received, complete 0)
...
C -> S UploadChunk(upload id, last, data)
server: reads all of it back, checks the SHA-256 (or drops it, refused)
S -> C ChunkStored(received = size, complete 1)
C -> S PushMessage(topic, json, upload id)
server: the upload must be this client's (its node), for that topic,
complete: the message and its attachment are stored together
S -> C MessagePushed(id)
```
- An upload belongs to the client's node and the topic it was started for.
- One not pushed within `UploadTimeout` seconds (default 3600) is deleted.
- A refused part doesn't drop the upload; a SHA-256 mismatch does.
- The DLL does all of it in `BakaShrot_PushMessageWithFile()` /
`_WithData()`; it reads a file twice (the SHA-256 first).
## Reading one
```
C -> S GetAttachment(topic, node, message id, part) same permissions as reading
S -> C AttachmentChunk(ids, message id, size, sha256, part, data)
```
Any part, in any order (the DLL reads them in order). Refused if the
message has none, or if it isn't all on this server yet (replicated after
its message), or isn't kept here (bigger than this server's
`MaxAttachmentSize`).
## Replicating
On its link to a peer, at every check-in, once the messages are sent
(`Design/Packets.md`, Replication):
```
P -> S MissingAttachmentsRequest
S -> P MissingAttachments([(topic, node, message id, next part)])
up to 256 attachments of messages S has,
from what it takes from P, not all here
P: for each one it has, all of it, and sends S (SendTopics/SendNodes):
P -> S ReplicateAttachmentChunk(topic, node, message id, part, data)
S -> P ChunkStored(received, complete)
... from the part S asked for: resumes after a dropped link
S: once all of it is in, checks the SHA-256 its message came with:
ready, or dropped and asked for again from the start
```
- A server relays what it has: an attachment that isn't on P either is
skipped, S asks again at the next check-in, maybe of another peer.
- An attachment bigger than S's `MaxAttachmentSize` is marked not kept
when its message arrives: S never asks for it.
- A message skipped on arrival (past S's max age) has no attachment row:
never asked for either.
## Storage (schema v7, `db_schema_v7.dbml`)
| Table | What |
|---|---|
| `attachments` | A message's: size, SHA-256, its blob once any of it is here, state: 0 missing, 1 receiving, 2 ready, 3 not kept. |
| `blobs` | The data of one attachment: whose (topic, node), size, SHA-256, bytes received, state: 0 receiving, 1 complete (an upload waiting for its message), 2 attached, 3 to delete. |
| `blob_chunks` | Its parts, 1 MB each, by (blob, index). |
- Triggers: deleting a message deletes its `attachments` row, which marks
its blob to delete. The retention thread (`Retention.pbi`) deletes those
parts 32 at a time, along with uploads past `UploadTimeout`, every
`RetentionInterval` seconds, retention rules or not.
- Parts are written through the writer (each one its own transaction), read
on each thread's own connection.
- SQLite reuses the freed pages; `vacuum` gives the space back to the disk.
## In the clients
| | DLL | Python | Tools |
|---|---|---|---|
| Push with one | `BakaShrot_PushMessageWithFile(Topic, Json, Path)`, `_WithData(Topic, Json, *Data, Size)` | `push(data, topic, attachment=bytes or path)` | `PushMessage -a <File>` |
| Does a message have one | `BakaShrot_GetMessageAttachmentSize()`, `BakaShrot_IsMessageAttachmentReady()` | `Message.attachment_size`, `.attachment_ready` | `GetLatestMessage` prints it |
| Read one | `BakaShrot_SaveAttachment(Topic, Node, Id, Path)`, `_LoadAttachment()` + `_GetAttachmentData()` | `save_attachment()`, `get_attachment()` | `GetAttachment <Topic> <Node> <Id> <OutFile>` |
## Speed
On one machine (i5-13500, localhost, PB 5.73): 5 MB up in ~80 ms and down
in ~65 ms through the tools; 512 MB up in 8.5 s (SHA-256 on both ends
included) and down in 3.9 s. One part per round trip: over a slow link,
latency adds up (1000 round trips per GB).
## Tested
- `Tests/Attachments-Test.ps1` (39 checks, two servers, ports 12410-12411):
one part, several, an exact multiple, one byte; none; replicated
identical; not kept past the other server's limit; too big to push;
deleted with its message, parts included.
- `Tests/AttachmentEdges-Test.ps1` (51 checks, ports 12413-12414), with a
raw protocol client (`Tests/AttachmentEdgeClient.pb`) for what the DLL
never sends:
- a wrong SHA-256: refused at the last part, the upload dropped, pushing
with it refused;
- parts out of order, of the wrong size, repeated, past the end, from
another client: refused, the upload goes on;
- someone else's upload, the wrong topic, attached twice, an unknown id,
too big, a topic the client may not push to or read: refused, the
connection stays up;
- uploads left behind (half sent, complete but never pushed): kept within
`UploadTimeout`, deleted past it (10.7 s for 10), then refused;
- replication resuming: the receiver killed at ~45 MB of 400 MB,
restarted: what it had committed is still there, the sender goes on
from that part, the result is identical;
- a byte flipped in the sender's database: the client refuses it
(SHA-256), the peer drops it, serves nothing, and asks again.
- `check_bakashrot.py` (Python): bytes and files, round trips, refusals.
## Not done
- **Resuming an upload** after a dropped connection: the parts are kept
until `UploadTimeout`, but the DLL starts over. (Replication resumes.)
- **Several parts in flight**, for links with high latency.
- **A corrupted copy is sent again and again.** If a server's own stored
copy is damaged (disk, a bug), its peers drop it at every check-in and
ask again: the whole attachment is re-sent every `PeerSyncInterval`
(6 times in 6 s in the test). The server itself never notices, it serves
the damaged parts to clients too (they refuse them, by their SHA-256).
Fix: when a peer answers "doesn't match", the sender checks its own copy
(`HashStorageBlob()`); if it's damaged, it marks it missing, so it gets a
good one back from another peer, and stops sending it. Details, and how
the test should change: `Notes.md`, open item 3.
- **No deduplication**: the same file attached twice is stored twice.
+154
View File
@@ -0,0 +1,154 @@
# Certificates - X.509 with Ed25519
Status (2026-11-13): an include in `Commons/Cryptography/`, tested on its
own and against OpenSSL, **not used by anything yet**. Next: a tool that
generates certificates, then the server and the client loading and
checking them (see the end).
## Why it's written here
- **libsodium has no X.509 or ASN.1**, so the DER and the certificate
structure are PureBasic (`Der.pbi`, `X509.pbi`). Every bit of
cryptography is still libsodium's: Ed25519 signatures, SHA-256 (key ids,
fingerprints), random serials, Base64 (PEM) and hex, seeds to key pairs
(PKCS#8).
- **Not the OS's APIs:** Windows' CryptoAPI can't check Ed25519
certificates, and the identity keys are Ed25519 already. Not OpenSSL
either: another library to ship and load on both OSes, for what's a few
hundred lines of DER. One code for Windows and Linux.
- **Standard certificates all the same:** OpenSSL reads them, verifies
chains of them, reads the private keys, and they read and check OpenSSL's
(`Tests/X509-Test.ps1`).
## Files
| File | What |
|---|---|
| `Commons/Cryptography/Der.pbi` | ASN.1 DER: a reader (strict) and a writer, integers, OIDs (any arc size), times, strings, bit strings. |
| `Commons/Cryptography/X509.pbi` | Certificates: reading, issuing, checking, PEM, PKCS#8 private keys. Includes `Der.pbi` and `Libsodium.pbi`. |
| `Tests/X509Test.pb` | 131 checks on its own, 145 with OpenSSL's certificates. |
| `Tests/X509-Test.ps1` | Runs it, makes OpenSSL's certificates for it, checks its own with OpenSSL. |
## Reading
- `BakaShrot_X509_Parse(*Der, Size)`, `_ParsePem(Text)`, `_Load(Path)`
(PEM or DER, by its first byte) give a `BakaShrot_X509Certificate`, freed
with `BakaShrot_X509_Free()`. Failures give 0 and a code.
- **Any certificate is read** (RSA, ECDSA...): version, serial, names,
validity, algorithms, every extension. Only Ed25519 ones have their key
and signature (`HasEd25519Key`, `HasEd25519Signature`), and only they can
be checked or issue others (`Unsupported` otherwise).
- **Strict DER:** shortest lengths and integers, no indefinite lengths, real
dates, no NUL in strings, the inner and outer signature algorithms the same
bytes, an extension once at most, v1 never written as such, nothing after
the certificate. A reader never reads past its buffer. Every truncation of
a certificate is refused, and of its 503 one-bit flips, the 335 that still
parse all fail the checks.
- **Known extensions** fill fields: BasicConstraints (`IsCa`,
`PathLength`), KeyUsage (`KeyUsage`, `#BakaShrot_X509_KeyUsage_*` flags),
the key ids (`SubjectKeyId`, `AuthorityKeyId`, hex). The others stay as
they are (`Extensions()`: OID, critical, DER value).
- Names keep their attributes in order (`Subject\Attributes()`): OID, text,
string type, RDN index. `BakaShrot_X509_NameGet(@\Subject, "CN")`,
`_NameToString()` ("CN=kitchen, OU=clients").
## Issuing
`BakaShrot_X509_Issue(*Template, *Issuer, *IssuerPrivateKey, *OutSize)`,
the issuer 0 for a self-signed one. The template: subject, validity, the
subject's public key, CA or not and its path length, key usage, the custom
extensions. It writes:
- v3, a random positive 16-byte serial (or the template's), Ed25519.
- The issuer's subject as the issuer certificate encodes it (so names match
byte for byte).
- Names one attribute per RDN: `C` as a PrintableString (2 letters),
`emailAddress` and `DC` as IA5String, the rest UTF8String.
- UTCTime from 1950 to 2049, GeneralizedTime otherwise (RFC 5280).
- BasicConstraints (critical, always), KeyUsage (critical, if any), the
subject's key id (the first 20 bytes of the key's SHA-256, RFC 7093) and
the issuer's, then the template's extensions in order.
It refuses: a private key that isn't the issuer's (or the subject's when
self-signed), an issuer that isn't a CA or lacks keyCertSign, a path length
on a leaf, NotAfter before NotBefore, a name it can't write.
## Checking
Each returns `#BakaShrot_X509_Ok` (0) or what's wrong
(`BakaShrot_X509_ErrorName()`): BadSignature, NotYetValid, Expired,
IssuerMismatch, NotCa, PathTooLong, UnknownCritical, Unsupported...
- `BakaShrot_X509_CheckIssuedBy(*Cert, *Issuer, Now, Handled)`: one link.
The issuer names match (as encoded), the key ids too when both have one,
the issuer may issue, the signature is its key's, `*Cert` is valid at
`Now` (both ends included), no critical extension is left unhandled.
- `BakaShrot_X509_VerifyChain(Chain(), *Root, Now, Handled)`: the leaf
first, then each issuer up to the one the trusted `*Root` issued. Every
link as above, the root valid and a CA, the path lengths kept.
- `_CheckSignature()`, `_CheckValidity()`, `_CanIssue()`,
`_CheckCriticalExtensions()` on their own.
- `Now` is seconds since 1970 UTC: `BakaShrot_X509_Now()`.
- `Handled` lists the critical extensions the caller understands
(`"oid;oid"`). RFC 5280: a critical extension a reader doesn't know makes
the certificate unusable.
## Custom extensions
- **BakaShrot's OID arc:** `#BakaShrot_Oid_Arc`,
`2.25.232025699926348910519219903487382490981`, a UUID OID (ITU-T X.667),
which needs no registration (made from a random UUID, 2026-11-13). It
could be swapped for a registered enterprise number (`1.3.6.1.4.1.<PEN>`)
as long as no certificate was issued for real with it.
- **Extensions:** `#BakaShrot_Oid_Extensions` (the arc + `.1`) + `.<n>`,
numbered as they're defined, a number never reused. None is defined yet;
the tests use 9000 and up.
- **Writing:** `BakaShrot_X509_AddTextExtension(@Template, Oid, Text)`
(UTF8String), `_AddIntegerExtension()`, `_AddExtension()` (any one DER
element, a `BakaShrot_DerWriter` makes them), critical or not.
- **Reading:** `BakaShrot_X509_GetExtensionText()`,
`_GetExtensionInteger()`, or `_FindExtension()` and the raw value.
- **Critical or not:** critical means "refuse me if you don't know me". For
fields only BakaShrot reads, non-critical is the usual choice; critical
if a reader that ignores it would grant too much (then pass it in
`Handled`).
- OpenSSL writes them too (`<oid> = ASN1:UTF8String:...` in an extensions
file, as the test does), and shows them by OID.
## Private keys and PEM
- `BakaShrot_X509_PrivateKeyToPem()` / `_PrivateKeyFromPem()`: PKCS#8
(RFC 8410), what `openssl genpkey -algorithm ed25519` writes, not
encrypted. Reading takes v1 and v2 (with the public key, which must
match). The seed and the DER are wiped after use.
- `BakaShrot_Pem_Encode()` / `_Decode()` for any label, LF line endings;
CRLF, spaces and text around the block are fine on reading.
## Threads
No globals. A parsed certificate is only read once made, and its names and
extensions are arrays, not lists (`ForEach` moves a list's current element,
see `CLAUDE.md`): any number of threads may check against the same CA.
## Not done
- **Using it:** a tool generating a CA, server and client certificates and
keys; the server and client loading them, checking the other end's. How
they'd fit the handshake (what replaces or joins the `PublicKeys` lists,
the ClientHello carrying a certificate, the 4 KB handshake frame limit) is
to decide with the client auth rework: a protocol change either way.
- **Revocation:** no CRL or OCSP. Short validities, or a list of revoked
serials or fingerprints in the configs, if it's ever needed.
- **Not interpreted:** SubjectAltName, ExtendedKeyUsage, NameConstraints,
policies. They're read as raw extensions; marked critical (NameConstraints
usually is), they make a certificate refused unless in `Handled`.
- **Names are matched as encoded**, byte for byte, not with RFC 5280's
case-insensitive comparison. Fine for certificates issued here, which
copy the issuer's encoding; another CA's could differ in string types.
- Multi-valued RDNs are read, not written (one attribute per RDN).
Encrypted PKCS#8, certificate requests (CSR): not done.
- `BakaShrot_X509_Now()` repeats `BakaShrot_NowUtcMs()`
(`Server/Storage/Storage.pbi`) in seconds, so `Commons/` doesn't depend on
the server: one could move to `Commons/` for both.
- Tested on Windows (5.73, 6.40 C) only so far; the Linux side
(`gettimeofday`, `-lsodium`) is the same code as elsewhere but unrun.
+231
View File
@@ -0,0 +1,231 @@
# Cryptography - what's done, what isn't
Status (protocol 3, 2026-11-08): every connection is encrypted and
authenticated, and both ends prove who they are.
- The client seals its Hello for the server's public key: only that server
can read it, and nobody watching learns who connects.
- Both ends make a key pair for this connection, sign the exchange with
their identity keys, and get the connection's keys from it.
- Everything after the ChallengeRequest is encrypted, both ways.
Still not done: messages aren't signed by the node that wrote them, and
keys sit in plain-text ini files (see the end).
## Library
- **libsodium 1.0.22**, the official MSVC release's dynamic build.
- `Build.ps1` extracts it from `Libs/libsodium-1.0.22-msvc.zip` to
`Libs/libsodium/{x64,x86}/`, and copies `libsodium.dll` next to the
programs.
- Linux would link `-lsodium` instead (untested).
- It needs the Visual C++ runtime (`vcruntime140.dll`), packaged with the
release from `Libs/redist/` (`Libs/redist/README.md`).
- **Wrappers:** `Commons/Cryptography/Libsodium.pbi` is the only file that
imports it. On top of it, nothing else calls libsodium:
- `Cipher.pbi`: encrypting and decrypting buffers with a connection's keys.
- `Session.pbi`: the handshake's part, the sealed Hello and the key
exchange.
- The handshake itself, what's signed and in which order, is in
`Commons/Networking/Connections.pbi`.
- **Imported functions:**
| libsodium | Wrapper | Notes |
|---|---|---|
| `sodium_init` | `InitCryptography()` | Called before any use; repeated calls are fine. |
| `crypto_sign_keypair` | `GenerateKeyPair()` | Used by `Tools/BakaShrotGenerateKeyPairs`. |
| `crypto_sign_detached` | `EncodeData()`, `BakaShrot_SignHandshake()` | **Signs**, the name `EncodeData` is wrong. |
| `crypto_sign_verify_detached` | `DecodeData()`, `BakaShrot_VerifyHandshake()` | **Verifies**, the name `DecodeData` is wrong. |
| `crypto_sign_ed25519_sk_to_pk` | `GetPublicKeyFromPrivateKey()` | Lets a server only keep its private key in its config. |
| `crypto_sign_ed25519_pk_to_curve25519` / `_sk_to_curve25519` | `BakaShrot_Session_SealHello()` / `_LoadHelloKeys()` | The X25519 key of an Ed25519 identity, for the sealed Hello. |
| `crypto_box_seal` / `_seal_open` | `BakaShrot_Session_SealHello()` / `_OpenHello()` | The Hello, sealed for the server. |
| `crypto_kx_keypair` | `BakaShrot_Session_NewKeyPair()` | One per connection and end. |
| `crypto_kx_client_session_keys` / `_server_session_keys` | `BakaShrot_Session_StartClient()` / `_StartServer()` | A key per direction, into the cipher. |
| `crypto_aead_xchacha20poly1305_ietf_encrypt` / `_decrypt` | `BakaShrot_Cipher_Encrypt()`, `_EncryptTo()` / `_Decrypt()` | Every packet after the ChallengeRequest. |
| `crypto_aead_xchacha20poly1305_ietf_keygen` | `BakaShrot_Cipher_GenerateKey()` | Tests only, real keys come from the handshake. |
| `sodium_memzero` | `BakaShrot_Cipher_Clear()`, the `_Clear*()` of `Session.pbi` | Wipes keys. |
| `crypto_hash_sha256` | `BakaShrot_X509_KeyId()`, `_Fingerprint()` | Certificates' key ids and fingerprints (`Design/Certificates.md`). |
| `randombytes_buf` | `BakaShrot_X509_Issue()` | Random serial numbers. |
| `crypto_sign_seed_keypair` / `crypto_sign_ed25519_sk_to_seed` | `BakaShrot_X509_PrivateKeyFromPem()` / `_PrivateKeyToPem()` | PKCS#8 files hold the 32-byte seed. |
| `sodium_bin2base64` / `_base642bin` / `_base64_encoded_len` | `BakaShrot_Pem_Encode()` / `_Decode()` | PEM; line breaks skipped. |
| `sodium_bin2hex` / `_hex2bin` | `BakaShrot_X509_Hex()` / `_FromHex()` | Serials, key ids. |
- **Base64 helpers**, in `Libsodium.pbi`:
- `EncodeKeyToString()` encodes a key or signature.
- `DecodeKeyFromString()` refuses anything that doesn't decode to exactly
the expected size.
## Keys
- **Identity keys: Ed25519.** A private key is 64 bytes (libsodium's
format: the seed followed by the public key), a public key 32, a
signature 64. One key both signs and receives the sealed Hello (its X25519
form, libsodium's conversion).
- **Stored as Base64 in ini files, in plain text:**
- A server's own key: `[BakaShrot] PrivateKey`. The server logs its
public key when it starts.
- Who it trusts: `[BakaShrot.Client.<name>] PublicKeys` and
`[BakaShrot.Peer.<name>] PublicKey`. The peer's is also the server it
expects at the other end of its link, so it's required.
- A client's: whatever the app passes to `BakaShrot_SetPrivateKey()`,
`BakaShrot_SetPublicKey()` and `BakaShrot_SetServerPublicKey()` (the
server's). The tools and `bakashrot.py` read them from `client.ini`:
`PrivateKey`, `PublicKey`, `ServerPublicKey`.
- **Connection keys: X25519**, made for each connection by both ends, the
secrets wiped once the cipher has its keys. So a recorded connection
can't be decrypted later, even with both identity keys (forward secrecy).
- **Generated** by `Tools/BakaShrotGenerateKeyPairs`, which `Build.ps1` runs
on every build.
- **Wiping:**
- Wiped from memory after use: BakaShrotGenerateKeyPairs; a server's key when it stops, and
its peer links'; every connection's keys when it ends.
- Not wiped: the client DLL's global copy of its private key, and the
config structures holding the Base64 text.
- **No rotation or revocation**, other than editing the configs and
restarting.
## Randomness
The challenge (32 bytes) and the nonce (32 bytes) come from PureBasic's
`OpenCryptRandom()` / `CryptRandomData()`, which use the OS's secure
generator. The connection key pairs and the sealed Hello's throwaway key
come from libsodium's.
## The handshake
See `Design/Packets.md` for the packets, `Connections.pbi` for the code.
The client knows the server's public key beforehand.
1. **Hello, sealed** (`crypto_box_seal` for the server's key): the client's
node (the one it writes as), its Base64 public key, and the public half
of a key pair it made for this connection.
2. The server opens it (another server can't: abort), decodes the key and
checks that a `[BakaShrot.Client.<name>]` has this `Node` and lists this
key.
3. **ChallengeRequest, in plain text:** a fresh random challenge and nonce,
the public half of the server's own pair for this connection, and the
server's signature of the transcript.
4. The client checks the signature with the server's public key: it's the
right server, and nobody swapped a half on the way. Both ends get the
connection's keys from both pairs (`crypto_kx`), every packet from here
on is encrypted (the cipher, below).
5. **ChallengeResponse:** the client signs the transcript, and echoes the
nonce.
6. The server checks the nonce is the one it issued for this connection,
and the signature against the key from the Hello. **AuthAccepted.**
**The transcript** (`BakaShrot_HandshakeTranscript`, 208 bytes) is what
both sign: a label (`"BakaShrot3 srv"` or `"BakaShrot3 cli"`, padded to 16
bytes, so one end's signature can't pass as the other's), the client's and
the server's identity keys, both halves, the challenge and the nonce. So
each signature only holds for this connection, between these two.
What that gets, and why:
- **Only the right server gets anywhere.** The Hello is sealed for it, and
the client won't send anything else until the server signed this
connection's halves with the key the client expects.
- **Only the registered client authenticates.** Same as before: it signs
the challenge, now along with the halves.
- **Nobody in the middle.** Swapping a half breaks a signature; relaying
untouched gets the relay nothing, it doesn't have the secrets.
- **Replays fail.** A replayed Hello gets a fresh challenge and server half,
which the replayer can't answer: the client's half is the client's. A
replayed packet later fails the cipher's sequence check.
- **Hijacking an authenticated connection fails:** an injected packet
doesn't decrypt, the connection is aborted.
- **Hidden from someone watching:** who connects (sealed Hello) and
everything after the ChallengeRequest. Not hidden: that it's BakaShrot,
the server's half and signature, packet sizes and timing.
The nonce is redundant with the challenge (both are fresh, random, and
signed), but it's harmless and kept as designed.
## The cipher (`Commons/Cryptography/Cipher.pbi`)
The crypto of the data itself, so no packet handler or framing code has to
do any: a `BakaShrot_Cipher` per connection holds the keys, then takes
buffers. `BakaShrot_ConnectionMetadata\Cipher`, set up by the handshake.
- **`BakaShrot_Cipher_InitWithKeys(*Cipher, *SendKey, *ReceiveKey)`**: a key
per direction, as the handshake gives them (refuses the same key twice).
Or **`_Init(*Cipher, *Key, Role)`**, one key shared by both ends, `Role`
`#BakaShrot_Cipher_Client` or `#BakaShrot_Cipher_Server`.
- **`BakaShrot_Cipher_Encrypt(*Cipher, *Data, Size, *OutSize)`** returns a new
buffer: `[sequence number, 8 bytes][encrypted data][16-byte tag]`, 24 bytes
more than the data (`#BakaShrot_Cipher_Overhead`). `_EncryptTo()` writes it
into a given buffer (the frame, in `BakaShrot_SendPacket()`).
- **`BakaShrot_Cipher_Decrypt(*Cipher, *Sealed, Size, *OutSize)`** returns the
data in a new buffer, or 0: then abort the connection.
- **`BakaShrot_Cipher_Clear(*Cipher)`** wipes the keys once done.
What it guarantees: nobody without the key reads, changes, forges or
truncates a buffer (XChaCha20-Poly1305, libsodium's AEAD), and nobody
replays, reorders, drops or reflects one: each carries its sequence number,
the receiver only takes the next one, and each direction has its own key
(or its own nonces with one key). Nonces never repeat within a key: a key is
only ever used for one connection.
Why XChaCha20-Poly1305 with sequence numbers rather than
`crypto_secretstream_*`: same primitives, but the buffers stay independent
(no stream state beyond the counter), the format is simple to describe in
`Design/Packets.md`, and replay/reorder protection comes from the sequence
check, which TCP's ordering makes strict.
**Where it's used:** in the framing, so the packets don't know about it.
`BakaShrot_SendPacket()` encrypts when given the connection's cipher (0 only
for the Hello and the ChallengeRequest), `BakaShrot_OpenFrame()` decrypts a
frame once the cipher is set up. On the server, the client's own thread
decrypts, outside the server's mutex; the listener only gathers bytes.
Frames are up to `#BakaShrot_MaxPacketSize + #BakaShrot_Cipher_Overhead`
once authenticated.
## Tests
- `Tests/CipherTest.pb` (56 checks, PB 5.73 and 6.40's C backend), without
sockets:
- The cipher: both directions, a bit flipped at every byte refused, cut
short, replayed, reordered, reflected to its sender or to another client
with the same key, another key, empty data, 16 MB (~33 ms both ways),
two keys, clearing, `_EncryptTo()`.
- The session: a sealed Hello only its server opens, without the identity
showing, tampered or cut short refused, an invalid server key refused;
the key exchange agrees both ways, a key per direction, the pairs wiped,
a swapped half or another connection's keys don't decrypt, an all-zero
half refused.
- `Tests/wire_check.py`, run by `Tests/Python-Test.ps1`: a proxy between
the client and the server records every byte. The pushed message, the
client's topic, node and public key never show up in it; a byte flipped
after the handshake drops the connection ("doesn't decrypt" in the
server's log); another server's public key can't connect ("isn't sealed
for this server").
- `Tests/HandshakeTest.pb`: the handshake packets' fields, without crypto.
- Every end-to-end test (`Tests/*.ps1`, the release's smoke test) runs over
encrypted connections, peer links included.
## What's NOT done (in rough order of importance)
1. **Messages aren't signed by the node that first wrote them,** so
replicated data can't be verified: a peer is trusted with what it sends
(`Design/ReplicationIssues.md`, issue 3).
2. **Private keys sit in plain-text ini files.**
3. **No key rotation or revocation**, and no way to pin more than one key
for a server (to change it without a flag day).
4. **One identity key signs and opens sealed boxes** (its X25519 form).
libsodium supports it and it's a common pattern, but a separate key for
each would be cleaner.
5. **Anyone can make the server work a little:** each new connection costs
it opening a sealed box, a key pair and a signature before the client
proved anything (before: one signature check). Only the 4 KB handshake
limit and the timeout bound it, no rate limit.
6. **The client DLL doesn't wipe its private key**, nor the configs their
Base64 text.
## Ideas for when it gets abstracted
- **A small interface**, so libsodium can be swapped or wrapped without
touching the networking: `Sign`, `Verify`, `GenerateKeyPair`,
`PublicKeyFromPrivateKey`, `Random`, plus `Session.pbi` and `Cipher.pbi`
as they are. Rename `EncodeData`/`DecodeData` to `Sign`/`Verify` while at
it.
- **Per-message signatures** by the origin node, stored with the message and
checked on replication, for item 1.
+362
View File
@@ -0,0 +1,362 @@
# Protocol - packets, flows and conventions
Reference for working on BakaShrot's networking. Related docs:
- `Design/Cryptography.md`: how the handshake proves both ends and sets up
the encryption, and what's still left.
- `Design/ReplicationIssues.md`: known replication problems, with a benchmark.
- `Design/StorageConcurrency.md`: the database threading problem and its
planned fix.
## Where things live
| What | Where |
|---|---|
| Packet base, type ids, limits | `Commons/Networking/Packets.pbi` |
| What a topic or node "ref" is: a name or an id | `Commons/Networking/Names.pbi` |
| Server: which name every id has, translating names to ids | `Server/Storage/Names.pbi` |
| One file per packet, with its `_Encode` and `_Decode` | `Commons/Networking/Packets/*.pbi` |
| Framing (and its encryption), connection metadata, the signed handshake transcript, `BakaShrot_GetPacketType` | `Commons/Networking/Connections.pbi` |
| Sealed Hello, key exchange; encrypting a buffer | `Commons/Cryptography/Session.pbi`, `Commons/Cryptography/Cipher.pbi` |
| Client side of the handshake, on any connection | `Commons/Networking/Outbound.pbi` |
| Server: listener, one thread per client, request handlers | `Server/Networking/Networking.pbi` |
| Server: links to peers, check-ins, sending missing messages and attachments | `Server/Networking/Peers.pbi` |
| Server: storing messages (the writer), attachments, deleting old ones | `Server/Storage/Writer.pbi`, `Attachments.pbi`, `Retention.pbi` |
| Server: its config, and the example one | `Server/Config/Config.pbi`, `Server/Config/schema.ini` |
| Server: the root thread, which stops and starts every worker (restart, vacuum) | `Server/Root.pbi` |
| Client DLL (one connection) | `Client/BakaShrot_Client.pbi`, used through `BakaShrot_Client_Prototypes.pbi` |
| Python client, over the DLL | `Interactors/Python/bakashrot.py` |
| Ready-to-run setups (configs, start scripts, a README each) | `Examples/`, listed in `Examples/README.md` |
| Tools: connecting through the DLL from an ini; ending (waits for Enter when started from Explorer) | `Tools/Common/ToolClient.pbi`, `Tools/Common/ToolConsole.pbi` |
| Tests of the packets alone, without sockets | `Tests/HandshakeTest.pb` |
| Tests of the cipher and the session crypto, without sockets | `Tests/CipherTest.pb` |
| What goes over the wire (a recording proxy) | `Tests/wire_check.py`, run by `Tests/Python-Test.ps1` |
| A raw protocol client, for what the DLL never sends | `Tests/AttachmentEdgeClient.pb`, run by `Tests/AttachmentEdges-Test.ps1` |
| Every end-to-end suite | `Tests/*.ps1`, listed in `CLAUDE.md` |
## Transport and framing
- **TCP, IPv4.** A server listens on `[BakaShrot.Server] Host:Port`.
- **Frames:** every packet is sent as one frame: its size as a **4-byte
little-endian** unsigned integer, followed by the packet itself.
- `BakaShrot_SendPacket()` sends a frame and loops until all of it is
sent.
- **Encryption:** the frame's content, not its size:
- Frame 1, the Hello: sealed for the server's public key
(`crypto_box_seal`, 48 bytes more).
- Frame 2, the ChallengeRequest: plain text, signed by the server.
- Every frame after it, both ways: encrypted with the connection's keys
(`Cipher.pbi`): `[sequence number, 8 bytes LE][encrypted packet][16-byte
tag]`, 24 bytes more. A frame that doesn't decrypt, or out of sequence,
aborts the connection. `BakaShrot_SendPacket()` encrypts when given
the cipher, `BakaShrot_OpenFrame()` decrypts once it's set up.
- `BakaShrot_Inbox_*` gathers received bytes and takes complete frames out
of them.
- **Limits:**
- A packet is 1 to `#BakaShrot_MaxHandshakePacketSize` (4 KB) bytes until
the other end is authenticated, then 1 to `#BakaShrot_MaxPacketSize`
(16 MB, plus the 24 bytes of encryption). A frame announcing anything
else is invalid, as soon as its
4-byte size arrived. The server lifts it (`BakaShrot_Inbox_Lift()`)
before sending AuthAccepted, the client once it got it. So anyone can
connect, but only those with a key can make the other end hold big
frames.
- At most 2 frames' worth of data may wait, unread, in an inbox
(`BakaShrot_Inbox_MaxSize()`: ~8 KB, then ~32 MB).
- Breaking either limit aborts the connection.
- A pushed message is at most `#BakaShrot_MaxMessageSize` (16 MB - 4 KB)
of UTF-8, refused above (by the client DLL already), so a stored
message fits in every packet that carries one later: LatestMessage, a
ReplicateMessages batch of one, without the fields around it going over.
- **Encrypted and authenticated:** see `Design/Cryptography.md`.
## Packet layout
- **A packet is a plain sequence of MessagePack values**, not a map or an
array, read in order with PB-MessagePack:
1. `Magic` (integer), always `#BakaShrot_ProtocolMagic` (`0x42534854`,
"BSHT").
2. `Version` (integer), always `#BakaShrot_ProtocolVersion` (6:
refusals carry a code; 5: the Hello carries the node only, the default
topic is the server's; 4: attachments; 3: the Hello sealed, a key per connection, everything
after the ChallengeRequest encrypted, times; 2 had topics and nodes by
name, in plain text; 1 had ids only).
3. `PacketType` (integer), one of the ids below.
4. The packet's own fields, in the order listed.
- **Encodings:** strings are UTF-8 MessagePack strings, the nonce a
MessagePack binary.
- **Decoding:** `BakaShrot_ReadPacketBase()` checks the magic, the version
and that the type is positive. Each `_Decode` then checks it's **its own**
type, and checks every field's MessagePack type, read error and range.
Anything wrong means the whole packet is rejected.
- **Not checked:** trailing data after the last field is ignored.
### Topics and nodes: names and ids
- **Each server has its own ids** (0-65535) for topics and nodes, and
gives them to the names: the config lists the topics
(`[BakaShrot.Topics]`), the nodes come from the sections that define
them (its own, its peers', its clients') and optionally
`[BakaShrot.Nodes]`; a name keeps the id the database has for it, a new
one gets the lowest free one (`Server/Storage/Names.pbi`). The **name is
what's shared**: "logs" can be 1 on one server and 200 on another.
- **A ref** is how a packet gives a topic or node: a name (1-64 of
`A-Z a-z 0-9 _ . -`, not only digits, any case), or an id in digits,
which always means that id on the receiving server. An unnamed topic or
node goes by its id in digits.
- **Clients** give refs in their requests, the server resolves them in its
own names. **Servers** send names to each other, never rely on ids
matching: the sync state maps the sender's ids to names, and the batches
carry names.
- **Only what's named on both servers replicates.** Unnamed topics and
nodes, and names the other server doesn't have, are dropped, unless the
receiver's `AcceptTopics` / `AcceptNodes` for that peer has a wildcard
(`*`, `sensors.*`; `AcceptNodes` is `*` by default) matching it: it's then added there with an id of its
own. The sync state lists every name the receiver takes, and its
wildcards, so the sender only sends those and nothing gets refused at
every check-in.
### Packet types
Direction: **C** client, **S** server, **P** peer, a server acting as a client
over its own link to another server.
| Id | Packet | Dir | Fields, in order | Answered by |
|---|---|---|---|---|
| 0 | None | | Never valid. | |
| 1-3 | | | Used by the removed `AuthenticationPacket.pbi`, don't reuse. | |
| 4 | ClientHello | C→S | `ClientNode` str (ref, the node it writes as), `ClientPubKeyB64` str, `ClientSessionKey` bin (32 bytes). Sent sealed for the server's key | ChallengeRequest |
| 5 | ChallengeRequest | S→C | `ChallengeB64` str (32 bytes), `Nonce` bin (32 bytes), `ServerSessionKey` bin (32 bytes), `ServerSignature` bin (64 bytes, of the transcript). The last packet in plain text | ChallengeResponse |
| 6 | ChallengeResponse | C→S | `ChallengeResponseB64` str (64-byte signature of the transcript), `Nonce` bin (32 bytes) | AuthAccepted |
| 7 | AuthAccepted | S→C | None. | |
| 8 | PushMessage | C→S | `Topic` str (ref, "" for the client's own), `JsonData` str, `UploadId` int (its attachment, 0 for none) | MessagePushed / RequestRefused |
| 9 | MessagePushed | S→C | `MessageId` int ≥ 1 | |
| 10 | GetLatestMessage | C→S | `Topic` str (ref), `Node` str (ref) | LatestMessage / RequestRefused |
| 11 | LatestMessage | S→C | `TopicId`, `NodeId` int 0-65535 (the server's), `TopicName`, `NodeName` str (names, or ids in digits), `MessageId` int ≥ 1, `PushedAt` int (time, see below), `JsonData` str, `AttachmentSize` int (0 for none), `AttachmentReady` int 0/1 | |
| 12 | RequestRefused | S→C | `Code` int 1-99 (what kind, `#BakaShrot_Refused_*` in `Client/BakaShrot_ErrorCodes.pbi`: what clients act on), `Reason` str, for logs and humans | |
| 13 | SyncStateRequest | P→S | None. | SyncState / RequestRefused |
| 14 | SyncState | S→P | `TopicCount` int, then each topic's `Id` int and `Name` str (the named topics S takes from P); `NodeCount` int, then each node's `Id` and `Name` (the named nodes S takes from P); `TopicPatternCount` int, then each pattern str; `NodePatternCount` int, then each pattern str (S's wildcards for P, `*` included); `PairCount` int, then each pair's `TopicId`, `NodeId`, `MessageId`. Ids are S's own, names are never digits | |
| 15 | ReplicateMessages | P→S | `Topic` str, `Node` str (names, never digits), `Count` int 1-10000, then each message's `MessageId` int (≥ 1, strictly increasing), `PushedAt` int (as stored, from its origin), `JsonData` str, `AttachmentSize` int (0 for none) and `AttachmentSha256` bin (32 bytes, empty for none) | MessagePushed (last id) / RequestRefused |
| 16 | QueryRequest | C→S | `Sql` str | QueryResult / RequestRefused |
| 17 | QueryResult | S→C | `JsonResult` str: `{"columns":[...],"rows":[[...],...]}`, every value a string or null | |
| 18 | ResolveName | C→S | `Kind` int (1 topic, 2 node), `Ref` str | NameResolved / RequestRefused |
| 19 | NameResolved | S→C | `Kind` int, `Id` int 0-65535 (the server's), `Name` str ("" if unnamed) | |
| 20 | ListNames | C→S | `Kind` int (1 topics, 2 nodes) | NamesList |
| 21 | NamesList | S→C | `Kind` int, `Truncated` int 0/1, `Count` int, then each entry's `Id` int, `Name` str ("" if unnamed), `Origin` str ("config", "id") | |
| 22 | GetMessages | C→S | `Topic` str (ref), `Node` str (ref), `AfterMessageId` int ≥ 0, `Limit` int 1-10000 | Messages / RequestRefused |
| 23 | Messages | S→C | `TopicId`, `NodeId` int 0-65535 (the server's), `TopicName`, `NodeName` str (names, or ids in digits), `More` int 0/1, `Count` int 0-10000, then each message's `MessageId` int (≥ 1, strictly increasing, above `AfterMessageId`), `PushedAt` int, `JsonData` str, `AttachmentSize` int (0 for none) and `AttachmentReady` int 0/1 | |
| 24 | UploadStart | C→S | `Topic` str (ref, "" for the client's own), `Size` int 1-MaxAttachmentSize, `Sha256` bin (32 bytes) | UploadStarted / RequestRefused |
| 25 | UploadStarted | S→C | `UploadId` int ≥ 1, `ChunkSize` int (1 MB) | |
| 26 | UploadChunk | C→S | `UploadId` int, `ChunkIndex` int ≥ 0 (the next one), `Data` bin (1 MB, the last one what's left) | ChunkStored / RequestRefused |
| 27 | ChunkStored | S→C, S→P | `Received` int (bytes so far), `Complete` int 0/1 (all of it, SHA-256 checked) | |
| 28 | GetAttachment | C→S | `Topic`, `Node` str (refs), `MessageId` int ≥ 1, `ChunkIndex` int ≥ 0 | AttachmentChunk / RequestRefused |
| 29 | AttachmentChunk | S→C | `TopicId`, `NodeId` int (the server's), `MessageId` int, `Size` int, `Sha256` bin (32 bytes), `ChunkIndex` int, `Data` bin | |
| 30 | MissingAttachmentsRequest | P→S | None. | MissingAttachments / RequestRefused |
| 31 | MissingAttachments | S→P | `Count` int 0-256, then each one's `Topic`, `Node` str (names), `MessageId` int, `NextChunk` int | |
| 32 | ReplicateAttachmentChunk | P→S | `Topic`, `Node` str (names), `MessageId` int, `ChunkIndex` int (the next one), `Data` bin | ChunkStored / RequestRefused |
**Attachments** (24-32, and the attachment fields): see
`Design/Attachments.md`. At most one per message, in parts of 1 MB, checked
with their SHA-256, replicated after their message.
**Times** (`PushedAt`): milliseconds since 1970-01-01 00:00:00 UTC, 1 to
`#BakaShrot_MaxTimestamp` (9999-12-31), anything else aborts. A message is
stamped by the server it's pushed to, when the push arrives (its clock, not
the client's), and keeps that time on every server it's replicated to.
## Rules
- **One request at a time.** A client sends one request and waits for its
single answer before the next one.
- **Refuse or abort:**
- **Refuse** (RequestRefused, the connection stays open) for things that
are valid but not allowed: permissions, no message found, too big,
a failed query, a regular client sending replication packets. Each with
a code (`Client/BakaShrot_ErrorCodes.pbi`): NotAllowed, UnknownName,
NotFound, NotReady, TooBig, NoDefaultTopic, InvalidRequest,
DataMismatch, QueryFailed, ServerError. Clients get them from
`BakaShrot_GetLastError()` (the DLL) or `error.code` (Python), with
their own codes (100+) for what never reached the server or broke the
connection.
- **Abort** (the connection is closed) for anything malformed or out of
order: an invalid frame or packet, a packet type that isn't expected at
that point, an answer to a different request, a timeout during the
handshake.
- The client side applies the same rules to the answers it gets.
- **Timeouts:**
- The server gives a client `#BakaShrot_Net_HandshakeTimeout` (10 s) per
handshake step, then waits for requests forever.
- The client side (`Outbound.pbi`) waits `#BakaShrot_Outbound_Timeout`
(10 s) for each answer.
- **The identity is fixed by the handshake.** Requests never carry who sends
them; the server uses the authenticated topic and node. A push picks its
topic, never its node.
## Flows
### Handshake (every connection)
```
client: knows the server's Ed25519 public key (ServerPublicKey),
makes a key pair for this connection
C -> S ClientHello node (ref, the one it writes as) + Base64 public key
+ the public half of the client's pair,
sealed for the server's public key
server: opens it (or aborts: not for this server), the node must
resolve to its id, the key must decode to 32 bytes, and one
[BakaShrot.Client.<name>] must have this Node and list this key
S -> C ChallengeRequest fresh random challenge + nonce, the public half of
the server's pair, and the server's signature of
the transcript (in plain text)
client: the signature checks out with ServerPublicKey (or aborts)
both: the connection's keys, from both pairs (crypto_kx), the
pairs' secrets wiped; everything from here on is encrypted
C -> S ChallengeResponse the client's signature of the transcript, nonce echoed
server: nonce == the one issued, signature valid for the Hello's key
S -> C AuthAccepted status -> Authenticated
```
The transcript both sign (`BakaShrot_HandshakeTranscript`, 208 bytes):
a 16-byte label (`"BakaShrot3 srv"` or `"BakaShrot3 cli"`, zero-padded),
the client's and the server's Ed25519 public keys, the client's and the
server's session halves, the challenge, the nonce.
- The status moves through New → Challenged → Authenticated, or Aborted /
Disconnected (`BakaShrot_ConnectionStatuses`).
- When authenticating, the server also records two things for the
connection:
- Its **permissions**, from the matching client section: `AllowRead`,
`AllowWrite`, `AllowQuery`, and the `PushTopics` / `ReadTopics` filters
(default: its `DefaultTopic`, nothing without one), and that
`DefaultTopic`: the topic of its pushes that don't name one.
- Whether it's a **peer**: its key and node match a
`[BakaShrot.Peer.<name>]`, and then its `AcceptTopics`.
### Client requests
```
PushMessage(t, json) AllowWrite, t in PushTopics ("" = its DefaultTopic,
refused without one), at most
#BakaShrot_MaxMessageSize. JSON or not: stored as
is, SQLite flags it in is_json
-> stored under t and the authenticated node with the
next message id, stamped with now (pushed_at)
-> MessagePushed(id)
GetLatestMessage(t, n) AllowRead, t in ReadTopics -> LatestMessage
GetMessages(t, n, after, AllowRead, t in ReadTopics -> Messages: those above
limit) after, in id order, at most limit, fewer once they
reach ~1 MB (#BakaShrot_MessagesBatchBytes, a
bigger one alone). None isn't a refusal. More = 1
if others follow: ask again after the last id
ResolveName(kind, ref) topics: in PushTopics or ReadTopics, or AllowQuery
-> NameResolved(id, name)
ListNames(kind) topics: those in PushTopics or ReadTopics, all with
AllowQuery -> NamesList(entries)
QueryRequest(sql) AllowQuery -> QueryResult
```
**Raw queries** (`RunReadOnlyQuery()` in `Server/Storage/Storage.pbi`) are kept
read-only by three things:
1. The SQL must start with `SELECT` or `WITH`.
2. It runs on its own fresh connection with `PRAGMA query_only = ON`. Writes
fail, and turning the pragma off only affects that throwaway connection.
3. Only the first statement runs.
Statements with no result columns are refused, and so are results over
10000 rows or too big for one packet. An error while reading the rows
refuses the whole query with SQLite's message, never a partial or empty
result: JSON functions over a row that isn't JSON give "malformed JSON",
add `is_json = 1` to the WHERE (or `CASE WHEN is_json THEN ... END`). PureBasic reports no column types for
SQLite, so values come back as strings.
### Replication (between servers)
Each server opens its own link to every `[BakaShrot.Peer.<name>]`,
authenticates as itself (the peer must list it as a client), and retries
every `PeerRetryDelay` seconds when that fails or the link drops. On its own
link, every `PeerSyncInterval` seconds, starting right away:
```
P -> S SyncStateRequest
S -> P SyncState every name S takes from P (its AcceptTopics and
AcceptNodes for P), their wildcards, and
MAX(message_id) for each topic/node of those, in
S's ids
P: compares with its own state (GetSyncState()), matching by name,
drops what's unnamed on its side, or neither listed by S nor
matching one of S's wildcards (BakaShrot_Names_NoteDropped(), a
no-op for now), and for every pair in its SendTopics and
SendNodes for S that S is behind on (0 for a name S doesn't have
yet):
P -> S ReplicateMessages the topic and node names, the next missing messages
of that pair, in id order, with their original
message ids and pushed_at: up to PeerBatchSize of them, cut short
at about 64 KB (a bigger message goes alone)
S: resolves the names to its own ids, adds the ones a wildcard took,
refuses what it doesn't take (only if its config changed since
its sync state), see Server/Storage/Names.pbi
S -> P MessagePushed(id) the batch stored in one transaction with
INSERT OR IGNORE, the last id echoed
... until caught up, or the first refusal for that pair
then the attachments of the messages S now has:
P -> S MissingAttachmentsRequest
S -> P MissingAttachments what S lacks, among what it takes from P
P -> S ReplicateAttachmentChunk ... -> S -> P ChunkStored, per part
(Design/Attachments.md)
```
- **Batch size:** `PeerBatchSize` is set on the sending side, in
`[BakaShrot.Server]` (default 100, clamped to 1-10000).
- **Size check:** the sender estimates a batch's size with
`#BakaShrot_ReplicateBatchOverhead` + `#BakaShrot_ReplicateMessageOverhead`
per message + the JSON's UTF-8 bytes, and stops adding messages before
it would go over `#BakaShrot_ReplicateBatchBytes` (64 KB, as when that
was the packet limit: short transactions, little memory). A message
bigger than that goes in a batch of its own. It also stops reading rows
from the database once it has about that much (`GetMessagesAfter()`).
- **Both directions** are covered because each server pushes over the link
it opened itself.
- **Only peers may replicate:** a regular client sending a SyncStateRequest
or ReplicateMessages is refused with `Only peers can replicate`.
- **Unexpected packets:** a packet on a link outside a check-in drops the
link.
- **Retention:** each server deletes a topic's messages past its own
`[BakaShrot.Retention]` max age (`Server/Storage/Retention.pbi`), by their
pushed_at. The sync state comes from `node_heads`, which deleting leaves
alone: a server still says it has what it deleted, so peers don't send it
again. What a peer sends already past this server's max age isn't
stored, but counts as received the same way (still acknowledged). A
peer that links later only gets what the others still have.
## Code conventions
- **Encode:** `BakaShrot_<Name>Packet_Encode(*Struct, *OutSize.Integer)` sets
the base fields itself, and returns a new buffer (the caller frees it with
`FreeMemory`) or 0.
- **Decode:** `BakaShrot_<Name>Packet_Decode(*MsgPackData)` returns a new
struct (the caller frees it with `FreeStructure`) or 0. It reads a view
made with `MsgPackWrapMsgBuffer()`, which the caller frees with
`MsgPackFree(*View, #False)`.
- **Linear code:** each field is written or read top to bottom: check its
type, read it, check the error, check its range. No loops, except for
lists such as SyncState's.
- **Which decoder to use:** `BakaShrot_GetPacketType()` reads a received
packet's type, so a handler can pick the right `_Decode`.
## Adding a packet
1. Add its id to `BakaShrot_PacketTypes` in `Commons/Networking/Packets.pbi`.
Never reuse an id.
2. Add `Commons/Networking/Packets/<Name>Packet.pbi`, with its structure
(`Extends BakaShrot_PacketBase`), `_Encode` and `_Decode`, following an
existing one.
3. Include it from `Commons/Networking/Connections.pbi`, and add it to the
flow comment at the top of that file.
4. **Server side:** handle it in `BakaShrot_NetClient_HandleRequest()`
(`Server/Networking/Networking.pbi`), checking the permission or role
first.
5. **Client side:** add a `<Name>String()` procedure to the DLL with its
`A`/`W` exports if it takes strings, a prototype in
`BakaShrot_Client_Prototypes.pbi`, and a tool if useful.
6. Update this document's packet table and flows.
+244
View File
@@ -0,0 +1,244 @@
# Releases - smoke test, 1.0.0, CI/CD
How releases are built and checked, what's missing before a 1.0.0, and what
to keep in mind when the builds move to CI/CD. Related docs:
- `Notes.md`: where things stand, the open items.
- `Design/StorageConcurrency.md`: WAL, `synchronous`, the writer.
- `Design/Cryptography.md`: what the handshake and the encryption protect,
and what they don't.
## Today
`Release.ps1` builds with PureBasic 6.40's C backend (`/OPTIMIZER`) into
`Release\<version>\` and zips it. `<version>` is `-Version`, or
`<date>-<commit>`, with `-dirty` if the tree has uncommitted changes (a
warning, not an error).
Its smoke test, from the release folder, on one server with a throwaway
database:
- generates keys with `BakaShrotGenerateKeyPairs.exe`, writes a server and a client config;
- pushes two messages, reads the latest back by name, reads both with
`BakaShrotGetMessages.exe`, resolves a name, queries them through the `messages`
view with `is_json = 1`;
- if `python` is on the PATH, reads them and pushes one with
`python\bakashrot.py`, then installs the wheel (`python\bakashrot-*.whl`,
built by `Interactors/Python/make_wheel.py`) with pip into a folder and
reads and pushes with it, from elsewhere and with no DLL path;
- pushes a 3 MB attachment with `BakaShrotPushMessage.exe -a` and reads it back
identical with `BakaShrotGetAttachment.exe`;
- then force-kills the server and deletes everything.
The end-to-end tests in `Tests/` cover much more (names, replication, big
messages, GetMessages, the Python client, retention, attachments and their
edge cases), but against `Build\` (PB 5.73) and `BenchServer.exe`, not the
release. The list is in `CLAUDE.md`.
## Fixed: the release needed the Visual C++ runtime
**Fixed (2026-11-08):** `Libs/redist/x64/vcruntime140.dll` (from Visual
Studio's `VC\Redist` folder, see `Libs/redist/README.md`) is copied next to
the exes by `Release.ps1`, which refuses to build without it, and
`VERSION.txt` gives its version and "Windows 10 or later, 64-bit". Next to
the exe, it's found before an installed one (it isn't a KnownDLL). Still to
check once on a clean Windows (item 1 below).
What it was:
`libsodium.dll` (the official MSVC build) imports `vcruntime140.dll` and the
`api-ms-win-crt-*` DLLs: the **Visual C++ runtime**. The release didn't
ship it and `VERSION.txt` didn't say so: it worked on the build machine only
because the runtime is installed there, on a clean Windows
`BakaShrot_Server.exe`, `BakaShrot_Client.dll` and every tool would fail to
load. Our own exes and `sqlite3.dll` don't need it. The `api-ms-win-crt-*`
ones are the Universal CRT, part of Windows 10 and later.
Checked with: `grep -a -o -i -E "(vcruntime[0-9_]*|msvcp[0-9_]*|api-ms-win-crt-[a-z0-9-]+)\.dll"`
on each binary of the release folder.
## The 1.0.0 smoke test
What `Release.ps1`'s test should also do, by importance. Most of it exists
in `Tests/` already, to be pointed at the release instead.
1. **Run from the extracted zip**, in a fresh folder, not from the release
folder: proves the zip has everything. Once on a **clean Windows**
(Windows Sandbox is enough), which is where the runtime above shows up.
2. **Replication**: two servers from the release, same names with
different ids. Push on A, read it on B by name, same data, same message
id; and the other way around.
3. **Restart, picking up where it was** on its last run:
- kill a server (not a clean stop), start it again on the same database;
- the messages are still there, and the next push to a topic/node gets
the next id, not 1 again or one already used;
- with two servers: push on B while A is down, start A, A catches up on
what it missed, and B gets what was pushed to A before it went down if
B hadn't had it yet.
That's how it's meant to work already, since nothing it needs lives
only in memory: the next message ids are read from the database the
first time a pair is pushed to (`Writer.pbi`), `node_heads` is kept by a
trigger in the same transaction as the messages, and every check-in
with a peer starts from both sync states, read from the databases. A
killed process loses nothing committed, whatever `Synchronous` says
(with `NORMAL`, a power loss or an OS crash can lose the last second). **Tested** by
`Tests/Restart-Test.ps1` (2026-11-09): kills with traffic in flight,
once in the middle of a catch-up, both directions, all hold. With
`BenchServer.exe` (the same server code plus a stop file), not the
release's exe itself.
4. **A clean shutdown**: the release server only stops from its console
(`quit`), so the test force-kills it, and the clean path never runs.
Needs a way to stop it without a console: a stop file like
`BenchServer.exe`'s, or a local admin connection (`Notes.md`, console
commands can't be scripted). Then check it stops within a few seconds,
with its last messages committed. On Linux, SIGTERM does it (2026-11-10,
checked through `docker stop`).
5. **Refusals**:
- an unknown public key, and a known one with the wrong private key:
not authenticated;
- a client given the wrong `ServerPublicKey`: can't connect (tested in
`Tests/wire_check.py`, not against the release);
- a frame over 4 KB before authenticating: cut right away;
- a client reading a topic outside its `ReadTopics`, pushing outside its
`PushTopics`, querying without `AllowQuery`: refused, and still
connected.
6. **`config.example.ini` loads**: fill in keys, start the server from it.
It's documentation, it drifts otherwise.
7. **The server's log is captured and checked**: no "Failed", "invalid",
"unexpected", "too much data" from the clients that are meant to work.
Today its output goes to a hidden console nobody reads.
8. **The data rules**:
- a non-JSON push is stored as is, with `is_json = 0`;
- a 1 MB message reads back whole, on both servers;
- a JSON query over non-JSON rows without `is_json = 1` is refused with
SQLite's error, not answered with no rows (fixed, see below).
9. **Every shipped tool runs once**: `BakaShrotList`, `BakaShrotGetMessages --follow`
(picks up a new push, exits 1 once the server is gone) aren't yet.
10. **Version hygiene**:
- `-Version 1.0.0` refuses a dirty tree instead of appending `-dirty`;
- the release commit is tagged (`v1.0.0`), the version comes from it;
- `VERSION.txt` gives the protocol version (5 now) and the runtime needed;
- the Python client is checked on the oldest version it claims (3.8),
not only on the latest (3.14 here).
Order: 1-3 first (the runtime is fixed), they're what a real deployment hits
on day one. Then 5-8, cheap since `Tests/` has most of it. 4 with the
console item.
## Fixed: a JSON query over non-JSON rows answered nothing, silently
Item 8, it came up with every change about non-JSON messages. Fixed on
2026-11-08 (Windows).
**What happened.** Since pushes aren't checked to be JSON anymore, the
`data` table holds both, flagged in `is_json`. SQLite's JSON functions
(`->>`, `json_extract()`, ...) raise an error on a row that isn't JSON
("malformed JSON"), and that ends the query: SQLite doing what it should.
But `RunReadOnlyQuery()` reads the rows with PureBasic's `NextDatabaseRow()`,
which returns `#False` both at the end of the rows and on an error, and
`DatabaseError()` stays empty after it. So the query counted as a success:
`{"rows": []}` for an aggregate (`SELECT COUNT(*) ... WHERE message_data ->>
'$.level' = 'warn'` gave no row at all), or only the rows read before the
first non-JSON one. A wrong answer that looked like a right one.
**The fix** (`RunReadOnlyQuery()`, `Server/Storage/Storage.pbi`): once the
rows end, SQLite itself is asked, with `sqlite3_errcode()` on the
connection's handle (`DatabaseID()`), before `FinishDatabaseQuery()`.
`SQLITE_DONE` (or `SQLITE_ROW`/`SQLITE_OK`) means they really ended,
anything else is an error: the query is refused with `sqlite3_errmsg16()`'s
message, and a hint when it's about JSON:
Query failed: malformed JSON (a row isn't JSON: add is_json = 1 to the WHERE)
Why this one:
- **Safe:** nothing else changes. The rows are still read by PureBasic, the
query isn't touched, only what happens once they end. A false alarm
would refuse a good query, visibly; it can't hide a bad one anymore.
- **Small:** two functions of the same `sqlite3.dll` PureBasic loaded, like
`Writer.pbi` does, loaded once under a mutex. If they can't be found,
every query is refused rather than unchecked.
- **General:** any error that cut the rows short is caught the same way (a
write stopped by `query_only` in `DELETE ... RETURNING` too), not only
JSON. It replaces the `DatabaseError()` check, which may be shared
between threads anyway.
Not done: having the server add `is_json = 1` to queries itself. It would
mean rewriting arbitrary SQL (subqueries, CTEs, joins), and a query that
wants the non-JSON rows too would get the wrong answer the other way.
**Queries still need the clause** (or `CASE WHEN is_json THEN ... END`) to
run JSON functions over mixed rows: they're refused instead of wrong now.
`CASE WHEN` is the guaranteed form: with `AND is_json = 1`, SQLite doesn't
promise to test that term first. It does today for these queries, and if a
plan ever didn't, the query would be refused now, not answered wrong.
**Not on Linux:** PureBasic's own SQLite is linked in there, not reachable
this way, so it keeps the `DatabaseError()` check that misses it. To do if
it's ever built there: `ImportC` the two functions, or read the rows with
SQLite's API like the writer.
**Tested:** `Tests/BigMessages-Test.ps1`: an aggregate and a row-by-row
SELECT over mixed rows are refused with "malformed JSON"; non-JSON rows
read without JSON functions, `CASE WHEN is_json`, a query with really no
rows and a plain SQL error behave as before.
## Before calling it 1.0
Not smoke-test items, but what the "1.0" label would promise. From
`Notes.md`'s open items:
- ~~Clients and peers can't verify the server's identity.~~ Fixed
(protocol 3, `Design/Cryptography.md`).
- ~~No encryption, no per-packet authentication after the handshake.~~
Fixed (protocol 3).
- Messages aren't signed by the node that first wrote them: a peer is
trusted with what it replicates (`Design/ReplicationIssues.md` #3).
- ~~`synchronous = NORMAL`: the last commits can be lost on a power loss.~~
Decided: `[BakaShrot.Server] Synchronous`, `FULL` by default
(`Design/StorageConcurrency.md`).
Either they're fixed, or they're documented limits of 1.0 (or it's a 0.9).
## For CI/CD
Notes for when the builds move to a pipeline.
- **Toolchain:**
- PureBasic isn't freely downloadable: a self-hosted Windows runner with
a licensed install, or a private image. Compiler paths are parameters
(`Build.ps1 -Compiler`, `Release.ps1 -Compiler`), default to
`C:\Program Files\PureBasic_573\...` and `..._640\...`.
- Two compilers are in use: 5.73 for `Build\` and the tests, 6.40's C
backend for releases. Decide whether CI tests the release build (it
should, it's what ships), or both.
- Check out with submodules (`Includes/PB-MessagePack`).
- `Libs/` holds the libsodium and SQLite zips: pin them and check their
hashes in the pipeline.
- **Scripts that need changes first:**
- `Build.ps1` ends by running the server, which waits on its console:
needs a `-NoRun` switch. It also writes private keys into `Build\`,
which must never be published as an artifact.
- The tests use fixed ports (12399 for the release, 12401-12416 for
`Tests/`): parallel jobs on one runner collide, make them parameters
or pick free ones.
- One entry point that runs every test (`Tests/*.ps1`, the handshake
and cipher tests) and fails if any fails. Today each is run by hand.
- The release server needs a console, or it stops right away (no
console input). The smoke test gives it a hidden window: check that
works on the runner (a service account may not get a console), or do
item 4 first.
- **Environment:**
- Exes run from temp folders are blocked by the antivirus here, the
tests run them from `Build\`. A runner may differ either way.
- A clean-machine job, without the Visual C++ runtime, to catch missing
DLLs (see above).
- Python: 64-bit, the oldest claimed version (3.8) and the latest.
- **Versions and artifacts:**
- Releases from tags (`v1.0.0` -> `-Version 1.0.0`), refusing a dirty tree.
- Artifacts: the release zip, and a source zip. Not `Build\`.
- **Benchmarks** (`Tests/Bench/`): too noisy and long for every build. A
nightly or on-demand job, compared to a stored baseline with
`Compare-Runs.ps1`, failing only on a big drop.
- **Linux:** `Libsodium.pbi` and the writer have Linux paths, never built
or tested. A later job, once wanted.
+174
View File
@@ -0,0 +1,174 @@
# Replication - known issues
How it works now: see the top of `Server/Networking/Peers.pbi`. In short, every
`PeerSyncInterval` seconds a server asks each linked peer for its sync state
(the highest message id per topic/node id), and sends it the messages it's
behind on, with their original ids. Each peer does the same over its own link.
Issues below are roughly ordered by how much they matter.
## 1. Drift: the same message id with different content (ruled out by config)
**The rule: a node pushes to one server.** Each client node has its
`[BakaShrot.Client.<name>]` section (its `Node`) on one server only, the
one it pushes to; the other servers get its messages by replication. Then
every topic/node pair has a single writer and this can't happen. Reading
from any server is fine, only pushing matters. Breaking the rule isn't
detected: it's the config's to keep.
**When it would happen:** the same topic/node id written to on two
servers, for example a client node registered on both, pushing to each
while they can't reach each other.
**What happens:** both servers are at `1:2#1`, the link drops, then:
| | Server A | Server B |
|---|---|---|
| Before | 1 | 1 |
| Client pushes to both | 1, 2a, 3a | 1, 2b |
| Once relinked | A is ahead, sends `#3a` | B isn't ahead, sends nothing |
| Result | 1, 2a, 3a | 1, 2b, 3a |
- Only the max id is compared, so `#2a` vs `#2b` is never noticed.
- If both had sent the same id, `INSERT OR IGNORE` would keep the local one
and silently drop the other.
- The servers end up partially resynced, with a mixed history for that pair.
**Possible fix, maybe someday:** authoritative servers. Each topic/node id
gets one server that's allowed to assign its message ids, and the others only
replicate it. Pushes for a pair not owned locally are refused, or forwarded.
A cheaper half-measure: detect drift by also comparing a hash of each
message (or of a range of them), and at least log it.
## 2. ~~The peer isn't verified~~ (fixed 2026-11-08, protocol 3)
It was: the handshake only proved the connecting side, the `PublicKey` in a
`[BakaShrot.Peer.<name>]` section was never checked, so whatever answered on
the peer's address got this server's messages pushed to it.
Now a link's Hello is sealed for the peer section's `PublicKey`, and the
peer must sign the handshake with the matching private key, or the link
fails; the link is encrypted (`Design/Cryptography.md`). A missing or
invalid `PublicKey` stops the server at start. The section's `Topic` and
`Node` are still only checked when the peer links to here.
## 3. Peers are trusted completely
A connection that authenticated with a peer's identity and key can replicate
messages for any topic/node id the receiver replicates, with any content.
Messages carry no proof of who first wrote them, so a compromised or buggy
peer can inject or overwrite history for nodes it doesn't own. (Overwrite
only in the sense of issue 1: it can't replace an id that's already stored.)
**Fix:** sign each message with its originating node's key when it's first
stored, keep the signature with it, and verify it on replication. That needs
every server to know the public key of every node it replicates.
## 4. Database concurrency (fixed)
**Fixed 2026-11-06:** every link thread and client thread now has its own
database connection, see `Design/StorageConcurrency.md`. Kept below for the
record.
The link threads used to read the database with the same unlocked handle as
the client threads.
**Seen happening** (2026-11-06, benchmark with `PeerBatchSize = 1`):
1. Server 1's link thread was reading the messages to send.
2. At the same time, server 1's thread for server 2's incoming link was
reading the sync state for server 2's check-in.
3. Both went through the same handle, so a read came back empty while
messages were still left. Server 1 logged
`Sent 1424 messages ... it had up to #0` for a backlog of 5000, and the
check-in ended there.
The next check-in picked up where it stopped, so nothing was lost here. But
the same collision during a write could have stored wrong data.
## 5. Gaps aren't detected
Only `MAX(message_id)` is compared. If a server has `1, 2, 5` for a pair (say
`3` and `4` were refused midway through a check-in), it reports `5` and never
gets `3` and `4`. Messages are sent in order and the sending stops at the
first refusal, so this needs something unusual, but nothing repairs it.
**Fix:** send a count with the max (`COUNT(*) = MAX` means no gaps), and fall
back to comparing id ranges when they differ.
## 6. Speed: batched since, the per-batch overhead remains
**Benchmarks** (2026-11-06, both servers on localhost, PureBasic 5.73 x64,
SQLite 3.54.1). The same 5000 messages of ~28 bytes and 1000 of ~4 KB, sent
from scratch:
| Version | 5000 small | 1000 x 4 KB |
|---|---|---|
| One message per packet (before batching) | 63.6 s, ~79 msg/s | 12.2 s, ~82 msg/s |
| `PeerBatchSize = 1` | ~69-87 msg/s | 12.0 s, ~83 msg/s |
| `PeerBatchSize = 100` (default) | 0.67 s, ~7500 msg/s | 0.94 s, ~1070 msg/s, ~4.3 MB/s |
| `PeerBatchSize = 1000` | 0.11 s, ~45000 msg/s | 1.48 s, ~680 msg/s |
**Where the per-batch time goes,** measured before batching:
- **~3.8 ms is SQLite**, one transaction synced to disk. The same inserts
inside one transaction take 0.014 ms each (5000 in 71 ms). Hence one
transaction per batch.
- **The rest is polling.** Both ends wait for packets in `Delay(5)` loops
(5.5 ms each on Windows, `Delay(1)` is 1.6 ms), and each batch waits for
its acknowledgement before the next one, so it pays a few of those per
round trip.
**Big messages** don't gain from batch sizes over ~16: only that many 4 KB
messages fit in a ~64 KB batch (`#BakaShrot_ReplicateBatchBytes`). Since
2026-11-08 a batch stops reading rows once it has that much, so a big
`PeerBatchSize` no longer reads rows it then can't send.
**Further fixes, if needed:**
1. Keep the rows that didn't fit for the next batch instead of reading them
again.
2. ~~Wake the waiting thread when data arrives instead of polling with
`Delay(5)`.~~ Done 2026-11-07: client threads sleep on an event the
listener sets (`Commons/Threading/Signal.pbi`), the listener and the
outbound side sleep in `select()` (`Commons/Networking/SocketWait.pbi`).
3. Send the next batch before the previous one is acknowledged (a window).
4. ~~WAL mode~~ Done 2026-11-07, see `Design/StorageConcurrency.md`.
**Since then** (2026-11-07, `Tests/Bench/Bench-Replication.ps1`, 4 servers in
a Y): the hub relays up to ~5700 msg/s of pushes to its leaves without
falling behind, sending at ~38000 msg/s while a catch-up runs. The lag is
now just the check-in wait, 4-6 s of pushes at every load (two check-ins for
leaf to leaf). A shorter `PeerSyncInterval` is what would lower it.
~~**A message that's too big for a batch isn't replicated.**~~ Fixed
2026-11-08: pushes are capped at `#BakaShrot_MaxMessageSize`, 4 KB under the
16 MB packet limit, so one always fits in a batch of its own.
## 7. Sync state size limit
The whole sync state must fit in one packet: 16 MB since 2026-11-08 (was
64 KB, roughly 4000 topic/node pairs), so the counts are what limits it now,
65536 topics, nodes and pairs (`SyncStatePacket.pbi`). The replicated topics are also sent as a list, and
`ReplicatingTopicIds = 0-65535` expands to 65536 entries, which doesn't fit.
**Fix:** send ranges instead of expanded lists, and page the pairs (for
example per topic).
## 8. Two links per pair of servers
With two servers listing each other as peers, there are two connections, and
each one is only used by its opener to push. That's what makes both
directions work, but it doubles the connections and the check-ins. Fine for
now. If it ever matters, one link could carry both directions.
## 9. Messages for topics a server doesn't replicate
The receiver lists the topics it replicates, and the sender only sends
those, so they're never sent. But a batch that arrives for another topic
anyway is refused, and that stops the pair's catch-up for that check-in. It only happens if the two servers disagree about the list
mid-check-in, for example after a config change.
## 10. ~~Replicated messages aren't validated~~
Moot since 2026-11-08: pushed messages aren't checked to be JSON either,
both are stored as is and flagged by `is_json`.
+179
View File
@@ -0,0 +1,179 @@
# Storage concurrency
Status (2026-11-07): **one connection per thread, WAL mode, a write mutex,
group commit, and a single writer connection with prepared statements are
done.** Full benchmark history: `Tests/Bench/Results-2026-11-07.md`. Ideas
not done yet: `Design/Suggestions.md`.
## The writer (2026-11-07, `Server/Storage/Writer.pbi`)
- **Every write goes through one connection,** opened by
`OpenStorageWriter()` when the workers start and closed by
`CloseStorageWriter()` once they're stopped (`Server/Root.pbi`). It's the
one exception to the rule below: shared, but only ever used while holding
the write mutex, so never by two threads at once.
- **Prepared statements, kept open,** through SQLite's own API
(`sqlite3_prepare16_v2`, `sqlite3_bind_*`, `sqlite3_step`), from the
same `sqlite3.dll` PureBasic loads: `DatabaseID()` is its `sqlite3`
handle. PureBasic prepares a statement again on every call. Windows only,
elsewhere the writer falls back to PureBasic's functions.
- **The next id of every topic/node id in memory,** instead of a
`MAX(message_id) + 1` in every insert: read from the database the first
time, raised by replicated messages, forgotten on any rollback. Only right
while this writer is the only one writing.
- **Checkpoints in a background thread,** every second, in PASSIVE rounds
that don't block anything, then a short one under the write mutex once
little is left, so the WAL can start over. The writer still checkpoints by
itself past 10,000 WAL frames, as a backstop when the thread can't keep up
(flat out). Without that backstop the WAL reached 700 MB and Windows
throttled the writes, up to 5 s for a push.
- **`node_heads`,** the highest message id of every topic/node id, kept by a
trigger on `data` (so even `BenchSeed` keeps it right). The sync state is
read from it: 0.5 ms instead of 167 ms at 2.4M rows, on every check-in.
Schema: `Server/Storage/db_schema_v3.dbml` (now `db_schema_v4.dbml`)`.
- **Measured:** ~25,700 -> ~34,300 msg/s for 4 servers, ~38,400 built with
PureBasic 6.40's C backend. p99 at 10 nodes x 50 msg/s: 13.6 -> 0.8 ms.
## WAL and the write mutex (2026-11-07)
- **WAL mode,** set by `SetupStorageDatabase()` (stored in the file), with
the config's `synchronous` on every connection (see below). Readers no
longer block the writer: a 0.5 s raw query used to stall pushes for
seconds and once made one fail with "database is locked", now pushes run
next to it at full speed.
- **`synchronous` is `[BakaShrot.Server] Synchronous`** since 2026-11-09,
`FULL` by default (it was `NORMAL`, fixed). The root sets
`BakaShrot_Storage_Synchronous` (`Storage.pbi`) before it opens any
connection. `OFF` is refused (a power loss could corrupt the file),
`EXTRA` too (the same as `FULL` in WAL mode, it only adds a directory
sync for the other journal modes).
- `FULL`: every commit flushes the WAL. An acknowledged push survives a
power loss or an OS crash. The flush is per transaction, so a group
commit's pushes share it.
- `NORMAL`: the WAL is only flushed at checkpoints (about every second,
`Writer.pbi`). The file can't get corrupted, but the last second or so
of commits before a power loss or an OS crash can be lost. Those
messages were acknowledged and maybe already replicated, so their ids
could be handed out again: drift (`ReplicationIssues.md` #1).
### Measured (2026-11-09)
`Bench-Replication.ps1 -Ramp "1x0,10x0,10x20" -Parts Ramp -Synchronous ...`,
4 servers in a Y, totals of the 4, one run each (±5-10%). On a VM whose
virtual disk flushes in 0.60 ms (p99 0.78 ms).
| | OFF | NORMAL | FULL | EXTRA |
|---|---|---|---|---|
| 1 pusher per server, flat out: msg/s | 28,785 | 22,595 | 5,100 | 5,026 |
| ... push p50 / p99 | 0.1 / 0.8 ms | 0.1 / 0.8 ms | 0.7 / 5.3 ms | 0.7 / 3.3 ms |
| 10 pushers per server, flat out: msg/s | 42,854 | 33,870 | 17,207 | 17,763 |
| ... push p50 / p99 / max | 0.6 / 4.8 / 95 ms | 0.5 / 3.3 / 1,113 ms | 1.6 / 9.3 / 123 ms | 1.6 / 8.7 / 129 ms |
| 800 msg/s steady: push p50 / p99 | 0.2 / 0.5 ms | 0.2 / 0.9 ms | 0.9 / 5.0 ms | 0.8 / 4.6 ms |
| Lost on a power loss / OS crash | the file may be corrupted | ~1 s of acknowledged pushes | nothing acknowledged | same as FULL |
No failed pushes, replication kept up in every case. `FULL`'s cost is the
disk's flush time: one client pushing one message at a time gets about
1 / (flush + 0.15 ms) pushes/s, ~1,300/s here; many clients share flushes
through the group commit, so the total drops much less (half here). On a
server SSD with power-loss protection a flush is far under 0.1 ms (close
to `NORMAL`), on a consumer SSD 1-5 ms, on a hard disk ~10 ms (~100/s for
one sequential client): time one on the target machine to know.
- **`BakaShrot_Storage_WriteMutex`** around every write. A connection that
finds the database locked sleeps in SQLite's busy handler (1, 2, 5, 10...
ms) and retries; with 10+ threads pushing, that's where the time went, and
10 nodes per server pushed less than 5. Queued on the mutex, the next one
writes as soon as the lock is free. The busy timeout still covers other
processes.
- **Measured** with `Tests/Bench/Bench-Replication.ps1` (4 servers in a Y,
~200-byte messages, i5-13500, all on localhost), along with the wake-ups
instead of `Delay()` polling (`ReplicationIssues.md` #6):
| | Before | After |
|---|---|---|
| Cluster push ceiling, 5 / 10 nodes per server | ~955 / ~900 msg/s | ~5770 / ~5730 msg/s |
| Push latency p50 / p99, 10 nodes x 50 msg/s | 18 / 490 ms | 0.4 / 5 ms |
| Indexed query (latest message) | 6-12 ms | ~0.5 ms |
| Pushes while a 0.5 s query loops | 323 of 400 msg/s, max 5.1 s, 1 failure | 396 of 400, max 17 ms |
That ceiling turned out not to be the database, but the `PrintN()` logging
every push (~0.4 ms each, serialized): see below.
## Group commit (2026-11-07)
- **`InsertNextMessage()`** queues the push (`BakaShrot_Storage_Queue`),
then takes the write mutex. Whoever holds it writes every queued push in
one transaction (up to `#BakaShrot_Storage_MaxGroupSize`), so the pushes
that were waiting find theirs done. No extra thread: the busier it gets,
the bigger the groups. Each push still returns once committed.
- **`[Storage]` log line** every 10 s while pushes come in: pushes/s,
pushes per transaction, ms per push, and how busy the writes are.
- **No more log line per push, read or query** (`#BakaShrot_Net_LogRequests`
in `Networking.pbi`): that `PrintN()` was what capped a server at ~2,400
pushes/s.
- **Measured:** a single server ~2,400 -> ~12,000 pushes/s, the cluster of 4
~5,800 -> ~25,700 msg/s, 2.5-9 pushes per transaction when saturated.
The writes are now the limit again (70-90 % busy at 0.07-0.11 ms per push).
- **Open:** p99 at moderate load went up (0.7 -> 8-18 ms). Suspect: a WAL
checkpoint running while holding the write mutex.
## The rule
**Never share a database handle between threads.** The `SetDatabase*()`
parameters and the query results belong to a handle, so two threads using one
overwrite each other's. That used to happen: a peer link once read an empty
result while 3500 messages were left to send, see
`Design/ReplicationIssues.md`, issue 4.
Every thread that touches the database opens its own connection with
`OpenStorageDatabase()` and closes it when it ends:
| Who | Opens | Closes | Where |
|---|---|---|---|
| A client thread | once its client is authenticated | when the thread ends | `BakaShrot_NetClient_Thread()`, `Server/Networking/Networking.pbi` |
| A peer link thread | when the thread starts | when the thread ends | `BakaShrot_PeerLink_Thread()`, `Server/Networking/Peers.pbi` |
| A raw query | for the query, read-only | right after | `RunReadOnlyQuery()`, `Server/Storage/Storage.pbi` |
| The root | at start, and on restart | on restart and at the end | `Server/Root.pbi` |
The root's connection is only used for setup, and while the workers are
stopped (vacuum, restart). See `Server/Root.pbi`.
## What makes several connections work
- **Busy timeout.** Each connection sets
`PRAGMA busy_timeout = #BakaShrot_Storage_BusyTimeout` (5000 ms), in
`OpenStorageDatabase()`. SQLite allows one writer at a time across
connections. Without it, a write fails at once with "database is locked"
while another connection writes. With it, the write waits its turn.
- **Atomic next id.** `InsertNextMessage()` is a single statement:
```sql
INSERT INTO data (topic_id, node_id, message_id, message_data)
SELECT ?1, ?2, COALESCE(MAX(message_id), 0) + 1, ?3
FROM data WHERE topic_id = ?1 AND node_id = ?2
RETURNING message_id
```
Nothing can run between reading `MAX` and inserting, even from another
connection. The UNIQUE `(topic_id, node_id, message_id)` constraint stays
as a safety net.
- **`BEGIN IMMEDIATE` for replicated batches** (`InsertReplicatedMessages()`).
It takes the write lock up front, waiting for it like any write, instead
of a deferred transaction that could fail midway when upgrading to a write
lock.
**Tested:** 8 connections pushing 100 messages each to the same topic/node
id at once, while two servers replicated. 800 pushes in 6.2 s, no failures,
ids exactly 1-800 on both servers.
## Left for later
- **What happens when the busy timeout runs out.** The statement fails, so
the push or batch is refused and retried at the next check-in for
replication. Fine at current loads; decide later whether pushes should
retry.
- ~~**Whether PureBasic's `DatabaseError()` is per thread**~~: it is, in
thread-safe mode (`/THREAD`), checked 2026-11-09 with 5.73 and 6.40: two
threads failing on their own connections 20,000 times each never saw the
other's message. `sqlite3_errmsg16()` on the connection gives the same
text. (`RunReadOnlyQuery()` still asks SQLite on Windows, for the errors
`DatabaseError()` doesn't report at all, see `Design/Release.md`.)
- **A single storage thread with a job queue,** only if writes ever become
the bottleneck. SQLite only has one writer anyway.
+123
View File
@@ -0,0 +1,123 @@
# Suggestions, not done yet
Improvements that came out of the 2026-11-07 benchmarks
(`Tests/Bench/Results-2026-11-07.md`), kept aside on purpose. The first two
are bigger changes, worth it when the use case needs them, the rest are
smaller.
## 1. Several pushes in flight per connection
**Today:** a client sends a `PushMessage`, waits for its `MessagePushed`,
then sends the next. One node can push at most once per round trip:
| Round trip | Most pushes/s per node |
|---|---|
| localhost, now | ~2,000-3,000 |
| LAN, 0.5 ms | ~2,000 |
| WAN, 50 ms | ~20 |
The server side doesn't care much, it groups pushes from every connection
anyway. This is about one node, or few nodes, far from their server.
**What it entails:**
- **Protocol.** Let a client send up to W pushes before the first answer.
TCP and the one thread per connection already keep them in order, and the
answers come back in the same order, so the Nth answer belongs to the Nth
push. Still, add a `RequestId` (client-chosen, echoed in `MessagePushed`
and `RequestRefused`) so a client can match answers without counting, and
so a desync is detectable. Old clients send no `RequestId` and keep
working one at a time. See `Design/Packets.md` for how to add a field.
- **Server inbox.** It holds at most two of the biggest packets
(`BakaShrot_Inbox_MaxSize()`), anything more aborts the connection as
"sent too much data". Since big packets (2026-11-08) that's ~32 MB once
authenticated, plenty for a window of small pushes, but a window of big
ones still needs backpressure: stop reading that client's socket while its inbox is full,
so TCP slows it down. PureBasic's `NetworkServerEvent()` keeps reporting
data that isn't read, so backpressure means the listener has to skip that
client's events without spinning: easiest is a per-client "full" flag,
with the listener not calling `ReceiveNetworkData()` for it and leaving
it out of its `select()` set until the client thread drains its inbox.
- **Server thread.** Take every complete packet in the inbox, queue all the
pushes in the writer at once (`BakaShrot_Storage_Queue`), then send the
answers. One connection then fills a whole group commit by itself.
- **Client DLL.** Keep `BakaShrot_PushMessage()` as is (synchronous, W=1).
Add an asynchronous variant for those who want it, without callbacks
since the DLL is used from other languages:
`BakaShrot_PushMessageAsync(Json)` returns a local sequence number,
`BakaShrot_GetPushResult(Sequence)` / `BakaShrot_WaitPushes()` collect the
ids or the refusals. The DLL holds at most W unanswered pushes, the next
call waits for room.
- **Semantics.** Each push is still independent: a refused one doesn't stop
the next ones, the caller gets one result per push. Ids are still handed
out in send order per node.
- **Bench.** `BenchClient` gets a window per pusher, to measure W = 1, 4,
16, ideally with a simulated latency (or the servers on another machine).
**Effort:** medium. Packets, DLL API, the server's inbox and thread loop.
The inbox backpressure is the delicate part.
## 2. Replication: windowed batches, several sockets per link, check-ins on demand
**Today,** per peer link: one connection, a check-in every
`PeerSyncInterval` (5 s) or so, then for each topic/node id the peer is
behind on, one batch of up to `PeerBatchSize` messages at a time, waiting
for its acknowledgement before the next, one pair after the other. The
benchmarks show it keeps up (the hub relays ~25,000+ msg/s), but the lag is
the check-in wait: 4-10 s of pushes, two check-ins from leaf to leaf.
**What it entails, cheapest first:**
1. **Check-ins on demand.** The writer signals (`Commons/Threading/Signal.pbi`)
when it committed something, and the link threads check in as soon as
there's something new, at most every `PeerMinSyncInterval` (say 100
ms), and still every `PeerSyncInterval` when idle. Cheap since the sync
state is now read from `node_heads`. Lowers the lag from seconds to
about the minimum interval plus the relay through the hub. Biggest gain
for the least work.
2. **A window of batches.** Send up to W batches before waiting for the
first acknowledgement, acknowledged in order. On a refusal, stop, and the
next check-in starts again after the last acknowledged one.
- **Needed first: the receiver must refuse a gap.** Today a batch is
stored whatever its first id, with `INSERT OR IGNORE`. With a window,
batch 2 could be stored after batch 1 was refused, leaving a gap that
the max-only sync state never repairs (`ReplicationIssues.md` #5).
Refuse a batch whose first id isn't the pair's head + 1, which
`node_heads` (or the writer's id cache) makes a cheap check.
- The same inbox limit as above: two packets. A peer connection needs a
bigger inbox, or the backpressure.
3. **Several sockets per link.** `PeerConnections = N` in the peer's
section: N connections, N threads on both ends, each one checking in and
catching up its share of the topic/node ids (for example
`(TopicId * 65536 + NodeId) % N`). A pair always goes over the same
socket, which keeps its messages in order. Catch-ups of different pairs
then run in parallel instead of one after the other. On the receiving
side, the batches of the N threads queue on the write mutex: they could
join the pushes' group commit (one transaction for whatever batches and
pushes are waiting) instead of one transaction each.
4. **One connection for both directions** (`ReplicationIssues.md` #8), if
the number of connections ever matters.
**Effort:** 1 is small, 2 is medium (mostly the gap check and the inbox), 3
is medium (config, threads, partitioning), 4 is larger (both ends of the
protocol change).
## 3. Smaller ones
- ~~**Decide on `synchronous = NORMAL`**~~: done 2026-11-09, a config
option (`Synchronous`), `FULL` by default, measured in
`Design/StorageConcurrency.md`.
- **`Build.ps1`:** the compiler path and `-Compiler` are fixed (2026-11-07),
but the `Libs\` zips for libsodium and SQLite are gone: it only works while
the extracted DLLs are still in `Libs\*d`.
- **Benchmark on two machines:** the servers on one, `BenchClient` on the
other. Flat out, the load generator uses ~85 % of a core on the same
machine, and the servers compete with it for the CPU and the disk.
- **The WAL at full speed:** flat out, each server writes ~25,000 WAL
frames/s, and the checkpoints can't keep it small, so the writer falls
back to checkpointing by itself past `#BakaShrot_Storage_WalBackstopFrames`
(the worst push goes up to ~0.7 s). A bigger page size, or fewer indexes
(is `idx_data_message_id` needed?), would write fewer pages per push.
- **Full-table JSON queries** grow with the data (~0.45 ms per 1,000 rows).
If some JSON field gets queried often, a generated column with an index
on it (like the `msg_type` noted in `db_schema_v4.dbml`) makes it a lookup.
+52
View File
@@ -0,0 +1,52 @@
# BakaShrot - Docker
Docker image for the server, built on the PureBasic images from `git.nibblepoker.lu`.
> [!NOTE]
> The PureBasic images are licensed, building requires a login to their registry. \
> The final image only holds the compiled server, libsodium and SQLite.
## Running
Fill in [Server/server.ini](Server/server.ini), then, from `Docker/Server/`:
```shell
docker compose up -d --build
```
See [Server/docker-compose.yml](Server/docker-compose.yml) and the [Dockerfile](Server/Dockerfile) for more.
## Building
From the repository's root:
```shell
git submodule update --init --recursive
docker login git.nibblepoker.lu
docker build --provenance=false -t bakashrot-server -f Docker/Server/Dockerfile .
```
`--provenance=false` pushes the image as a plain manifest: with the default attestation it's an index, and GitHub
doesn't see the Dockerfile's `org.opencontainers.image.source` label there, so the package isn't linked to the repository.
## Uploading
Tag and push the image to both registries, with the version and as `latest`:
### Gitea
```shell
docker login git.nibblepoker.lu
docker tag bakashrot-server git.nibblepoker.lu/aziascreations/bakashrot-server:0.0.1
docker tag bakashrot-server git.nibblepoker.lu/aziascreations/bakashrot-server:latest
docker push git.nibblepoker.lu/aziascreations/bakashrot-server:0.0.1
docker push git.nibblepoker.lu/aziascreations/bakashrot-server:latest
```
### GitHub
Requires a [personal access token](https://github.com/settings/tokens) with the `write:packages` scope as the password.
```shell
docker login ghcr.io -u aziascreations
docker tag bakashrot-server ghcr.io/aziascreations/bakashrot-server:0.0.1
docker tag bakashrot-server ghcr.io/aziascreations/bakashrot-server:latest
docker push ghcr.io/aziascreations/bakashrot-server:0.0.1
docker push ghcr.io/aziascreations/bakashrot-server:latest
```
The package then has to be linked to the repository, and made public if needed, in its settings on GitHub.
+81
View File
@@ -0,0 +1,81 @@
# BakaShrot server image.
#
# Built from the repository's root, with the PB-MessagePack submodule checked
# out and a login to the registry holding the PureBasic images (they're
# licensed, so not public):
# git submodule update --init --recursive
# docker login git.nibblepoker.lu
# docker build --provenance=false -t bakashrot-server -f Docker/Server/Dockerfile .
# Another compiler image: --build-arg COMPILER_IMAGE=<image>, any Debian 13
# (trixie) image with PureBasic's compilers on the PATH, gcc and libssl-dev.
#
# Run it with a config and a volume for the database:
# docker run -d --name bakashrot -p 12345:12345 \
# -v ./server.ini:/etc/bakashrot/server.ini:ro \
# -v bakashrot-data:/var/lib/bakashrot \
# bakashrot-server
# In server.ini's [BakaShrot.Server]: Port = 12345, Host empty (every
# interface: 127.0.0.1 can't be reached from outside the container), and
# DatabasePath = /var/lib/bakashrot/server.sqlite (relative paths are from
# that folder too).
#
# Or with docker-compose.yml, next to this file, and its empty server.ini
# to fill in.
#
# `docker stop` stops it cleanly (SIGTERM). Console commands (names, vacuum,
# restart...): start it with -it, then `docker attach bakashrot`, and
# detach with Ctrl+P, Ctrl+Q.
# --- Build ---------------------------------------------------------------------
# PureBasic 6.41 for linux3 (PureBasic's newest Linux build) on
# debian:trixie-slim, the same Debian as the runtime stage below.
ARG COMPILER_IMAGE=git.nibblepoker.lu/packages/purebasic:6.41-linux3-trixie-slim
FROM ${COMPILER_IMAGE} AS build
RUN apt-get update \
&& apt-get install -y --no-install-recommends libsodium-dev \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /src
# Everything Server/BakaShrot_Server.pb includes, and nothing else.
COPY Client/BakaShrot_ErrorCodes.pbi Client/
COPY Commons Commons
COPY Includes Includes
COPY Server Server
# The release build: C backend, optimized, thread-safe.
RUN mkdir /out && pbcompilerc --thread --optimizer Server/BakaShrot_Server.pb --executable /out/bakashrot-server
# --- Runtime -------------------------------------------------------------------
FROM debian:trixie-slim
# The source label links the package to the repository on ghcr.io. GitHub
# reads it from the image itself, not from an index: build with
# --provenance=false, or the attestation hides it (Docker/README.md).
LABEL org.opencontainers.image.source="https://github.com/aziascreations/BakaShrot" \
org.opencontainers.image.description="BakaShrot server" \
org.opencontainers.image.licenses="CC0-1.0"
# libsodium for the cryptography, SQLite 3.38+ for the storage: the server
# loads libsqlite3.so.0 itself (Server/Storage/Storage.pbi).
RUN apt-get update \
&& apt-get install -y --no-install-recommends libsodium23 libsqlite3-0 \
&& rm -rf /var/lib/apt/lists/*
RUN useradd --system --home-dir /var/lib/bakashrot --shell /usr/sbin/nologin bakashrot \
&& mkdir -p /etc/bakashrot /var/lib/bakashrot \
&& chown bakashrot:bakashrot /var/lib/bakashrot
COPY --from=build /out/bakashrot-server /usr/local/bin/bakashrot-server
USER bakashrot
WORKDIR /var/lib/bakashrot
VOLUME /var/lib/bakashrot
EXPOSE 12345
ENTRYPOINT ["/usr/local/bin/bakashrot-server"]
CMD ["/etc/bakashrot/server.ini"]
@@ -0,0 +1,8 @@
# Only what the server is compiled from: Build/ alone can hold gigabytes of
# test databases, and private keys.
*
!Client/BakaShrot_ErrorCodes.pbi
!Commons
!Includes
!Server
**/.git
@@ -0,0 +1,38 @@
# BakaShrot server, example compose file.
#
# Fill in server.ini next to this file first (a private key, topics, a
# client section: it's empty, the server refuses to start as it is), then,
# from this folder, with a login to the registry holding the PureBasic
# images (see the Dockerfile):
# docker compose up -d --build
# docker compose logs bakashrot # its public key, for client.ini
# docker compose down # stops it cleanly (SIGTERM)
#
# Console commands (names, vacuum, restart...): `docker attach bakashrot`,
# detach with Ctrl+P, Ctrl+Q (not Ctrl+C: that stops it).
#
# The database lives in the bakashrot-data volume, kept by `down`
# (`down -v` deletes it).
services:
bakashrot:
build:
# The repository's root: the build needs Commons/, Includes/, Server/.
context: ../..
dockerfile: Docker/Server/Dockerfile
image: bakashrot-server
container_name: bakashrot
restart: unless-stopped
ports:
# server.ini's [BakaShrot.Server] Port.
- "12345:12345"
volumes:
- ./server.ini:/etc/bakashrot/server.ini:ro
- bakashrot-data:/var/lib/bakashrot
# Only needed to type console commands with `docker attach bakashrot`.
# The server runs fine without these two lines.
stdin_open: true
tty: true
volumes:
bakashrot-data:
+60
View File
@@ -0,0 +1,60 @@
; ============================================================================
; BakaShrot server config, for docker-compose.yml: empty, fill it in.
;
; Every option is documented in Server/Config/schema.ini (config.example.ini
; in a release). Keys: BakaShrotGenerateKeyPairs.exe. Never commit a filled
; in copy, it holds the server's private key.
; ============================================================================
[BakaShrot]
; This server's private key. Its public key, which clients need as
; ServerPublicKey, is in the log when it starts (docker compose logs).
PrivateKey =
; The node this server authenticates as when it links to peers.
Node =
[BakaShrot.Topics]
; One topic name per line.
; logs
[BakaShrot.Retention]
; topic = age (30d, 12h...), or nothing to keep everything forever.
; logs = 30d
[BakaShrot.Server]
; Empty: every interface (127.0.0.1 can't be reached from outside the
; container). The port must match docker-compose.yml's.
Host =
Port = 12345
ReplicatingTopics =
NetThreadPoolSize = 4
; In the bakashrot-data volume.
DatabasePath = /var/lib/bakashrot/server.sqlite
MaxAttachmentSize = 1G
Synchronous = FULL
; One section per peer, see schema.ini.
; [BakaShrot.Peer.other]
; Host =
; Port =
; Node =
; PublicKey =
; One section per client allowed to connect.
[BakaShrot.Client.example]
; The client's public key (client.ini's PublicKey).
PublicKeys =
; The node it writes as (client.ini's Node must say the same).
Node =
; DefaultTopic = logs
; PushTopics = logs
; ReadTopics = *
AllowRead = 1
AllowWrite = 1
AllowQuery = 0
+12
View File
@@ -0,0 +1,12 @@
# Examples
Ready-to-run setups, each in its own folder with its configs, scripts to
start it, and a README. Build first (`Build.ps1` at the root): the scripts
take the exes from `Build\`, or from a release folder with `-BinDir`.
| Example | What it shows |
|---|---|
| [`SingleServer`](SingleServer/README.md) | One server, one client: pushing, reading, attachments, names, SQL, with the tools. |
Their keys are in the repository, so public: they're only for trying the
examples locally, never reuse them.
+136
View File
@@ -0,0 +1,136 @@
# One server, one client
The smallest BakaShrot setup: one server on `127.0.0.1:12360`, one client
that pushes and reads messages with the tools.
> **The keys in `server.ini` and `client.ini` are public, they're in the
> repository.** They're only for trying this example on your own machine
> (the server only listens on 127.0.0.1). Never reuse them: make your own
> with `BakaShrotGenerateKeyPairs.exe`.
## Running it
Build first, `Build.ps1` at the root, or use a release folder (`-BinDir
Release\<version>` on both scripts). Then, from this folder:
```powershell
powershell -ExecutionPolicy Bypass -File Start-Server.ps1
powershell -ExecutionPolicy Bypass -File Run-Client.ps1
```
- `Start-Server.ps1` opens the server in its own window and waits until it
listens. Type `quit` in that window to stop it (`help` lists the other
commands). `-Here` runs it in the current console instead, `-Reset`
deletes its database first, so the ids start from 1 again.
- `Run-Client.ps1` goes through what a client does, printing each command
before its output. The commands can be pasted as they are from this
folder:
```text
== Push a message to the client's default topic (logs, the server's DefaultTopic for it), as node demo
> ..\..\Build\BakaShrotPushMessage.exe @messages\hello.json client.ini
Pushed as message #1
...
== Read the latest message of logs:demo (topic:node, by name)
> ..\..\Build\BakaShrotGetLatestMessage.exe logs demo client.ini
Message logs:demo#2 (ids 1:2), pushed 2026-11-08T21:23:53.590Z
Attachment: 159 bytes
{"level":"info","text":"Daily report, attached"}
```
The server's database (`example.sqlite`) and what the client saves
(`out\`) stay in this folder, git ignores them.
## What's in here
| File | What it is |
|---|---|
| `server.ini` | The server: its key, its names, where it listens, the one client it accepts and what that client may do. Every option is documented in `Server/Config/schema.ini`. |
| `client.ini` | The client: its key pair, the node it writes as (`demo`), and the server's address and public key. Every tool takes it as its last argument. |
| `Start-Server.ps1` | Starts the server with `server.ini`. |
| `Run-Client.ps1` | The client's steps, below. |
| `messages\` | What the client pushes (`hello.json`, `reading.json`, `report.json` with `report.txt` attached) and the SQL it runs (`query.sql`). |
## How the two configs fit together
- **Keys:** each side has a key pair. The server lists the client's public
key in `[BakaShrot.Client.demo] PublicKeys`; the client has the server's
in `ServerPublicKey`. Every connection is encrypted, and only reaches the
server holding the matching private key.
- **Names:** messages are filed under a topic and a node. The topics are
listed in `[BakaShrot.Topics]`, the nodes come from the sections that
define them (`server`, `demo`). The server gives each name an id of its
own; clients use the names.
- **Who the client is:** its node, `demo`, in both configs (`Node`).
Every message it pushes is stored under it. That's why the server
checks it: the key proves who's connecting, the server's `Node` for that
key says which node it may write as, so no client can push as another's
node.
- **Where its pushes go:** the server's `DefaultTopic = logs`, unless a
push names another topic in `PushTopics` (`-t sensors`). Only the server
has it: `client.ini` has no topic.
- **What it may do:** read every topic (`ReadTopics = *`, `AllowRead`),
push (`AllowWrite`), run read-only SQL (`AllowQuery`).
- **Retention:** `sensors` messages are kept a day, `logs` ones forever.
- **Durability:** `Synchronous = FULL` (the default): every message the
server acknowledges is flushed to disk first, so it survives a power cut.
`NORMAL` pushes faster but can lose the last second or so of messages
then; see `Server/Config/schema.ini`.
## What the client does
`Run-Client.ps1`, step by step:
1. **Pushes** `hello.json` to `logs`, its default topic: `BakaShrotPushMessage @messages\hello.json`.
JSON goes in a file (`@file`): PowerShell drops the double quotes of an
argument.
2. **Pushes** `reading.json` to `sensors`: `-t sensors`.
3. **Pushes** `report.json` with `report.txt` attached: `-a messages\report.txt`.
4. **Reads the latest** message of `logs:demo`: `BakaShrotGetLatestMessage logs demo`.
5. **Saves the attachment** back to `out\report-copy.txt` and checks it's
the same: `BakaShrotGetAttachment logs demo <id> out\report-copy.txt`.
6. **Reads every** message of `logs:demo`, one per line (id, time, data):
`BakaShrotGetMessages logs demo --time`.
7. **Reads** `sensors:demo`'s latest.
8. **Shows the ids** the server has for the names: `BakaShrotResolveIds topic sensors`, `BakaShrotList`.
9. **Queries** with SQL: `BakaShrotQuery @messages\query.sql`, on the
`messages` view, which has the names.
To watch messages arrive, leave this running and push from another
terminal:
```powershell
..\..\Build\BakaShrotGetMessages.exe logs demo --after latest --follow client.ini
```
## Looking at the database
`example.sqlite` is a plain SQLite file, the `messages` view has the
names. To browse one topic in a tool like SQLiteStudio:
1. Open the `browse` table: one row. Pick a topic in its `topic` cell (a
dropdown of the topics, from its foreign key), and a node in `node` to
narrow it, or leave it NULL for every node. Commit.
2. Open the `browse_messages` view: that topic's messages, newest first,
with their node, id, time (UTC), data and attachment size.
The server never writes `browse`, so it's safe to change while it runs.
Close the tool when done: an open grid keeps the server from finishing
its checkpoints, and its WAL file grows meanwhile.
## From Python
The same `client.ini` works with the Python client
(`Interactors/Python/bakashrot.py`, over the DLL). From the repository's
root:
```python
import sys
sys.path.insert(0, r"Interactors\Python")
from bakashrot import Client
with Client.from_ini(r"Examples\SingleServer\client.ini", r"Build\BakaShrot_Client.dll") as client:
print("pushed", client.push({"from": "python"}))
for message in client.get_messages("logs", "demo").messages:
print(message.id, message.json())
```
@@ -0,0 +1,101 @@
# ============================================================================
# BakaShrot example: what a client does, with the tools and client.ini.
#
# Start the server first (Start-Server.ps1). Each step prints the command
# it runs, then its output: run from this folder, the commands can be
# pasted as they are. Every run pushes 3 more messages, the ids go on from
# the last run's (Start-Server.ps1 -Reset starts over).
#
# Usage: powershell -ExecutionPolicy Bypass -File Run-Client.ps1 [-BinDir <dir>]
# -BinDir Where the tools are, with BakaShrot_Client.dll next to them:
# Build\ by default (Build.ps1), or a Release\<v>\.
# ============================================================================
param(
[string]$BinDir = (Join-Path $PSScriptRoot "..\..\Build")
)
$ErrorActionPreference = "Stop"
$Port = 12360
function Test-Port($Port) {
$Client = New-Object System.Net.Sockets.TcpClient
try {
$Async = $Client.BeginConnect("127.0.0.1", $Port, $null, $null)
return ($Async.AsyncWaitHandle.WaitOne(200) -and $Client.Connected)
} catch { return $false }
finally { $Client.Close() }
}
function Write-Step($Text) {
Write-Host ""
Write-Host "== $Text" -ForegroundColor Cyan
}
# Runs a tool, shows the command and what it printed, stops if it failed.
# client.ini is always the last argument.
function Invoke-Tool($Name, [string[]]$Arguments) {
$Arguments += "client.ini"
$Shown = $Arguments | ForEach-Object { if ($_ -match " ") { "`"$_`"" } else { $_ } }
Write-Host ("> " + (Join-Path $Bin "$Name.exe") + " " + ($Shown -join " ")) -ForegroundColor DarkGray
$Output = & (Join-Path $Bin "$Name.exe") @Arguments 2>&1
$Code = $LASTEXITCODE
$Output | ForEach-Object { Write-Host " $_" }
if ($Code -ne 0) { throw "$Name failed with code $Code" }
return ($Output -join "`n")
}
if (-not (Test-Path (Join-Path $BinDir "BakaShrot_Client.dll"))) {
throw "No BakaShrot_Client.dll in ${BinDir}: build it first (Build.ps1), or pass -BinDir"
}
if (-not (Test-Port $Port)) {
throw "Nothing listens on port ${Port}: start the server first (Start-Server.ps1)"
}
# From this folder, so every path is short: client.ini, messages\...
Push-Location $PSScriptRoot
try {
$Bin = Resolve-Path -Relative $BinDir
New-Item -ItemType Directory -Force "out" | Out-Null
Write-Step "Push a message to the client's default topic (logs, the server's DefaultTopic for it), as node demo"
# JSON goes in a file (@file): PowerShell drops the double quotes of an argument.
$null = Invoke-Tool "BakaShrotPushMessage" @("@messages\hello.json")
Write-Step "Push one to another topic it may push to (sensors)"
$null = Invoke-Tool "BakaShrotPushMessage" @("-t", "sensors", "@messages\reading.json")
Write-Step "Push one with a file attached"
$Pushed = Invoke-Tool "BakaShrotPushMessage" @("-a", "messages\report.txt", "@messages\report.json")
if ($Pushed -notmatch "message #(\d+)") { throw "Unexpected answer: $Pushed" }
$ReportId = $Matches[1]
Write-Step "Read the latest message of logs:demo (topic:node, by name)"
$null = Invoke-Tool "BakaShrotGetLatestMessage" @("logs", "demo")
Write-Step "Read the attachment back"
$null = Invoke-Tool "BakaShrotGetAttachment" @("logs", "demo", $ReportId, "out\report-copy.txt")
if ((Get-FileHash "out\report-copy.txt").Hash -ne (Get-FileHash "messages\report.txt").Hash) { throw "The attachment came back different" }
Write-Host " Same bytes as messages\report.txt"
Write-Step "Read every message of logs:demo, with when they were pushed (UTC)"
$null = Invoke-Tool "BakaShrotGetMessages" @("logs", "demo", "--time")
Write-Step "Read the sensors one"
$null = Invoke-Tool "BakaShrotGetLatestMessage" @("sensors", "demo")
Write-Step "What the server calls the names: their ids there"
$null = Invoke-Tool "BakaShrotResolveIds" @("topic", "sensors")
$null = Invoke-Tool "BakaShrotList" @()
Write-Step "A raw SQL query (needs AllowQuery = 1), from messages\query.sql"
$null = Invoke-Tool "BakaShrotQuery" @("@messages\query.sql")
Write-Host ""
Write-Host "Done. To follow new messages as they come, from this folder:" -ForegroundColor Green
Write-Host " $(Join-Path $Bin 'BakaShrotGetMessages.exe') logs demo --after latest --follow client.ini"
}
finally {
Pop-Location
}
@@ -0,0 +1,67 @@
# ============================================================================
# BakaShrot example: starts the server with server.ini.
#
# In a window of its own by default (the server needs a console: it reads
# its commands there, and stops at once without one), then waits until it
# listens. Type "quit" in that window to stop it, "help" for the others.
#
# Usage: powershell -ExecutionPolicy Bypass -File Start-Server.ps1 [-BinDir <dir>] [-Here] [-Reset]
# -BinDir Where BakaShrot_Server.exe is, with libsodium.dll and
# sqlite3.dll: Build\ by default (Build.ps1), or a Release\<v>\.
# -Here Runs it in this console instead, until "quit".
# -Reset Deletes the example's database first: no messages, ids from 1.
#
# Its database, example.sqlite, goes next to this script.
# ============================================================================
param(
[string]$BinDir = (Join-Path $PSScriptRoot "..\..\Build"),
[switch]$Here,
[switch]$Reset
)
$ErrorActionPreference = "Stop"
$Server = Join-Path $BinDir "BakaShrot_Server.exe"
$Ini = Join-Path $PSScriptRoot "server.ini"
$Port = 12360
function Test-Port($Port) {
$Client = New-Object System.Net.Sockets.TcpClient
try {
$Async = $Client.BeginConnect("127.0.0.1", $Port, $null, $null)
return ($Async.AsyncWaitHandle.WaitOne(200) -and $Client.Connected)
} catch { return $false }
finally { $Client.Close() }
}
if (-not (Test-Path $Server)) {
throw "No ${Server}: build it first (Build.ps1), or pass -BinDir"
}
if (Test-Port $Port) {
throw "Something already listens on port $Port, the example server may already run"
}
if ($Reset) {
Get-ChildItem $PSScriptRoot -Filter "example.sqlite*" | Remove-Item -Confirm:$false
Write-Host "Deleted the example's database"
}
if ($Here) {
Push-Location $PSScriptRoot
try { & $Server $Ini }
finally { Pop-Location }
exit $LASTEXITCODE
}
$Process = Start-Process -FilePath $Server -ArgumentList "`"$Ini`"" -WorkingDirectory $PSScriptRoot -PassThru
$Deadline = (Get-Date).AddSeconds(15)
while (-not (Test-Port $Port)) {
if ($Process.HasExited) { throw "The server stopped with code $($Process.ExitCode), see its log above" }
if ((Get-Date) -gt $Deadline) { throw "The server isn't listening on $Port after 15 s" }
Start-Sleep -Milliseconds 100
}
Write-Host "The server runs in its own window (process $($Process.Id)), on 127.0.0.1:$Port."
Write-Host "Try it with: powershell -ExecutionPolicy Bypass -File `"$(Join-Path $PSScriptRoot 'Run-Client.ps1')`""
Write-Host "Stop it by typing quit in its window."
@@ -0,0 +1,26 @@
; ============================================================================
; BakaShrot example: the client's config, read by every tool (their last
; argument), the client DLL and the Python client.
;
; EXAMPLE KEYS, PUBLIC IN THE REPOSITORY: never use them for anything real.
; Make your own with BakaShrotGenerateKeyPairs.exe.
; ============================================================================
[BakaShrot]
; This client's key pair. The server lists the public key in
; [BakaShrot.Client.demo] PublicKeys.
PrivateKey = zDA8o6hp7zkIatlumOKFWqV8j3yYON8QFpIkMAEnpJnKv4FbbX4SmshWDRJp9ds5qpEDVYRHSnE7exw2pkQK1w==
PublicKey = yr+BW21+EprIVg0SafXbOaqRA1WER0pxO3scNqZECtc=
; The node it writes as: the server checks its section for this key says
; Node = demo. Every message it pushes is stored as "demo".
; No topic here: where its pushes go when they don't name one is the
; server's DefaultTopic, which topics it may push to and read its
; PushTopics and ReadTopics.
Node = demo
; Where the server is, and its public key: the client only talks to the
; server holding the matching private key.
ServerHost = 127.0.0.1
ServerPort = 12360
ServerPublicKey = k32QNiTXL9lA7DhdwBQv9jQXouADujciaOWVZuA3JE4=
@@ -0,0 +1 @@
{"level":"info","text":"Hello from the example client"}
@@ -0,0 +1 @@
SELECT topic, node, message_id, pushed_utc, message_data ->> '$.text' FROM messages WHERE topic = 'logs' AND is_json = 1 ORDER BY message_id
@@ -0,0 +1 @@
{"sensor":"kitchen-temperature","celsius":21.5}
@@ -0,0 +1 @@
{"level":"info","text":"Daily report, attached"}
@@ -0,0 +1,5 @@
Daily report
============
Any file can be attached to a message: bytes of any kind, up to the
server's MaxAttachmentSize. The message's JSON says what it is.
@@ -0,0 +1,67 @@
; ============================================================================
; BakaShrot example: the server's config (one server, one client).
;
; EXAMPLE KEYS, PUBLIC IN THE REPOSITORY: never use them for anything real.
; Make your own with BakaShrotGenerateKeyPairs.exe.
;
; Every option is documented in Server/Config/schema.ini.
; ============================================================================
[BakaShrot]
; This server's private key. Its public key, which the client needs, is
; k32QNiTXL9lA7DhdwBQv9jQXouADujciaOWVZuA3JE4= (the server logs it too).
PrivateKey = KymGH/iJFcqE0JtGmRmWIsQnKTEl49Zq+qYEsfLHtWOTfZA2JNcv2UDsOF3AFC/2NBei4AO6NyJo5ZVm4DckTg==
; The node this server authenticates as when it links to peers. It has
; none here.
Node = server
; The topics this server has. It gives each an id of its own (they keep it
; across restarts); clients and other servers use the names.
[BakaShrot.Topics]
logs
sensors
; No [BakaShrot.Nodes]: the nodes come from the sections that define them,
; "server" above and "demo" below (and the ones peers send, as they come).
; Sensor readings are kept a day, logs forever (no line for them).
[BakaShrot.Retention]
sensors = 1d
[BakaShrot.Server]
; Only reachable from this machine.
Host = 127.0.0.1
Port = 12360
ReplicatingTopics = logs;sensors
NetThreadPoolSize = 4
; Next to this file: Start-Server.ps1 runs the server from this folder.
DatabasePath = ./example.sqlite
MaxAttachmentSize = 64M
; Every acknowledged push is on disk, even through a power loss (the
; default). NORMAL is faster but can lose the last second of messages then.
Synchronous = FULL
; The one client: Run-Client.ps1's tools, with client.ini.
[BakaShrot.Client.demo]
; client.ini's PublicKey.
PublicKeys = yr+BW21+EprIVg0SafXbOaqRA1WER0pxO3scNqZECtc=
; The node this key writes as, fixed: every message it pushes is stored
; under it, so no client can push as another's node. client.ini's Node
; must say the same.
Node = demo
; Where its pushes go when they don't name a topic (BakaShrotPushMessage
; without -t). Only a default: it may push to any topic in PushTopics.
DefaultTopic = logs
; The topics it may push to (always as "demo"), and read from. Without
; these two lines: only its DefaultTopic.
PushTopics = logs;sensors
ReadTopics = *
AllowRead = 1
AllowWrite = 1
; Raw read-only SQL, for BakaShrotQuery.exe.
AllowQuery = 1
+83
View File
@@ -0,0 +1,83 @@
# BakaShrot - Python client
Python client for BakaShrot servers, over `BakaShrot_Client.dll`, without dependencies.
The wheel includes the DLLs it needs, nothing else to install or compile. \
Windows 10 or later, 64-bit Python 3.8+.
> [!NOTE]
> The client and the server must come from the same release, any other protocol version refuses the connection.
## Linux
The Linux wheel (`bakashrot-<version>-py3-none-linux_x86_64.whl`) holds only the client library,
libsodium comes from the system: `apt install libsodium23` on Debian and Ubuntu. \
Linux x86-64 with glibc 2.34+ (Debian 12, Ubuntu 22.04 or later), 64-bit Python 3.8+.
It's tagged `linux_x86_64`, not `manylinux`: manylinux doesn't allow depending on libsodium,
so it goes on Gitea, not PyPI.
Building it: compile the client in the Docker compiler image (Debian 13, so glibc 2.34 is enough),
named `BakaShrot_Client.dll` as the repository does on Linux, then `make_wheel.py --linux`:
```shell
docker run --rm -v "$PWD":/src:ro -v "$PWD/dist":/out -w /src git.nibblepoker.lu/packages/purebasic:6.41-linux3-trixie-slim \
sh -c 'apt-get update -qq && apt-get install -y -qq libsodium-dev >/dev/null && pbcompilerc -t --optimizer Client/BakaShrot_Client.pbi -so /out/BakaShrot_Client.dll'
python3 Interactors/Python/make_wheel.py dist dist --linux
```
## Installing
From Gitea:
```shell
pip install --index-url https://git.nibblepoker.lu/api/packages/aziascreations/pypi/simple/ bakashrot
```
From a GitHub release, or a release folder:
```shell
pip install https://github.com/aziascreations/BakaShrot/releases/download/v0.0.1/bakashrot-0.0.1-py3-none-win_amd64.whl
pip install python\bakashrot-0.0.1-py3-none-win_amd64.whl
```
Usage is in [bakashrot.py](bakashrot.py)'s docstring, and in [example.py](example.py).
## Building
`Release.ps1` builds the wheel into `Release\<version>\python\`, and checks it once installed by pip.
By hand, from the DLLs of a release folder or of `Build\`:
```shell
python Interactors/Python/make_wheel.py Release/<version> dist
```
The version comes from `__version__` in [bakashrot.py](bakashrot.py).
## Licenses
The wheel's license is `CC0-1.0 AND ISC`:
* BakaShrot is in the public domain ([CC0](../../LICENSE)).
* The included `libsodium.dll` is under the [ISC license](../../Libs/libsodium/LICENSE),
whose notice must ship with it: it's in the wheel's `dist-info/licenses/`.
`vcruntime140.dll`, which libsodium needs, isn't included: Python already loads its own.
## Uploading
### Gitea
Requires [twine](https://pypi.org/project/twine/) 6.1+ (for the license metadata), and your Gitea login or an access token with the `write:package` scope.
```shell
pip install twine
twine upload --repository-url https://git.nibblepoker.lu/api/packages/aziascreations/pypi -u aziascreations dist/bakashrot-0.0.1-py3-none-win_amd64.whl
```
### GitHub
GitHub has no Python registry, the wheel is attached to the release instead.
Requires the [GitHub CLI](https://cli.github.com/), logged in with `gh auth login`.
```shell
gh release create v0.0.1 --repo aziascreations/BakaShrot --title "0.0.1" dist/bakashrot-0.0.1-py3-none-win_amd64.whl
```
Or, if the release already exists:
```shell
gh release upload v0.0.1 --repo aziascreations/BakaShrot dist/bakashrot-0.0.1-py3-none-win_amd64.whl
```
+622
View File
@@ -0,0 +1,622 @@
"""BakaShrot client for Python, over BakaShrot_Client.dll.
No dependencies beyond the standard library: the DLL is loaded with ctypes
and does the connecting, authenticating and talking to the server. Messages
come back as stored, a str that may or may not be JSON: parsing them is up
to the app (Message.json() helps).
from bakashrot import Client
with Client.from_ini("client.ini") as client:
message_id = client.push({"temperature": 21.5})
for message in client.get_messages("logs", "kitchen", after=0).messages:
print(message.id, message.data)
for message in client.follow("logs", "kitchen"): # until stopped
print(message.id, message.json())
photo_id = client.push({"kind": "photo"}, attachment="photo.jpg")
client.save_attachment("logs", "kitchen", photo_id, "copy.jpg")
Topics and nodes are "refs": a name ("logs") or an id (12, or "12"), ids
being the server's own.
A message can have one attachment (a file, or bytes), of any size the
server takes: uploaded in parts before the message is stored, read back in
parts, checked with its SHA-256 (Design/Attachments.md).
The connection only goes through to the server holding the private key of
server_public_key (client.ini's ServerPublicKey, the server logs it when it
starts), and everything on it is encrypted.
Errors are exceptions with a code (`error.code`, an ErrorCode, the same
numbers as the DLL's BakaShrot_GetLastError(), see
Client/BakaShrot_ErrorCodes.pbi):
RefusedError the server refused (codes 1-99), still connected
ConnectionLostError not connected, unreachable, the connection lost or
broken: connect() again (nothing reconnects by itself)
AuthError the server rejected the handshake or couldn't prove
its key: fix the config, retrying won't help
BakaShrotError the rest: a bad argument, a file, the DLL itself
A push whose answer was lost (ConnectionLostError) may have been stored all
the same: pushed again, it's stored twice. Delivery is at least once.
The DLL holds a single connection per process: only one Client may be
connected at a time. Calls are serialized with a lock, so a Client can be
shared between threads, one request at a time.
The DLL is 64-bit, so is the Python running this. It's looked for, in order:
the dll_path given, the BAKASHROT_DLL environment variable, next to this
file, then in the current directory. libsodium.dll must be next to it.
The wheel (make_wheel.py, `pip install bakashrot`) has them all next to
this file: nothing else to install or build.
"""
from __future__ import annotations
import configparser
import ctypes
import enum
import json
import os
import threading
import time
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Any, Iterator, Optional, Union
# The release's, and the wheel's (make_wheel.py reads it from here).
__version__ = "0.0.1"
__all__ = [
"Client", "Message", "MessagesPage", "NameEntry", "NamesList",
"BakaShrotError", "RefusedError", "ConnectionLostError", "AuthError", "ErrorCode",
"MAX_GET_MESSAGES", "MAX_MESSAGE_SIZE",
]
# Same as the server: Commons/Networking/Packets.pbi, GetMessagesPacket.pbi.
MAX_GET_MESSAGES = 10000
MAX_MESSAGE_SIZE = 16 * 1024 * 1024 - 4096
Ref = Union[str, int]
class ErrorCode(enum.IntEnum):
"""What failed: Client/BakaShrot_ErrorCodes.pbi, the same numbers.
1-99: refused by the server, 100+: the client's own."""
NONE = 0
# Refused by the server, the connection still open.
NOT_ALLOWED = 1 # AllowRead/Write/Query, PushTopics/ReadTopics
UNKNOWN_NAME = 2 # a topic or node this server doesn't know
NOT_FOUND = 3 # no such message, attachment or upload
NOT_READY = 4 # the attachment isn't on this server yet: retry later
TOO_BIG = 5 # over a limit, or more than this server keeps
NO_DEFAULT_TOPIC = 6 # a push without a topic, and no DefaultTopic
INVALID_REQUEST = 7 # parts out of order, an upload for another topic...
DATA_MISMATCH = 8 # an upload that doesn't match its SHA-256
QUERY_FAILED = 9 # the SQL failed
SERVER_ERROR = 10 # the server's database failed: retry later
# The client's own.
NOT_CONNECTED = 100 # never connected, or closed or lost before
CONNECT_FAILED = 101 # nothing answers at that host and port
AUTH_REJECTED = 102 # the server closed the handshake: wrong ServerPublicKey,
# a key or node it doesn't allow, another version
SERVER_NOT_VERIFIED = 103 # the server couldn't prove its key
CONNECTION_LOST = 104 # broke during a request (a push may still be stored)
PROTOCOL_ERROR = 105 # an unexpected answer, the connection is closed
INVALID_ARGUMENT = 106
FILE_ERROR = 107
ATTACHMENT_MISMATCH = 108 # a downloaded attachment that doesn't match its SHA-256
ALREADY_CONNECTED = 109
INTERNAL = 110 # out of memory, the DLL missing or too old...
@property
def is_refusal(self) -> bool:
return 1 <= self.value <= 99
def _error_code(value: int):
"""An ErrorCode, or the int itself if this module doesn't know it."""
try:
return ErrorCode(value)
except ValueError:
return value
class BakaShrotError(Exception):
"""Something failed: code (an ErrorCode) tells what, see ErrorCode."""
def __init__(self, message: str, code: int = ErrorCode.INTERNAL):
super().__init__(message)
self.code = _error_code(code)
class RefusedError(BakaShrotError):
"""The server refused the request, the connection is still open. code
says why (1-99, e.g. ErrorCode.NOT_FOUND), reason in the server's words."""
def __init__(self, reason: str, code: int):
super().__init__(reason or "Refused", code)
self.reason = reason
class ConnectionLostError(BakaShrotError):
"""Not connected, or the connection failed or was closed (code:
NOT_CONNECTED, CONNECT_FAILED, CONNECTION_LOST, PROTOCOL_ERROR):
connect() again to go on."""
class AuthError(BakaShrotError):
"""The server rejected the handshake (AUTH_REJECTED) or couldn't prove it
holds server_public_key's private key (SERVER_NOT_VERIFIED): a config to
fix, connecting again won't help."""
@dataclass(frozen=True)
class Message:
"""A stored message. data is as stored: JSON or not (the server's
is_json column tells which, json() parses it). pushed_at: when it was
pushed, to whichever server it was pushed to, in milliseconds since
1970-01-01 UTC (pushed is the same as a datetime). attachment_size: its
attachment's, 0 for none; attachment_ready: whether all of it is on
this server (a replicated one comes after its message), see
Client.get_attachment() and save_attachment()."""
id: int
topic: str
node: str
topic_id: int
node_id: int
data: str
pushed_at: int = 0
attachment_size: int = 0
attachment_ready: bool = False
def json(self) -> Any:
"""The data parsed as JSON, raises ValueError if it isn't."""
return json.loads(self.data)
@property
def pushed(self) -> datetime:
"""When it was pushed, as an aware datetime in UTC."""
return datetime.fromtimestamp(self.pushed_at / 1000, tz=timezone.utc)
@dataclass(frozen=True)
class MessagesPage:
"""One answer to get_messages(): in message id order. more is True if
more follow the last one, ask again with after=last_id."""
messages: list = field(default_factory=list)
more: bool = False
@property
def last_id(self) -> Optional[int]:
return self.messages[-1].id if self.messages else None
def __iter__(self):
return iter(self.messages)
def __len__(self):
return len(self.messages)
@dataclass(frozen=True)
class NameEntry:
id: int
name: str # "" if unnamed: those don't replicate
origin: str # "config", "id", "peer"
@dataclass(frozen=True)
class NamesList:
kind: str # "topic" or "node"
items: list
truncated: bool # True if they didn't all fit in one answer
def _ref(value: Ref) -> bytes:
if isinstance(value, bool) or not isinstance(value, (str, int)):
raise TypeError(f"a topic or node is a name or an id, not {value!r}")
if isinstance(value, int) and not 0 <= value <= 65535:
raise ValueError(f"an id is 0-65535, not {value}")
return str(value).encode("utf-8")
def _find_dll(dll_path: Optional[str]) -> str:
candidates = []
if dll_path:
candidates.append(dll_path)
if os.environ.get("BAKASHROT_DLL"):
candidates.append(os.environ["BAKASHROT_DLL"])
candidates.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "BakaShrot_Client.dll"))
candidates.append(os.path.join(os.getcwd(), "BakaShrot_Client.dll"))
for candidate in candidates:
if os.path.isfile(candidate):
return os.path.abspath(candidate)
raise BakaShrotError("BakaShrot_Client.dll not found, looked at: " + ", ".join(candidates))
class _Dll:
"""The DLL's functions, with their types. Loaded once per process."""
_instance: Optional["_Dll"] = None
_instance_lock = threading.Lock()
@classmethod
def get(cls, dll_path: Optional[str]) -> "_Dll":
with cls._instance_lock:
if cls._instance is None:
cls._instance = cls(_find_dll(dll_path))
return cls._instance
def __init__(self, path: str):
if ctypes.sizeof(ctypes.c_void_p) != 8:
raise BakaShrotError("BakaShrot_Client.dll is 64-bit, this Python is 32-bit")
try:
self.lib = ctypes.CDLL(path)
except OSError as error:
raise BakaShrotError(f"Failed to load {path} (is libsodium.dll next to it?): {error}") from error
self.path = path
I, L, Q, P, S = ctypes.c_ssize_t, ctypes.c_int32, ctypes.c_int64, ctypes.c_char_p, ctypes.c_void_p
signatures = {
"BakaShrot_GetLastError": (L, []),
"BakaShrot_SetPrivateKeyA": (I, [P]),
"BakaShrot_SetPublicKeyA": (I, [P]),
"BakaShrot_SetServerPublicKeyA": (I, [P]),
"BakaShrot_SetNodeA": (I, [P]),
"BakaShrot_ConnectA": (I, [P, L]),
"BakaShrot_IsConnected": (I, []),
"BakaShrot_Disconnect": (I, []),
"BakaShrot_PushMessageToA": (Q, [P, P]),
"BakaShrot_GetLatestMessageOfA": (I, [P, P]),
"BakaShrot_GetMessagesA": (L, [P, P, Q, L]),
"BakaShrot_GetMessageCount": (L, []),
"BakaShrot_SelectMessage": (I, [L]),
"BakaShrot_HasMoreMessages": (I, []),
"BakaShrot_GetMessageId": (Q, []),
"BakaShrot_GetMessagePushedAt": (Q, []),
"BakaShrot_GetMessageAttachmentSize": (Q, []),
"BakaShrot_IsMessageAttachmentReady": (I, []),
"BakaShrot_PushMessageWithFileA": (Q, [P, P, P]),
"BakaShrot_PushMessageWithDataA": (Q, [P, P, S, Q]),
"BakaShrot_SaveAttachmentA": (Q, [P, P, Q, P]),
"BakaShrot_LoadAttachmentA": (Q, [P, P, Q]),
"BakaShrot_GetAttachmentData": (Q, [S, Q]),
"BakaShrot_FreeAttachmentData": (I, []),
"BakaShrot_GetMessageTopicId": (L, []),
"BakaShrot_GetMessageNodeId": (L, []),
"BakaShrot_GetMessageTopicA": (I, [S, I]),
"BakaShrot_GetMessageNodeA": (I, [S, I]),
"BakaShrot_GetMessageDataA": (I, [S, I]),
"BakaShrot_ResolveTopicA": (L, [P]),
"BakaShrot_ResolveNodeA": (L, [P]),
"BakaShrot_GetResolvedNameA": (I, [S, I]),
"BakaShrot_ListTopics": (L, []),
"BakaShrot_ListNodes": (L, []),
"BakaShrot_GetNamesListA": (I, [S, I]),
"BakaShrot_QueryA": (I, [P]),
"BakaShrot_GetQueryResultA": (I, [S, I]),
"BakaShrot_GetRefusalReasonA": (I, [S, I]),
}
for name, (restype, argtypes) in signatures.items():
try:
function = getattr(self.lib, name)
except AttributeError as error:
raise BakaShrotError(f"{path} has no {name}, is it an older build?", ErrorCode.INTERNAL) from error
function.restype = restype
function.argtypes = argtypes
setattr(self, name[len("BakaShrot_"):], function)
def string(self, getter) -> str:
"""Calls a string getter: asks for the size, then copies (UTF-8)."""
size = getter(None, 0)
if size <= 1:
return ""
buffer = ctypes.create_string_buffer(size)
getter(buffer, size)
return buffer.raw[: size - 1].decode("utf-8")
class Client:
"""A connection to a BakaShrot server, through the DLL.
private_key, public_key: the client's Ed25519 keys in Base64 (BakaShrotGenerateKeyPairs.exe).
server_public_key: the server's Ed25519 public key in Base64, it must
prove it holds the matching private key.
node: the node the client writes as, a name or an id, which the
server's [BakaShrot.Client.<name>] must give its key (Node). Its
default topic, for pushes that don't name one, is the server's to say
(that section's DefaultTopic).
"""
_connected_client: Optional["Client"] = None
def __init__(self, private_key: str, public_key: str, server_public_key: str, node: Ref,
host: str = "127.0.0.1", port: int = 12345, dll_path: Optional[str] = None):
self._dll = _Dll.get(dll_path)
self._lock = threading.RLock()
self.private_key = private_key
self.public_key = public_key
self.server_public_key = server_public_key
self.node = node
self.host = host
self.port = int(port)
@classmethod
def from_ini(cls, path: str, dll_path: Optional[str] = None) -> "Client":
"""From a client.ini as the tools read it: [BakaShrot] PrivateKey,
PublicKey, ServerPublicKey, Node, ServerHost, ServerPort (a Topic
left in it is ignored)."""
parser = configparser.ConfigParser(interpolation=None)
if not parser.read(path, encoding="utf-8-sig"):
raise BakaShrotError(f"Failed to open '{path}'", ErrorCode.FILE_ERROR)
section = parser["BakaShrot"] if parser.has_section("BakaShrot") else {}
def get(key, fallback=None):
value = section.get(key, fallback)
if value is None:
raise BakaShrotError(f"'{path}' has no [BakaShrot] {key}", ErrorCode.INVALID_ARGUMENT)
return value.strip()
return cls(get("PrivateKey"), get("PublicKey"), get("ServerPublicKey"),
get("Node", section.get("NodeId")),
get("ServerHost"), int(get("ServerPort")), dll_path)
# --- Connection --------------------------------------------------------
def connect(self) -> "Client":
"""Connects and authenticates. Raises ConnectionLostError when the
server can't be reached (CONNECT_FAILED), AuthError when it rejects
the handshake or can't prove its key, BakaShrotError on a bad setting
(INVALID_ARGUMENT) or another Client holding the DLL's connection
(ALREADY_CONNECTED)."""
with self._lock:
owner = Client._connected_client
if owner is not None and owner is not self and owner.connected:
raise BakaShrotError("The DLL holds one connection, another Client is connected", ErrorCode.ALREADY_CONNECTED)
if self.connected:
return self
dll = self._dll
if not dll.SetPrivateKeyA(self.private_key.encode("ascii")):
raise BakaShrotError("Invalid private key", dll.GetLastError())
if not dll.SetPublicKeyA(self.public_key.encode("ascii")):
raise BakaShrotError("Invalid public key", dll.GetLastError())
if not dll.SetServerPublicKeyA(self.server_public_key.encode("ascii")):
raise BakaShrotError("Invalid server public key", dll.GetLastError())
if not dll.SetNodeA(_ref(self.node)):
raise BakaShrotError(f"Invalid node {self.node!r}", dll.GetLastError())
if not dll.ConnectA(self.host.encode("utf-8"), self.port):
raise self._failed(f"Connect to {self.host}:{self.port}")
Client._connected_client = self
return self
def close(self) -> None:
with self._lock:
if Client._connected_client is self:
self._dll.Disconnect()
Client._connected_client = None
@property
def connected(self) -> bool:
return Client._connected_client is self and bool(self._dll.IsConnected())
def __enter__(self) -> "Client":
return self.connect()
def __exit__(self, *_) -> None:
self.close()
def _check_connected(self) -> None:
if not self.connected:
raise ConnectionLostError("Not connected", ErrorCode.NOT_CONNECTED)
_MESSAGES = {
ErrorCode.NOT_CONNECTED: "not connected",
ErrorCode.CONNECT_FAILED: "nothing answers there",
ErrorCode.AUTH_REJECTED: "the server closed the connection during the handshake: wrong server public key, "
"a key or node it doesn't allow, or another version (its log says which)",
ErrorCode.SERVER_NOT_VERIFIED: "the server couldn't prove it holds the server public key's private key",
ErrorCode.CONNECTION_LOST: "the connection to the server failed",
ErrorCode.PROTOCOL_ERROR: "the server answered something unexpected, the connection is closed",
}
def _failed(self, what: str) -> BakaShrotError:
"""The error for a failed call, by the DLL's BakaShrot_GetLastError()."""
code = _error_code(self._dll.GetLastError())
reason = self._dll.string(self._dll.GetRefusalReasonA)
if isinstance(code, int) and 1 <= int(code) <= 99:
return RefusedError(reason, code)
if not self._dll.IsConnected() and Client._connected_client is self:
Client._connected_client = None
name = code.name if isinstance(code, ErrorCode) else str(code)
message = f"{what} ({name}): {reason or self._MESSAGES.get(code, 'failed')}"
if code in (ErrorCode.NOT_CONNECTED, ErrorCode.CONNECT_FAILED, ErrorCode.CONNECTION_LOST, ErrorCode.PROTOCOL_ERROR):
return ConnectionLostError(message, code)
if code in (ErrorCode.AUTH_REJECTED, ErrorCode.SERVER_NOT_VERIFIED):
return AuthError(message, code)
return BakaShrotError(message, code if code else ErrorCode.INTERNAL)
# --- Requests ----------------------------------------------------------
def push(self, data: Any, topic: Optional[Ref] = None,
attachment: Union[None, bytes, bytearray, memoryview, str, os.PathLike] = None) -> int:
"""Pushes a message into topic (default: the client's default one, its server's DefaultTopic), under
the client's node. data is stored as is if it's a str (JSON or not),
anything else is turned into JSON first. Returns its message id.
attachment: bytes, or the path of a file, uploaded first (in parts,
any size the server's MaxAttachmentSize allows): the message is only
stored once all of it is."""
if not isinstance(data, str):
data = json.dumps(data, separators=(",", ":"), ensure_ascii=False)
encoded = data.encode("utf-8")
if len(encoded) > MAX_MESSAGE_SIZE:
raise BakaShrotError(f"The message is too big: {len(encoded)} bytes, at most {MAX_MESSAGE_SIZE}", ErrorCode.INVALID_ARGUMENT)
topic_ref = b"" if topic is None else _ref(topic)
with self._lock:
self._check_connected()
if attachment is None:
message_id = self._dll.PushMessageToA(topic_ref, encoded)
elif isinstance(attachment, (bytes, bytearray, memoryview)):
raw = bytes(attachment)
if not raw:
raise BakaShrotError("The attachment is empty", ErrorCode.INVALID_ARGUMENT)
buffer = ctypes.create_string_buffer(raw, len(raw))
message_id = self._dll.PushMessageWithDataA(topic_ref, encoded, ctypes.cast(buffer, ctypes.c_void_p), len(raw))
else:
path = os.fspath(attachment)
if not os.path.isfile(path) or os.path.getsize(path) == 0:
raise BakaShrotError(f"Can't attach {path!r}: no such file, or empty", ErrorCode.FILE_ERROR)
message_id = self._dll.PushMessageWithFileA(topic_ref, encoded, path.encode("utf-8"))
if message_id < 1:
raise self._failed("Push")
return message_id
def get_attachment(self, topic: Ref, node: Ref, message_id: int) -> bytes:
"""The attachment of topic:node#message_id, all of it in memory
(save_attachment() for big ones), checked with its SHA-256. Raises
RefusedError if the message has none, or it isn't on this server
yet."""
with self._lock:
self._check_connected()
size = self._dll.LoadAttachmentA(_ref(topic), _ref(node), int(message_id))
if size < 0:
raise self._failed("Attachment")
try:
buffer = ctypes.create_string_buffer(size)
self._dll.GetAttachmentData(ctypes.cast(buffer, ctypes.c_void_p), size)
return buffer.raw[:size]
finally:
self._dll.FreeAttachmentData()
def save_attachment(self, topic: Ref, node: Ref, message_id: int, path: Union[str, os.PathLike]) -> int:
"""Saves the attachment of topic:node#message_id to path (replaced),
a part at a time, checked with its SHA-256. Returns its size. A
failed one leaves no file."""
with self._lock:
self._check_connected()
size = self._dll.SaveAttachmentA(_ref(topic), _ref(node), int(message_id), os.fspath(path).encode("utf-8"))
if size < 0:
raise self._failed("Attachment")
return size
def _current(self) -> Message:
dll = self._dll
return Message(dll.GetMessageId(), dll.string(dll.GetMessageTopicA), dll.string(dll.GetMessageNodeA),
dll.GetMessageTopicId(), dll.GetMessageNodeId(), dll.string(dll.GetMessageDataA),
dll.GetMessagePushedAt(), dll.GetMessageAttachmentSize(), bool(dll.IsMessageAttachmentReady()))
def latest(self, topic: Ref, node: Ref) -> Optional[Message]:
"""The latest message of topic/node, None if there's none yet."""
with self._lock:
self._check_connected()
if not self._dll.GetLatestMessageOfA(_ref(topic), _ref(node)):
error = self._failed("Latest message")
if isinstance(error, RefusedError) and error.code == ErrorCode.NOT_FOUND:
return None
raise error
return self._current()
def get_messages(self, topic: Ref, node: Ref, after: int = 0, limit: int = 1000) -> MessagesPage:
"""The messages of topic/node after message id `after` (0: from the
first), in id order: at most limit (1-10000), fewer if they didn't
fit in about 1 MB (a bigger one comes alone). None if there are no
more, that's not an error."""
if not 1 <= limit <= MAX_GET_MESSAGES:
raise ValueError(f"limit is 1-{MAX_GET_MESSAGES}, not {limit}")
if after < 0:
raise ValueError(f"after is 0 or more, not {after}")
with self._lock:
self._check_connected()
dll = self._dll
count = dll.GetMessagesA(_ref(topic), _ref(node), after, limit)
if count < 0:
raise self._failed("Get messages")
messages = []
for index in range(count):
dll.SelectMessage(index)
messages.append(self._current())
return MessagesPage(messages, bool(dll.HasMoreMessages()))
def iter_messages(self, topic: Ref, node: Ref, after: int = 0, batch: int = 1000) -> Iterator[Message]:
"""Every message of topic/node after `after`, asking for batch at a
time, until there are no more."""
while True:
page = self.get_messages(topic, node, after, batch)
yield from page.messages
if page.messages:
after = page.last_id
if not page.more:
return
def follow(self, topic: Ref, node: Ref, after: Union[int, str] = "latest",
interval: float = 0.5, batch: int = 1000) -> Iterator[Message]:
"""Every message of topic/node after `after`, then new ones as they
come, checking every `interval` seconds once caught up. Forever:
stop iterating to stop. after="latest" starts with the next new one.
Raises ConnectionLostError if the connection fails: nothing
reconnects by itself, connect() again and follow from the last id."""
if after == "latest":
latest = self.latest(topic, node)
after = latest.id if latest else 0
elif not isinstance(after, int):
raise ValueError(f"after is a message id or 'latest', not {after!r}")
while True:
page = self.get_messages(topic, node, after, batch)
yield from page.messages
if page.messages:
after = page.last_id
if not page.more:
time.sleep(interval)
def resolve_topic(self, ref: Ref) -> tuple:
"""(id, name) of a topic on this server, name "" if unnamed."""
return self._resolve(self._dll.ResolveTopicA, ref, "Resolve topic")
def resolve_node(self, ref: Ref) -> tuple:
"""(id, name) of a node on this server, name "" if unnamed."""
return self._resolve(self._dll.ResolveNodeA, ref, "Resolve node")
def _resolve(self, function, ref: Ref, what: str) -> tuple:
with self._lock:
self._check_connected()
resolved = function(_ref(ref))
if resolved < 0:
raise self._failed(what)
return resolved, self._dll.string(self._dll.GetResolvedNameA)
def list_topics(self) -> NamesList:
"""Every topic the client may see, with this server's ids."""
return self._list(self._dll.ListTopics, "List topics")
def list_nodes(self) -> NamesList:
"""Every node, with this server's ids."""
return self._list(self._dll.ListNodes, "List nodes")
def _list(self, function, what: str) -> NamesList:
with self._lock:
self._check_connected()
if function() < 0:
raise self._failed(what)
parsed = json.loads(self._dll.string(self._dll.GetNamesListA))
return NamesList(parsed["kind"], [NameEntry(i["id"], i["name"], i["origin"]) for i in parsed["items"]],
bool(parsed["truncated"]))
def query_raw(self, sql: str) -> str:
"""Runs one read-only SELECT on the server (the client needs
AllowQuery = 1), returns its result as the server's JSON text:
{"columns": [...], "rows": [[...], ...]}, every value a str or null.
JSON functions on message_data need "is_json = 1" in the WHERE (or
CASE WHEN is_json THEN ... END) when some rows aren't JSON, or the
query is refused: RefusedError "Query failed: malformed JSON"."""
with self._lock:
self._check_connected()
if not self._dll.QueryA(sql.encode("utf-8")):
raise self._failed("Query")
return self._dll.string(self._dll.GetQueryResultA)
def query(self, sql: str) -> list:
"""query_raw(), as a list of dicts, one per row, by column name."""
result = json.loads(self.query_raw(sql))
columns = result["columns"]
return [dict(zip(columns, row)) for row in result["rows"]]
@@ -0,0 +1,229 @@
"""Checks bakashrot.py against a running server, run by Tests/Python-Test.ps1.
Usage: python check_bakashrot.py <DllPath> <KitchenIni> <LoungeIni>
KitchenIni logs:kitchen, may push to logs and secret, read everything, query.
LoungeIni logs:lounge, may read logs only.
Expects an empty database. Prints PASS/FAIL per check, exits 1 if any failed.
"""
import hashlib
import os
import sys
import tempfile
import threading
import time
import bakashrot
from bakashrot import AuthError, BakaShrotError, Client, ConnectionLostError, ErrorCode, RefusedError
dll_path, kitchen_ini, lounge_ini = sys.argv[1:4]
fails = 0
def check(what, ok, detail=""):
global fails
if not ok:
fails += 1
detail = str(detail)
if len(detail) > 300:
detail = detail[:300] + f"... ({len(detail)} chars)"
print(f"{'PASS' if ok else 'FAIL'} {what}\n -> {detail}", flush=True)
def raises(function, error_type, contains="", code=None):
try:
function()
except error_type as error:
got = getattr(error, "code", None)
return contains in str(error) and (code is None or got == code), f"{type(error).__name__} [{got!r}]: {error}"
except Exception as error: # noqa: BLE001 - reported as a failure
return False, f"{type(error).__name__}: {error}"
return False, "didn't raise"
kitchen = Client.from_ini(kitchen_ini, dll_path)
lounge = Client.from_ini(lounge_ini, dll_path)
with kitchen:
check("Connects from client.ini", kitchen.connected, kitchen._dll.path)
# --- Nothing yet ---------------------------------------------------------
check("latest() with no messages: None", kitchen.latest("logs", "kitchen") is None)
page = kitchen.get_messages("logs", "kitchen")
check("get_messages() with no messages: empty, no more", len(page) == 0 and not page.more and page.last_id is None, page)
# --- Pushes --------------------------------------------------------------
started = time.perf_counter()
ids = [kitchen.push({"i": i}) for i in range(1, 251)]
elapsed = time.perf_counter() - started
check("250 pushes on one connection, ids 1-250", ids == list(range(1, 251)),
f"{elapsed * 1000:.0f} ms, {250 / elapsed:.0f} msg/s")
latest = kitchen.latest("logs", "kitchen")
check("latest(): #250", latest is not None and latest.id == 250 and latest.json() == {"i": 250}, latest)
now_ms = int(time.time() * 1000)
check("latest().pushed_at: just now, UTC ms", latest is not None and now_ms - 60000 < latest.pushed_at <= now_ms + 1000,
f"{latest.pushed_at if latest else None} vs {now_ms}")
check("latest().pushed: the same, an aware datetime in UTC",
latest is not None and latest.pushed.tzinfo is not None and latest.pushed.utcoffset().total_seconds() == 0
and int(latest.pushed.timestamp() * 1000) == latest.pushed_at, latest.pushed if latest else None)
topic_id, topic_name = kitchen.resolve_topic("logs")
node_id, node_name = kitchen.resolve_node("kitchen")
check("resolve_topic/node()", (topic_id, topic_name, node_id, node_name) == (1, "logs", 5, "kitchen"),
(topic_id, topic_name, node_id, node_name))
# --- Pages ---------------------------------------------------------------
page = kitchen.get_messages("logs", "kitchen", after=0, limit=100)
check("First page: 1-100, more", [m.id for m in page] == list(range(1, 101)) and page.more and page.last_id == 100,
f"{len(page)} messages, more={page.more}")
first = page.messages[0]
check("A message's fields", (first.topic, first.node, first.topic_id, first.node_id, first.data, first.json())
== ("logs", "kitchen", 1, 5, '{"i":1}', {"i": 1}), first)
stamps = [m.pushed_at for m in page]
check("Each message of a page has its pushed_at, in push order", all(stamps) and stamps == sorted(stamps),
f"{stamps[0]} .. {stamps[-1]}")
page = kitchen.get_messages("logs", "kitchen", after=200, limit=100)
check("Last page: 201-250, no more", [m.id for m in page] == list(range(201, 251)) and not page.more,
f"{len(page)} messages, more={page.more}")
page = kitchen.get_messages("logs", "kitchen", after=150, limit=100)
check("Exactly up to the last one: 151-250, no more", [m.id for m in page] == list(range(151, 251)) and not page.more,
f"{len(page)} messages, more={page.more}")
page = kitchen.get_messages("1", 5, after=250)
check("After the last one, by ids: empty, no more", len(page) == 0 and not page.more, page)
every = list(kitchen.iter_messages("logs", "kitchen", batch=37))
check("iter_messages(batch=37): all 250 in order", [m.id for m in every] == list(range(1, 251)), f"{len(every)} messages")
# --- Data ----------------------------------------------------------------
text_id = kitchen.push("plain text, not JSON")
unicode_id = kitchen.push("héllo wörld, 🌍, 日本語")
empty_id = kitchen.push("")
page = kitchen.get_messages("logs", "kitchen", after=250)
data = [m.data for m in page]
check("Non-JSON, non-ASCII and empty data read back as pushed",
data == ["plain text, not JSON", "héllo wörld, 🌍, 日本語", ""] and [m.id for m in page] == [text_id, unicode_id, empty_id],
data)
ok, detail = raises(lambda: page.messages[0].json(), ValueError)
check("json() on non-JSON data raises ValueError", ok, detail)
rows = kitchen.query("SELECT is_json, COUNT(*) AS n FROM data GROUP BY is_json ORDER BY is_json")
check("query(): is_json flags 3 non-JSON, 250 JSON", rows == [{"is_json": "0", "n": "3"}, {"is_json": "1", "n": "250"}], rows)
ok, detail = raises(lambda: kitchen.query("SELECT nope FROM data"), RefusedError, "nope", ErrorCode.QUERY_FAILED)
check("A query that fails: RefusedError, QUERY_FAILED", ok, detail)
# --- Answers split at ~1 MB ----------------------------------------------
big = "x" * (700 * 1024)
big_ids = [kitchen.push(big) for _ in range(3)]
page = kitchen.get_messages("logs", "kitchen", after=empty_id, limit=10)
check("3 x 700 KB: one per answer, more", [m.id for m in page] == big_ids[:1] and page.more and page.messages[0].data == big,
f"{len(page)} messages, more={page.more}")
every = list(kitchen.iter_messages("logs", "kitchen", after=empty_id))
check("iter_messages() over them: all 3, whole", [m.id for m in every] == big_ids and all(m.data == big for m in every),
[len(m.data) for m in every])
# --- Refusals ------------------------------------------------------------
ok, detail = raises(lambda: kitchen.get_messages("logs", "nobody"), RefusedError, "Unknown node 'nobody'", ErrorCode.UNKNOWN_NAME)
check("Unknown node: RefusedError, UNKNOWN_NAME", ok, detail)
check("Still connected after a refusal", kitchen.connected and kitchen.latest("logs", "kitchen").id == big_ids[-1])
ok, detail = raises(lambda: kitchen.get_messages("logs", "kitchen", limit=0), ValueError)
check("limit 0: ValueError, before asking", ok, detail)
ok, detail = raises(lambda: kitchen.get_messages("logs", "kitchen", after=-1), ValueError)
check("after -1: ValueError", ok, detail)
ok, detail = raises(lambda: kitchen.push("x", topic="nothing"), RefusedError, "Unknown topic", ErrorCode.UNKNOWN_NAME)
check("Push to an unknown topic: RefusedError, UNKNOWN_NAME", ok, detail)
secret_id = kitchen.push({"s": 1}, topic="secret")
check("Push to another allowed topic", secret_id == 1, secret_id)
ok, detail = raises(lambda: lounge.connect(), BakaShrotError, "one connection", ErrorCode.ALREADY_CONNECTED)
check("A second Client can't connect while one is", ok and not lounge.connected, detail)
topics = kitchen.list_topics()
check("list_topics()", topics.kind == "topic" and {"logs", "secret"} <= {t.name for t in topics.items}, topics)
# --- follow() ------------------------------------------------------------
followed = []
errors = []
def follower():
try:
for message in kitchen.follow("logs", "kitchen", after="latest", interval=0.05):
followed.append(message)
if len(followed) == 5:
return
except Exception as error: # noqa: BLE001 - reported below
errors.append(error)
thread = threading.Thread(target=follower, daemon=True)
thread.start()
time.sleep(0.5)
new_ids = [kitchen.push({"f": i}) for i in range(5)]
thread.join(10)
check("follow(after='latest') from another thread: only the 5 new ones",
not thread.is_alive() and not errors and [m.id for m in followed] == new_ids,
f"{[m.id for m in followed]} vs {new_ids}, errors {errors}")
# --- Attachments (in secret, the other checks count logs) -------------------
blob = os.urandom(3 * 1024 * 1024 + 7)
started = time.perf_counter()
blob_id = kitchen.push({"kind": "blob"}, topic="secret", attachment=blob)
up = time.perf_counter() - started
message = kitchen.latest("secret", "kitchen")
check("push(attachment=bytes): the message has it, ready",
message is not None and message.id == blob_id and message.attachment_size == len(blob) and message.attachment_ready,
message)
started = time.perf_counter()
data = kitchen.get_attachment("secret", "kitchen", blob_id)
down = time.perf_counter() - started
check("get_attachment(): the same bytes", data == blob, f"{len(data)} bytes, {up * 1000:.0f} ms up, {down * 1000:.0f} ms down")
folder = tempfile.mkdtemp()
source = os.path.join(folder, "source.bin")
with open(source, "wb") as file:
file.write(os.urandom(1500 * 1024))
file_id = kitchen.push("from a file", topic="secret", attachment=source)
copy = os.path.join(folder, "copy.bin")
size = kitchen.save_attachment("secret", "kitchen", file_id, copy)
with open(source, "rb") as a, open(copy, "rb") as b:
same = hashlib.sha256(a.read()).digest() == hashlib.sha256(b.read()).digest()
check("push(attachment=path), save_attachment(): the same file", size == os.path.getsize(source) and same, size)
plain_id = kitchen.push("no attachment", topic="secret")
page = kitchen.get_messages("secret", "kitchen", after=blob_id - 1)
sizes = [(m.id, m.attachment_size, m.attachment_ready) for m in page]
check("get_messages(): each message's attachment",
sizes == [(blob_id, len(blob), True), (file_id, os.path.getsize(source), True), (plain_id, 0, False)], sizes)
ok, detail = raises(lambda: kitchen.get_attachment("secret", "kitchen", plain_id), RefusedError, "No attachment", ErrorCode.NOT_FOUND)
check("get_attachment() of a message without: RefusedError, NOT_FOUND", ok, detail)
ok, detail = raises(lambda: kitchen.push("x", topic="secret", attachment=b""), BakaShrotError, "empty", ErrorCode.INVALID_ARGUMENT)
check("An empty attachment: refused before sending", ok, detail)
ok, detail = raises(lambda: kitchen.push("x", topic="secret", attachment=os.path.join(folder, "missing.bin")), BakaShrotError, "no such file", ErrorCode.FILE_ERROR)
check("A missing file: refused before sending", ok, detail)
check("Still connected", kitchen.connected)
check("close(): disconnected", not kitchen.connected)
ok, detail = raises(lambda: kitchen.push("x"), ConnectionLostError, code=ErrorCode.NOT_CONNECTED)
check("A request once closed: ConnectionLostError, NOT_CONNECTED", ok, detail)
# --- Connecting: unreachable, rejected ---------------------------------------
nowhere = Client(kitchen.private_key, kitchen.public_key, kitchen.server_public_key, kitchen.node, "127.0.0.1", 1, dll_path)
ok, detail = raises(nowhere.connect, ConnectionLostError, code=ErrorCode.CONNECT_FAILED)
check("Nothing listening: ConnectionLostError, CONNECT_FAILED", ok, detail)
stranger = Client(kitchen.private_key, kitchen.public_key, kitchen.server_public_key, "nobody", kitchen.host, kitchen.port, dll_path)
ok, detail = raises(stranger.connect, AuthError, code=ErrorCode.AUTH_REJECTED)
check("A node the server doesn't give this key: AuthError, AUTH_REJECTED", ok, detail)
with lounge:
page = lounge.get_messages("logs", "kitchen", after=245, limit=3)
check("Another identity once the first closed: reads logs", [m.id for m in page] == [246, 247, 248] and page.more,
f"{[m.id for m in page]}, more={page.more}")
ok, detail = raises(lambda: lounge.get_messages("secret", "kitchen"), RefusedError, "Not allowed to read topic 'secret'", ErrorCode.NOT_ALLOWED)
check("A topic not in its ReadTopics: RefusedError, NOT_ALLOWED", ok, detail)
ok, detail = raises(lambda: lounge.query("SELECT 1"), RefusedError, "Not allowed to query", ErrorCode.NOT_ALLOWED)
check("Not allowed to query: RefusedError, NOT_ALLOWED", ok, detail)
print()
print("All checks passed" if fails == 0 else f"{fails} check(s) failed")
sys.exit(1 if fails else 0)
+42
View File
@@ -0,0 +1,42 @@
"""Example app: catches up on a topic/node's messages, then follows new ones.
Usage: python example.py <ClientIni> <Topic> <Node> [--from-start]
Run it from Build\\ (Build.ps1) while BakaShrot_Server.exe runs, e.g.:
python ..\\Interactors\\Python\\example.py client.ini logs local
and push from another terminal:
.\\BakaShrotPushMessage.exe @msg.json client.ini
Ctrl+C to stop.
"""
import json
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from bakashrot import Client, ConnectionLostError # noqa: E402
if len(sys.argv) < 4:
print(__doc__)
sys.exit(1)
ini, topic, node = sys.argv[1:4]
after = 0 if "--from-start" in sys.argv[4:] else "latest"
# The DLL next to the ini (Build\), unless BAKASHROT_DLL says otherwise.
dll = os.environ.get("BAKASHROT_DLL") or os.path.join(os.path.dirname(os.path.abspath(ini)), "BakaShrot_Client.dll")
try:
with Client.from_ini(ini, dll) as client:
print(f"Connected to {client.host}:{client.port} as node {client.node}, following {topic}:{node}")
for message in client.follow(topic, node, after=after):
# Parsing is the app's business: the server stores anything.
try:
shown = json.dumps(message.json())
except ValueError:
shown = f"(not JSON) {message.data!r}"
print(f"{message.topic}:{message.node}#{message.id} {shown}")
except KeyboardInterrupt:
pass
except ConnectionLostError as error:
print(error)
sys.exit(1)
+204
View File
@@ -0,0 +1,204 @@
"""Builds the bakashrot wheel: bakashrot.py with the client library it
needs, so that `pip install` is all a Python app needs, nothing to compile.
python make_wheel.py <BinDir> [OutDir] [--linux]
BinDir holds BakaShrot_Client.dll and libsodium.dll (a release folder, or
Build\\). OutDir defaults to the current directory. Release.ps1 runs it.
Prints the wheel's path.
--linux: the Linux wheel instead, from a Linux build's BakaShrot_Client.dll
(the .so, named as on Windows: bakashrot.py and the tools look for that
name). libsodium isn't in it: it comes from the system (Debian/Ubuntu:
libsodium23), and the wheel needs glibc 2.34+. Tagged linux_x86_64, not
manylinux: manylinux doesn't allow depending on libsodium. Build the .so on
an old enough glibc (the Docker compiler image, Debian 13, needs 2.34).
Licenses: BakaShrot is CC0-1.0, libsodium ISC, which asks for its notice
in every copy: both are in the Windows wheel's dist-info/licenses/ (LICENSE,
and Libs/libsodium/LICENSE), the metadata says "CC0-1.0 AND ISC". The Linux
wheel only has LICENSE, "CC0-1.0", libsodium not being in it.
vcruntime140.dll, which libsodium.dll needs, isn't in the Windows wheel:
every CPython on Windows has loaded its own already, and that's the one used.
The wheel is bakashrot-<version>-py3-none-win_amd64.whl (or
-linux_x86_64.whl), the version being bakashrot.py's __version__. Inside
it, bakashrot.py is bakashrot/__init__.py, the libraries next to it, where
bakashrot.py looks first. Only the standard library: no setuptools, no
build step, and the same inputs give the same wheel (fixed timestamps).
"""
import base64
import hashlib
import os
import re
import sys
import zipfile
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.normpath(os.path.join(HERE, "..", ".."))
NAME = "bakashrot"
# Zip entries' timestamp, so the wheel only changes when its content does.
FIXED_TIME = (2026, 1, 1, 0, 0, 0)
USAGE_EXAMPLE = """\
```python
from bakashrot import Client
with Client.from_ini("client.ini") as client:
message_id = client.push({"temperature": 21.5})
for message in client.get_messages("logs", "kitchen", after=0).messages:
print(message.id, message.data)
```
See the module's docstring (`help(bakashrot)`) for the rest.
"""
WINDOWS = {
"tag": "py3-none-win_amd64",
"libraries": ["BakaShrot_Client.dll", "libsodium.dll"],
# In the wheel's dist-info/licenses/, from the repository's root.
"licenses": {"LICENSE": "../LICENSE", "libsodium/LICENSE": "Libs/libsodium/LICENSE"},
"license_expression": "CC0-1.0 AND ISC",
"classifier": "Operating System :: Microsoft :: Windows :: Windows 10",
"summary": "Python client for BakaShrot servers, with the client DLL included",
"description": """\
# bakashrot
Python client for [BakaShrot](https://github.com/aziascreations/BakaShrot)
servers: push messages and attachments, read them back, resolve names, query.
Includes `BakaShrot_Client.dll` and `libsodium.dll`: nothing else to install
or build. Windows 10 or later, 64-bit Python 3.8+. The server must speak the
same protocol: use the release this package comes from.
BakaShrot is CC0-1.0 (public domain). The included libsodium is Frank
Denis's, under the ISC license: its notice is in this package's
`licenses/libsodium/LICENSE`.
""" + USAGE_EXAMPLE,
}
LINUX = {
"tag": "py3-none-linux_x86_64",
"libraries": ["BakaShrot_Client.dll"],
"licenses": {"LICENSE": "../LICENSE"},
"license_expression": "CC0-1.0",
"classifier": "Operating System :: POSIX :: Linux",
"summary": "Python client for BakaShrot servers, with the client library included",
"description": """\
# bakashrot
Python client for [BakaShrot](https://github.com/aziascreations/BakaShrot)
servers: push messages and attachments, read them back, resolve names, query.
Includes the client library (`BakaShrot_Client.dll`, a Linux shared object
named as on Windows). Needs libsodium from the system, nothing else to build:
`apt install libsodium23` on Debian and Ubuntu. Linux x86-64 with glibc 2.34+
(Debian 12, Ubuntu 22.04 or later), 64-bit Python 3.8+. The server must speak
the same protocol: use the release this package comes from.
BakaShrot is CC0-1.0 (public domain).
""" + USAGE_EXAMPLE,
}
def read_version(module_path):
with open(module_path, encoding="utf-8") as file:
match = re.search(r'^__version__ = "([^"]+)"', file.read(), re.MULTILINE)
if not match:
sys.exit(f"No __version__ in {module_path}")
return match.group(1)
def record_line(path, data):
digest = base64.urlsafe_b64encode(hashlib.sha256(data).digest()).rstrip(b"=").decode("ascii")
return f"{path},sha256={digest},{len(data)}"
def main():
args = sys.argv[1:]
platform = WINDOWS
if "--linux" in args:
args.remove("--linux")
platform = LINUX
if len(args) not in (1, 2):
sys.exit(__doc__)
bin_dir = args[0]
out_dir = args[1] if len(args) == 2 else os.getcwd()
tag = platform["tag"]
module_path = os.path.join(HERE, "bakashrot.py")
version = read_version(module_path)
dist_info = f"{NAME}-{version}.dist-info"
files = [] # (path in the wheel, bytes)
with open(module_path, "rb") as file:
files.append((f"{NAME}/__init__.py", file.read()))
for library in platform["libraries"]:
path = os.path.join(bin_dir, library)
if not os.path.isfile(path):
sys.exit(f"Missing {path}")
with open(path, "rb") as file:
data = file.read()
# A Windows DLL starts with "MZ", a Linux .so with "\x7fELF": a
# library from the other platform would only fail once imported.
if platform is LINUX and not data.startswith(b"\x7fELF"):
sys.exit(f"{path} isn't a Linux shared object (build it on Linux, or drop --linux)")
if platform is WINDOWS and data.startswith(b"\x7fELF"):
sys.exit(f"{path} is a Linux shared object (add --linux)")
files.append((f"{NAME}/{library}", data))
# Metadata 2.4 (PEP 639): an SPDX expression and the license files,
# without license classifiers (not allowed with an expression).
metadata = "\n".join([
"Metadata-Version: 2.4",
f"Name: {NAME}",
f"Version: {version}",
f"Summary: {platform['summary']}",
"Author: Herwin Bozet (NibblePoker)",
f"License-Expression: {platform['license_expression']}",
] + [f"License-File: {name}" for name in platform["licenses"]] + [
"Project-URL: GitHub, https://github.com/aziascreations/BakaShrot",
"Project-URL: Gitea, https://git.nibblepoker.lu/aziascreations/BakaShrot",
f"Classifier: {platform['classifier']}",
"Classifier: Programming Language :: Python :: 3",
"Requires-Python: >=3.8",
"Description-Content-Type: text/markdown",
"",
platform["description"],
]).encode("utf-8")
files.append((f"{dist_info}/METADATA", metadata))
files.append((f"{dist_info}/WHEEL", "\n".join([
"Wheel-Version: 1.0",
"Generator: BakaShrot make_wheel.py",
"Root-Is-Purelib: false",
f"Tag: {tag}",
"",
]).encode("utf-8")))
for name, source in platform["licenses"].items():
path = os.path.join(ROOT, source)
if not os.path.isfile(path):
sys.exit(f"Missing {path}")
with open(path, "rb") as file:
files.append((f"{dist_info}/licenses/{name}", file.read()))
record = "\n".join([record_line(path, data) for path, data in files] + [f"{dist_info}/RECORD,,", ""])
files.append((f"{dist_info}/RECORD", record.encode("utf-8")))
os.makedirs(out_dir, exist_ok=True)
wheel_path = os.path.join(out_dir, f"{NAME}-{version}-{tag}.whl")
with zipfile.ZipFile(wheel_path, "w", zipfile.ZIP_DEFLATED) as wheel:
for path, data in files:
info = zipfile.ZipInfo(path, FIXED_TIME)
info.compress_type = zipfile.ZIP_DEFLATED
# The shared object must stay executable for some loaders.
info.external_attr = (0o755 if path.endswith(".dll") and platform is LINUX else 0o644) << 16
wheel.writestr(info, data)
print(wheel_path)
if __name__ == "__main__":
main()
+2
View File
@@ -0,0 +1,2 @@
This interactor should be able toquery a server via a client app.
The client should never parse the JSON, only the final app should.
@@ -0,0 +1,2 @@
[InternetShortcut]
URL=https://download.libsodium.org/libsodium/releases/
+18
View File
@@ -0,0 +1,18 @@
/*
* ISC License
*
* Copyright (c) 2013-2026
* Frank Denis <j at pureftpd dot org>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
+26
View File
@@ -0,0 +1,26 @@
# Runtime redistributables
DLLs the release needs next to its exes that Windows doesn't always have,
packaged by `Release.ps1`.
| File | Needed by | From | Version |
|---|---|---|---|
| `x64/vcruntime140.dll` | `libsodium.dll` (the official MSVC build) | Visual Studio 2026 (18) Community, `VC\Redist\MSVC\14.51.36231\x64\Microsoft.VC145.CRT\` | 14.51.36247.0 |
SHA-256 of `x64/vcruntime140.dll`:
`D1F4225DF2CD877DBF130D5668A021DCE3F94118455FF5EC952061C30AFC9CE7`
- **Why:** `libsodium.dll` imports `vcruntime140.dll` (the Visual C++
2015-2026 runtime). Without it, on a Windows without that runtime
installed, `BakaShrot_Server.exe`, `BakaShrot_Client.dll` and every tool
fail to load. Next to the exe, it's found before any installed one.
- **Not needed:** the other DLLs of that folder (`msvcp140.dll`,
`vcruntime140_1.dll`, ...): nothing imports them. The `api-ms-win-crt-*`
DLLs libsodium also imports are the Universal CRT, part of Windows 10 and
later, so the release needs Windows 10+.
- **Allowed:** files from Visual Studio's `VC\Redist` folder are the ones its
license lets you redistribute with an app.
- **Updating:** copy the newer one from that folder, update this table and
the hash. To check what a binary imports:
`grep -a -o -i -E "(vcruntime[0-9_]*|msvcp[0-9_]*|api-ms-win-crt-[a-z0-9-]+)\.dll" <file>`
- x86 isn't built, so there's no `x86/`.
Binary file not shown.
+1013
View File
File diff suppressed because it is too large Load Diff
+412
View File
@@ -0,0 +1,412 @@
# ============================================================================
# BakaShrot release build
#
# Builds everything with PureBasic 6.40's C backend and its optimizer into
# Release\<version>\, ready to copy to a server or hand to a client:
# BakaShrot_Server.exe the server
# BakaShrot_Client.dll the client DLL, with
# BakaShrot_Client_Prototypes.pbi its PureBasic prototypes, and
# BakaShrot_ErrorCodes.pbi the error codes they include
# BakaShrotPushMessage.exe, BakaShrotGetLatestMessage.exe,
# BakaShrotGetMessages.exe, BakaShrotGetAttachment.exe, BakaShrotQuery.exe,
# BakaShrotResolveIds.exe, BakaShrotList.exe,
# BakaShrotGenerateKeyPairs.exe the tools
# libsodium.dll, sqlite3.dll what they need next to them
# vcruntime140.dll what libsodium.dll needs (Libs\redist)
# python\bakashrot.py, example.py the Python client, over the DLL
# python\bakashrot-*.whl the same with the DLLs in it, for pip
# (if Python is on the PATH)
# config.example.ini the server's config, documented
# VERSION.txt commit, date, compiler, libraries
# LICENSE.txt, LICENSE-libsodium.txt BakaShrot's (CC0), libsodium's (ISC,
# its notice must ship with it)
# and Release\BakaShrot-<version>.zip of it, unless -NoZip.
#
# No keys and no configs with keys in it: generate them with BakaShrotGenerateKeyPairs.exe.
#
# Then checks the build works, unless -SkipTest: generates keys, runs the
# server from the release folder on a spare port with a throwaway database,
# pushes two messages, reads them back by name (the latest, then both),
# resolves a name and queries it through the "messages" view with the
# tools, reads them with the Python client if Python is on the PATH, then
# stops the server and deletes all of it.
#
# Usage:
# powershell -ExecutionPolicy Bypass -File Release.ps1
# ... -Version 1.2.0 instead of <date>-<commit>
# ... -Force replaces Release\<version>\ if it exists
# ... -Compiler <path> -NoOptimizer -SqliteDll <path> -SkipTest -NoZip
#
# Needs libsodium in Libs\libsodium\x64 and sqlite3.dll (3.38+, for the JSON
# functions) in Libs\sqlite\x64, Build.ps1 extracts both from Libs\*.zip.
# ============================================================================
param(
[string]$Version = "",
[string]$Compiler = "C:\Program Files\PureBasic_640\Compilers\pbcompilerc.exe",
[switch]$NoOptimizer,
[string]$SqliteDll = "",
[string]$OutRoot = "",
[switch]$Force,
[switch]$SkipTest,
[switch]$NoZip,
[int]$TestPort = 12399
)
$ErrorActionPreference = "Stop"
$Root = $PSScriptRoot
if (-not $OutRoot) { $OutRoot = Join-Path $Root "Release" }
# --- Checks -----------------------------------------------------------------
if (-not (Test-Path $Compiler)) { throw "Compiler not found: $Compiler, pass -Compiler" }
$CompilerName = ((& $Compiler /VERSION) | Select-Object -First 1) -replace " - \(c\).*$", ""
if ($CompilerName -notmatch "PureBasic 6\.") { throw "Expected PureBasic 6.x, got '$CompilerName'" }
if ($CompilerName -notmatch "C Backend") { Write-Warning "Not the C backend: $CompilerName" }
$Sodium = Join-Path $Root "Libs\libsodium\x64\libsodium.dll"
if (-not (Test-Path $Sodium) -or -not (Test-Path (Join-Path $Root "Libs\libsodium\x64\libsodium.lib"))) {
throw "Missing Libs\libsodium\x64\libsodium.dll/.lib, run Build.ps1 once to extract them"
}
if (-not $SqliteDll) { $SqliteDll = Join-Path $Root "Libs\sqlite\x64\sqlite3.dll" }
if (-not (Test-Path $SqliteDll)) { throw "Missing $SqliteDll, run Build.ps1 once to extract it, or pass -SqliteDll" }
$SqliteVersion = (Get-Item $SqliteDll).VersionInfo.ProductVersion
if ([version]$SqliteVersion -lt [version]"3.38") { throw "SQLite $SqliteVersion is too old, the JSON functions need 3.38+" }
$SodiumVersion = (Get-Item $Sodium).VersionInfo.ProductVersion
# Its ISC license asks for its notice in every copy, the wheel's too.
$SodiumLicense = Join-Path $Root "Libs\libsodium\LICENSE"
if (-not (Test-Path $SodiumLicense)) { throw "Missing Libs\libsodium\LICENSE, libsodium's notice must ship with it" }
# The runtime DLLs Windows may not have, see Libs\redist\README.md.
$Redist = @(Get-ChildItem (Join-Path $Root "Libs\redist\x64") -Filter "*.dll" -ErrorAction SilentlyContinue)
if (-not ($Redist | Where-Object { $_.Name -eq "vcruntime140.dll" })) {
throw "Missing Libs\redist\x64\vcruntime140.dll, libsodium.dll needs it, see Libs\redist\README.md"
}
$RedistVersion = ($Redist | Where-Object { $_.Name -eq "vcruntime140.dll" }).VersionInfo.FileVersion
# The commit, marked "dirty" if anything isn't committed.
$Commit = "nogit"
$Dirty = $false
Push-Location $Root
try {
$Commit = (git rev-parse --short HEAD 2>$null)
if ($LASTEXITCODE -ne 0 -or -not $Commit) { $Commit = "nogit" }
else { $Dirty = [bool](git status --porcelain 2>$null) }
} catch { $Commit = "nogit" }
finally { Pop-Location }
if (-not $Version) {
$Version = (Get-Date -Format "yyyyMMdd") + "-" + $Commit
if ($Dirty) { $Version += "-dirty" }
}
$OutDir = Join-Path $OutRoot $Version
if (Test-Path $OutDir) {
if (-not $Force) { throw "$OutDir already exists, pass -Force to replace it" }
Remove-Item -Recurse -Force $OutDir
}
New-Item -ItemType Directory -Force $OutDir | Out-Null
Write-Host "Release $Version -> $OutDir"
Write-Host "Compiler: $CompilerName$(if (-not $NoOptimizer) { ' /OPTIMIZER' })"
Write-Host "SQLite $SqliteVersion, libsodium $SodiumVersion"
if ($Dirty) { Write-Warning "Uncommitted changes, the version is marked dirty" }
# --- Build ------------------------------------------------------------------
$Common = @("/QUIET")
if (-not $NoOptimizer) { $Common += "/OPTIMIZER" }
$Targets = @(
@("Server\BakaShrot_Server.pb", "BakaShrot_Server.exe", @("/CONSOLE", "/THREAD")),
@("Client\BakaShrot_Client.pbi", "BakaShrot_Client.dll", @("/DLL", "/THREAD")),
@("Tools\BakaShrotPushMessage\BakaShrotPushMessage.pb", "BakaShrotPushMessage.exe", @("/CONSOLE")),
@("Tools\BakaShrotGetLatestMessage\BakaShrotGetLatestMessage.pb", "BakaShrotGetLatestMessage.exe", @("/CONSOLE")),
@("Tools\BakaShrotGetMessages\BakaShrotGetMessages.pb", "BakaShrotGetMessages.exe", @("/CONSOLE")),
@("Tools\BakaShrotGetAttachment\BakaShrotGetAttachment.pb", "BakaShrotGetAttachment.exe", @("/CONSOLE")),
@("Tools\BakaShrotQuery\BakaShrotQuery.pb", "BakaShrotQuery.exe", @("/CONSOLE")),
@("Tools\BakaShrotResolveIds\BakaShrotResolveIds.pb", "BakaShrotResolveIds.exe", @("/CONSOLE")),
@("Tools\BakaShrotList\BakaShrotList.pb", "BakaShrotList.exe", @("/CONSOLE")),
@("Tools\BakaShrotGenerateKeyPairs\BakaShrotGenerateKeyPairs.pb", "BakaShrotGenerateKeyPairs.exe", @("/CONSOLE"))
)
Push-Location $Root
try {
foreach ($Target in $Targets) {
Write-Host "Compiling $($Target[0])"
$Flags = $Target[2] + $Common
& $Compiler (Join-Path $Root $Target[0]) @Flags /OUTPUT (Join-Path $OutDir $Target[1])
if ($LASTEXITCODE -ne 0) { throw "Failed to compile $($Target[0])" }
}
}
finally {
Pop-Location
}
# The DLL's import library and exports aren't needed to use it.
Get-ChildItem $OutDir -Include "*.lib", "*.exp" -Recurse | Remove-Item -Force
Copy-Item $Sodium $OutDir
Copy-Item $SodiumLicense (Join-Path $OutDir "LICENSE-libsodium.txt")
Copy-Item (Join-Path $Root "..\LICENSE") (Join-Path $OutDir "LICENSE.txt")
foreach ($File in $Redist) { Copy-Item $File.FullName $OutDir }
Copy-Item $SqliteDll (Join-Path $OutDir "sqlite3.dll")
Copy-Item (Join-Path $Root "Client\BakaShrot_Client_Prototypes.pbi") $OutDir
Copy-Item (Join-Path $Root "Client\BakaShrot_ErrorCodes.pbi") $OutDir
New-Item -ItemType Directory -Force (Join-Path $OutDir "python") | Out-Null
foreach ($File in @("bakashrot.py", "example.py")) {
Copy-Item (Join-Path $Root "Interactors\Python\$File") (Join-Path $OutDir "python")
}
# The wheel: bakashrot.py with this release's DLLs, `pip install` and done.
$Wheel = $null
$PythonExe = Get-Command python -ErrorAction SilentlyContinue
if ($PythonExe) {
$Wheel = & $PythonExe.Source -B (Join-Path $Root "Interactors\Python\make_wheel.py") $OutDir (Join-Path $OutDir "python")
if ($LASTEXITCODE -ne 0) { throw "Failed to build the Python wheel: $Wheel" }
Write-Host "Wheel: $Wheel"
}
else {
Write-Warning "No python on the PATH, no wheel"
}
Copy-Item (Join-Path $Root "Server\Config\schema.ini") (Join-Path $OutDir "config.example.ini")
$VersionText = @"
BakaShrot $Version
Built: $(Get-Date -Format "yyyy-MM-dd HH:mm:ss")
Commit: $Commit$(if ($Dirty) { " (with uncommitted changes)" })
Compiler: $CompilerName$(if (-not $NoOptimizer) { " /OPTIMIZER" })
SQLite: $SqliteVersion
libsodium: $SodiumVersion
VC++ runtime: $RedistVersion (vcruntime140.dll, for libsodium.dll)
Needs Windows 10 or later, 64-bit. Keep the DLLs next to the exes.
Licenses: BakaShrot is CC0 (LICENSE.txt), libsodium ISC (LICENSE-libsodium.txt),
SQLite public domain, vcruntime140.dll under Visual Studio's redistribution terms.
Run the server: BakaShrot_Server.exe config.ini
Its config: config.example.ini. Keys: BakaShrotGenerateKeyPairs.exe, the
private key goes in [BakaShrot] PrivateKey, the public key in the configs that trust it, and
in its clients' client.ini as ServerPublicKey (it logs it when it starts).
Every connection is encrypted, and only reaches the server holding the
private key of the ServerPublicKey (or peer PublicKey) it was given.
It reads commands from its console (quit, restart, vacuum, help), so it
needs one: it stops right away without console input.
Topics and nodes go by name ([BakaShrot.Topics], [BakaShrot.Nodes]) or id,
each server has its own ids for the same names.
[BakaShrot.Server] Synchronous = FULL (default) flushes every push to disk
before answering it; NORMAL is faster but a power loss can lose the last
second of messages. See config.example.ini.
Tools, next to BakaShrot_Client.dll, with a client.ini:
BakaShrotPushMessage [-t <Topic>] [-a <File>] <Json|@JsonFile> [ClientIni]
BakaShrotGetLatestMessage <Topic> <Node> [ClientIni]
BakaShrotGetMessages <Topic> <Node> [--after <Id|latest>] [--limit <N>] [--follow] [--interval <Ms>] [--time] [ClientIni]
BakaShrotGetAttachment <Topic> <Node> <MessageId> <OutFile> [ClientIni]
BakaShrotResolveIds <topic|node> <NameOrId> [ClientIni]
BakaShrotList [topics|nodes|all] [ClientIni] [--json]
BakaShrotQuery <Sql|@SqlFile> [ClientIni] e.g. SELECT * FROM messages WHERE topic = 'logs'
client.ini: [BakaShrot] PrivateKey, PublicKey, Node (the node it writes
as, a name or an id), ServerHost, ServerPort, ServerPublicKey. Where its
pushes go by default is the server's DefaultTopic for it.
Python (3.8+, 64-bit): python\bakashrot.py, no dependencies, uses
BakaShrot_Client.dll (set BAKASHROT_DLL, or pass dll_path). See its
docstring, and python\example.py <ClientIni> <Topic> <Node>.
Or pip install python\bakashrot-*.whl: the same, with the DLLs in it.
Compatibility: protocol 6. Servers and clients (the DLL, the tools, the
Python client) must come from the same release: any other version
refuses the connection, there's no mixing. From an older release:
- server configs: [BakaShrot.Client.<name>] Identities = topic:node is
refused at start, write Node = node and DefaultTopic = topic (the
server's message says which); [BakaShrot] and peer sections' Topic is
ignored; [BakaShrot.Topics] can be names alone, [BakaShrot.Nodes] can
go; Synchronous = FULL is the default now (NORMAL was);
- client.ini: Topic is ignored, ServerPublicKey is required;
- apps: BakaShrot_ErrorCodes.pbi next to the prototypes, SetTopic() is
gone, and a database made before is upgraded in place at the first
start (keep a copy).
Errors: every failure has a code, BakaShrot_GetLastError() in the DLL,
error.code in Python (bakashrot.ErrorCode), the name in the tools'
messages. BakaShrot_ErrorCodes.pbi lists them, and what to do about each.
Nothing reconnects by itself. A push whose answer was lost may have been
stored: pushed again, it's stored twice (at least once delivery).
"@
Set-Content -Path (Join-Path $OutDir "VERSION.txt") -Value $VersionText -Encoding UTF8
# --- Test -------------------------------------------------------------------
function New-KeyPair {
$Lines = & (Join-Path $OutDir "BakaShrotGenerateKeyPairs.exe")
if ($LASTEXITCODE -ne 0) { throw "BakaShrotGenerateKeyPairs failed: $Lines" }
return @{
PrivateKey = $Lines[0] -replace "^PrivateKey = ", ""
PublicKey = $Lines[1] -replace "^PublicKey = ", ""
}
}
function Test-Port($Port) {
$Client = New-Object System.Net.Sockets.TcpClient
try {
$Async = $Client.BeginConnect("127.0.0.1", $Port, $null, $null)
return ($Async.AsyncWaitHandle.WaitOne(200) -and $Client.Connected)
} catch { return $false }
finally { $Client.Close() }
}
function Invoke-Tool($Name, [string[]]$Arguments) {
$Output = & (Join-Path $OutDir $Name) @Arguments 2>&1
if ($LASTEXITCODE -ne 0) { throw "$Name failed: $Output" }
return ($Output -join "`n")
}
if (-not $SkipTest) {
Write-Host "Testing the build"
# Inside the release folder: exes run from temp folders get blocked by
# the antivirus here, and the tools look for the DLL next to themselves.
$TestDir = Join-Path $OutDir "_test"
New-Item -ItemType Directory -Force $TestDir | Out-Null
$Server = $null
try {
if (Test-Port $TestPort) { throw "Port $TestPort is already in use, pass -TestPort" }
$ServerKeys = New-KeyPair
$ClientKeys = New-KeyPair
Set-Content -Path (Join-Path $TestDir "server.ini") -Encoding Ascii -Value @"
[BakaShrot]
PrivateKey = $($ServerKeys.PrivateKey)
Node = server
[BakaShrot.Topics]
releasetest = 7
[BakaShrot.Nodes]
server = 1
tester = 2
[BakaShrot.Server]
Host = 127.0.0.1
Port = $TestPort
ReplicatingTopics = releasetest
DatabasePath = $(Join-Path $TestDir "test.sqlite")
[BakaShrot.Client.test]
PublicKeys = $($ClientKeys.PublicKey)
Node = tester
DefaultTopic = releasetest
AllowRead = 1
AllowWrite = 1
AllowQuery = 1
"@
Set-Content -Path (Join-Path $TestDir "client.ini") -Encoding Ascii -Value @"
[BakaShrot]
PrivateKey = $($ClientKeys.PrivateKey)
PublicKey = $($ClientKeys.PublicKey)
Node = tester
ServerHost = 127.0.0.1
ServerPort = $TestPort
ServerPublicKey = $($ServerKeys.PublicKey)
"@
Set-Content -Path (Join-Path $TestDir "message.json") -Encoding Ascii -Value '{"release":"test","value":42}'
# Its own (hidden) console: without console input, the server stops
# right away.
$Server = Start-Process -FilePath (Join-Path $OutDir "BakaShrot_Server.exe") -ArgumentList "`"$(Join-Path $TestDir 'server.ini')`"" `
-WorkingDirectory $TestDir -WindowStyle Hidden -PassThru
$Deadline = (Get-Date).AddSeconds(15)
while (-not (Test-Port $TestPort)) {
if ($Server.HasExited) { throw "The server exited with code $($Server.ExitCode)" }
if ((Get-Date) -gt $Deadline) { throw "The server isn't listening on $TestPort" }
Start-Sleep -Milliseconds 100
}
$ClientIni = Join-Path $TestDir "client.ini"
$Pushed = Invoke-Tool "BakaShrotPushMessage.exe" @("@$(Join-Path $TestDir 'message.json')", $ClientIni)
if ($Pushed -notmatch "message #1") { throw "Unexpected push answer: $Pushed" }
$Latest = Invoke-Tool "BakaShrotGetLatestMessage.exe" @("releasetest", "tester", $ClientIni)
if ($Latest -notmatch '"release"\s*:\s*"test"' -or $Latest -notmatch '\(ids 7:2\)') { throw "Unexpected latest message: $Latest" }
$Pushed = Invoke-Tool "BakaShrotPushMessage.exe" @("@$(Join-Path $TestDir 'message.json')", $ClientIni)
if ($Pushed -notmatch "message #2") { throw "Unexpected second push answer: $Pushed" }
# message.json ends with a line break, kept in the data: one empty line after each.
$Messages = @(& (Join-Path $OutDir "BakaShrotGetMessages.exe") "releasetest" "tester" $ClientIni | Where-Object { $_ -ne "" })
if ($LASTEXITCODE -ne 0 -or $Messages.Count -ne 2 -or $Messages[0] -notmatch '^1\t\{"release"' -or $Messages[1] -notmatch '^2\t') {
throw "Unexpected messages: $($Messages -join ' | ')"
}
$Resolved = Invoke-Tool "BakaShrotResolveIds.exe" @("topic", "releasetest", $ClientIni)
if ($Resolved -notmatch "topic releasetest = 7") { throw "Unexpected resolved topic: $Resolved" }
$Sql = Join-Path $TestDir "query.sql"
Set-Content -Path $Sql -Encoding Ascii -Value "SELECT message_data ->> '$.value', is_json, topic_id FROM messages WHERE topic = 'releasetest' AND node = 'tester' AND is_json = 1"
$Queried = Invoke-Tool "BakaShrotQuery.exe" @("@$Sql", $ClientIni)
if ($Queried -notmatch '\[\["42","1","7"\],\["42","1","7"\]\]') { throw "Unexpected query result: $Queried" }
Write-Host " Pushed, read back by name, resolved and queried messages: OK"
if ($PythonExe) {
$Script = "import sys; sys.path.insert(0, sys.argv[1]); from bakashrot import Client; " +
"c = Client.from_ini(sys.argv[2], sys.argv[3]); c.connect(); " +
"p = c.get_messages('releasetest', 'tester'); print(len(p), p.messages[0].json()['value'], c.push({'py': 1})); c.close()"
$PyOut = & $PythonExe.Source -B -c $Script (Join-Path $OutDir "python") $ClientIni (Join-Path $OutDir "BakaShrot_Client.dll") 2>&1
if ($LASTEXITCODE -ne 0 -or "$PyOut" -ne "2 42 3") { throw "Unexpected Python client output: $PyOut" }
Write-Host " Read and pushed with the Python client: OK"
# The wheel, installed by pip, run from elsewhere with no DLL
# path: it must use the DLLs inside it.
$Installed = Join-Path $TestDir "wheel"
$PipOut = & $PythonExe.Source -m pip install --no-index --no-deps --disable-pip-version-check --quiet --target $Installed $Wheel 2>&1
if ($LASTEXITCODE -ne 0) { throw "pip couldn't install the wheel: $PipOut" }
$Script = "import os, sys; sys.path.insert(0, sys.argv[1]); import bakashrot; " +
"c = bakashrot.Client.from_ini(sys.argv[2]); c.connect(); " +
"inside = os.path.dirname(c._dll.path) == os.path.dirname(bakashrot.__file__); " +
"print(inside, c.latest('releasetest', 'tester').json()['py'], c.push({'wheel': 1})); c.close()"
Push-Location $TestDir
try { $PyOut = & $PythonExe.Source -B -c $Script $Installed $ClientIni 2>&1 }
finally { Pop-Location }
if ($LASTEXITCODE -ne 0 -or "$PyOut" -ne "True 1 4") { throw "Unexpected output from the wheel: $PyOut" }
Write-Host " Read and pushed with the wheel, installed by pip: OK"
}
else {
Write-Host " No python on the PATH, the Python client wasn't checked"
}
# An attachment of 3 parts and a bit, up and back.
$Attach = Join-Path $TestDir "attach.bin"
$Bytes = New-Object byte[] (3 * 1024 * 1024 + 17)
(New-Object System.Random 5).NextBytes($Bytes)
[IO.File]::WriteAllBytes($Attach, $Bytes)
$Pushed = Invoke-Tool "BakaShrotPushMessage.exe" @("-a", $Attach, "@$(Join-Path $TestDir 'message.json')", $ClientIni)
if ($Pushed -notmatch "message #(\d+), with an attachment of 3145745 bytes") { throw "Unexpected push with an attachment: $Pushed" }
$AttachedId = $Matches[1]
$Copy = Join-Path $TestDir "attach-copy.bin"
$Saved = Invoke-Tool "BakaShrotGetAttachment.exe" @("releasetest", "tester", $AttachedId, $Copy, $ClientIni)
if ($Saved -notmatch "Saved 3145745 bytes" -or (Get-FileHash $Attach).Hash -ne (Get-FileHash $Copy).Hash) { throw "Unexpected attachment read back: $Saved" }
Write-Host " Pushed and read back an attachment: OK"
}
finally {
if ($Server -and -not $Server.HasExited) {
Stop-Process -Id $Server.Id -Force
$Server.WaitForExit(5000) | Out-Null
}
Remove-Item -Recurse -Force $TestDir -ErrorAction SilentlyContinue
}
}
# --- Package ----------------------------------------------------------------
if (-not $NoZip) {
Add-Type -AssemblyName System.IO.Compression.FileSystem
$Zip = Join-Path $OutRoot "BakaShrot-$Version.zip"
if (Test-Path $Zip) { Remove-Item -Force $Zip }
[IO.Compression.ZipFile]::CreateFromDirectory($OutDir, $Zip, [IO.Compression.CompressionLevel]::Optimal, $true)
Write-Host "Zip: $Zip"
}
Write-Host ""
Write-Host "Done: $OutDir"
Get-ChildItem $OutDir | Select-Object Name, @{ n = "KB"; e = { [math]::Round($_.Length / 1KB) } } | Format-Table -AutoSize | Out-String | Write-Host
+261
View File
@@ -0,0 +1,261 @@
;{- Code Header
; ==- Basic Info -================================
; Name: BakaShrot_Server.pb
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; BakaShrot Server - CLI entry point
;
; Usage: BakaShrot_Server [ConfigFile]
; ConfigFile Path to the server's ini config, defaults to "config.ini".
; See Config/schema.ini for its layout.
;
; Loads the config, opens and sets up the database at [BakaShrot.Server]
; DatabasePath, listens on [BakaShrot.Server] Host:Port, and links to every
; [BakaShrot.Peer.<name>]. Then reads commands from the console:
; (empty), quit Stops the server.
; restart Stops every worker, reloads the config, starts again.
; vacuum Stops every worker, VACUUMs the database, starts again.
; names Lists every topic and node with its id and name.
; help Lists the commands.
; See Root.pbi for how the workers are stopped.
; Exits with 0 on success, 1 on failure.
;
; Windows: it stops once there's no more console input (no console, closed
; standard input). Elsewhere, it runs on without one (a container, a
; service) and SIGTERM or SIGINT stops it the same way as "quit".
;
; Compile as a thread-safe console program.
; ============================================================================
; ------------------------------------------------------------------------------
;- Compiler directive
CompilerIf Not #PB_Compiler_IsMainFile
CompilerError "The server's main file was included !"
CompilerEndIf
CompilerIf Not #PB_Compiler_Thread
CompilerError "The server must be compiled in thread-safe mode !"
CompilerEndIf
EnableExplicit
XIncludeFile "Root.pbi"
#BakaShrot_Server_DefaultConfigPath = "config.ini"
Procedure PrintCommands()
PrintN("Commands: quit (or an empty line), restart, vacuum, names, help")
EndProcedure
CompilerIf #PB_Compiler_OS <> #PB_OS_Windows
; Same numbers on Linux and macOS.
#BakaShrot_Server_SigInt = 2
#BakaShrot_Server_SigTerm = 15
#BakaShrot_Server_PollIn = $0001
#BakaShrot_Server_FDupFd = 0
; struct pollfd
Structure BakaShrot_Server_PollFd
Fd.l
Events.w
REvents.w
EndStructure
ImportC ""
BakaShrot_Server_Signal.i(Signal.l, *Handler) As "signal"
BakaShrot_Server_Poll.l(*Fds, Count.i, TimeoutMs.l) As "poll"
BakaShrot_Server_Read.i(Fd.l, *Buffer, Size.i) As "read"
; dup() itself can't be imported: fasm reserves the name.
BakaShrot_Server_Fcntl.l(Fd.l, Command.l, Argument.i) As "fcntl"
EndImport
; Longest command line kept, the rest of a longer one is dropped.
#BakaShrot_Server_MaxCommandSize = 256
; The signal that asked to stop, 0 until then. Only ever set by the
; handler (all a handler may safely do), read by ReadCommand().
Global BakaShrot_Server_StopSignal.l = 0
; #True once standard input is closed: commands can't come any more.
Global BakaShrot_Server_NoInput.i = #False
; Standard input, taken before OpenConsole(): it moves descriptor 0
; elsewhere and closes it (then reused by the next file opened).
Global BakaShrot_Server_InputFd.l = -1
ProcedureC BakaShrot_Server_OnSignal(Signal.l)
BakaShrot_Server_StopSignal = Signal
EndProcedure
CompilerEndIf
; Waits for the next command, Chr(4) once there's no more input.
; Windows: Input(). Elsewhere, Input() returns "" (quit) at the end of the
; input and blocks until a whole line came, so standard input is read here
; instead: never blocking for more than 250 ms without checking for a stop
; signal (it then returns "", see BakaShrot_Server_StopSignal).
Procedure.s ReadCommand()
CompilerIf #PB_Compiler_OS = #PB_OS_Windows
ProcedureReturn Input()
CompilerElse
Protected Fd.BakaShrot_Server_PollFd, Byte.a, BytesRead.i, Size.i
Protected Dim Chars.a(#BakaShrot_Server_MaxCommandSize)
Repeat
If BakaShrot_Server_StopSignal
ProcedureReturn ""
EndIf
If BakaShrot_Server_NoInput
Delay(250)
Continue
EndIf
If BakaShrot_Server_InputFd < 0
ProcedureReturn Chr(4)
EndIf
Fd\Fd = BakaShrot_Server_InputFd
Fd\Events = #BakaShrot_Server_PollIn
Fd\REvents = 0
If BakaShrot_Server_Poll(@Fd, 1, 250) <= 0
Continue
EndIf
; Readable, or closed: one byte, so nothing is read past the line.
BytesRead = BakaShrot_Server_Read(BakaShrot_Server_InputFd, @Byte, 1)
If BytesRead = 0 Or (BytesRead < 0 And Not BakaShrot_Server_StopSignal)
ProcedureReturn Chr(4)
EndIf
If BytesRead = 1
If Byte = 10
ProcedureReturn PeekS(@Chars(0), Size, #PB_UTF8 | #PB_ByteLength)
EndIf
; CR of a CRLF skipped.
If Byte <> 13 And Size < #BakaShrot_Server_MaxCommandSize
Chars(Size) = Byte
Size + 1
EndIf
EndIf
ForEver
CompilerEndIf
EndProcedure
Define Root.BakaShrot_Root
Define Command.s, ExitCode.i
CompilerIf #PB_Compiler_OS <> #PB_OS_Windows
BakaShrot_Server_InputFd = BakaShrot_Server_Fcntl(0, #BakaShrot_Server_FDupFd, 0)
CompilerEndIf
OpenConsole("BakaShrot Server")
CompilerIf #PB_Compiler_OS <> #PB_OS_Windows
BakaShrot_Server_Signal(#BakaShrot_Server_SigTerm, @BakaShrot_Server_OnSignal())
BakaShrot_Server_Signal(#BakaShrot_Server_SigInt, @BakaShrot_Server_OnSignal())
CompilerEndIf
Root\ConfigPath = #BakaShrot_Server_DefaultConfigPath
If CountProgramParameters() > 0
Root\ConfigPath = ProgramParameter(0)
EndIf
If Not BakaShrot_Root_LoadConfig(@Root)
End 1
EndIf
If Not BakaShrot_Root_OpenDatabase(@Root)
FreeConfig(Root\Config)
End 1
EndIf
If Not BakaShrot_Root_StartWorkers(@Root)
BakaShrot_Root_CloseDatabase(@Root)
FreeConfig(Root\Config)
End 1
EndIf
PrintN("Running.")
PrintCommands()
ExitCode = 0
Repeat
Command = LCase(Trim(ReadCommand()))
CompilerIf #PB_Compiler_OS <> #PB_OS_Windows
If BakaShrot_Server_StopSignal
If BakaShrot_Server_StopSignal = #BakaShrot_Server_SigTerm
PrintN("Got SIGTERM, stopping")
Else
PrintN("Got SIGINT, stopping")
EndIf
Break
EndIf
CompilerEndIf
; Once there's no more input (no console, closed standard input), every
; ReadCommand() returns Chr(4) right away. Without this, it would loop
; forever.
If FindString(Command, Chr(4))
CompilerIf #PB_Compiler_OS = #PB_OS_Windows
PrintN("No more input, stopping")
Break
CompilerElse
PrintN("No console input, running until SIGTERM or SIGINT")
BakaShrot_Server_NoInput = #True
Continue
CompilerEndIf
EndIf
Select Command
Case "", "quit"
Break
Case "restart"
If Not BakaShrot_Root_Restart(@Root)
PrintN("[Root] Restart failed, stopping")
ExitCode = 1
Break
EndIf
Case "vacuum"
If Not BakaShrot_Root_Vacuum(@Root)
PrintN("[Root] Couldn't start again after vacuuming, stopping")
ExitCode = 1
Break
EndIf
Case "names"
BakaShrot_Names_Print()
Case "help"
PrintCommands()
Default
PrintN("Unknown command '" + Command + "'")
PrintCommands()
EndSelect
ForEver
PrintN("Stopping...")
BakaShrot_Root_StopWorkers(@Root)
BakaShrot_Root_CloseDatabase(@Root)
FreeConfig(Root\Config)
End ExitCode
+8
View File
@@ -0,0 +1,8 @@
IDE Options = PureBasic 6.41 beta 2 (Windows - x64)
CursorPosition = 15
FirstLine = 23
EnableXP
DPIAware
CompileSourceDirectory
EnableCompileCount = 1
EnableBuildCount = 0
File diff suppressed because it is too large Load Diff
+8
View File
@@ -0,0 +1,8 @@
IDE Options = PureBasic 6.41 beta 2 (Windows - x64)
CursorPosition = 135
Folding = --
EnableXP
DPIAware
CompileSourceDirectory
EnableCompileCount = 1
EnableBuildCount = 0
+218
View File
@@ -0,0 +1,218 @@
; BakaShrot server config file.
; Section names are literal strings as far as PureBasic's Preferences
; library is concerned — the dots below are just part of the name.
;
; Topics and nodes: each has an id (0-65535) on this server, and can have a
; name. Topics are named in [BakaShrot.Topics]; nodes by the sections that
; define them ([BakaShrot] Node, a peer's, a client's), [BakaShrot.Nodes]
; only names the others. The server gives every name its id, and keeps it.
; Names are what's shared between servers: replication sends them, and
; each server stores the messages under its own ids for them ("logs" can be
; 1 here and 200 on a peer).
; ONLY WHAT'S NAMED ON BOTH SERVERS REPLICATES: a topic or node without a
; name, or whose name the other server doesn't have, is dropped. Unnamed
; ones still work locally, by id.
; Names: 1-64 of A-Z a-z 0-9 _ . -, not only digits, case doesn't matter.
; The server's "names" command and the BakaShrotList tool list them all.
;
; Topic, Node and ReplicatingTopics were TopicId, NodeId and
; ReplicatingTopicIds before: the old names are still read.
;
; Everywhere below, a topic or node can be written as a name or an id.
; Topic lists (and a peer's node lists): names and ids separated by ";",
; ranges of ids (100-150), wildcards like file names (sensors.*, kitchen-??:
; * any characters, ? one, they only match names), or * for every one.
; In a peer's AcceptTopics / AcceptNodes, * and wildcards also take names
; this server doesn't have: they get an id here by themselves, the highest
; free one counting down from 65535 (see them with the "names" command).
[BakaShrot]
; Config shared by every type of config.
; This node's Ed25519 private key (Base64), from BakaShrotGenerateKeyPairs.exe. It proves who
; this server is: clients seal their Hello for its public key and check
; that it signed the handshake, so they need that public key (client.ini's
; ServerPublicKey, peers' PublicKey below in THEIR own config). The server
; logs it when it starts. See Commons/Networking/Connections.pbi.
PrivateKey =
; The node this server authenticates as when it links to its peers, a name
; or an id. Its peers must register it under the same name: a client
; section with this Node and this server's public key. (A Topic left here
; from before protocol 5 is ignored.)
Node =
[BakaShrot.Topics]
; One topic name per line. This server gives each its id: the one its
; database already has for it, or the lowest free one for a new one, so the
; order doesn't matter and they keep their ids.
; "name = id" pins one instead (configs from before work as they are). Once
; a name has messages, its id can't change: the server refuses to start if
; a pin moves it, and says which id to use.
; logs
; sensors
[BakaShrot.Nodes]
; Optional. The nodes [BakaShrot] Node, the peers' and the clients' Node
; define are named already. List the others this server should know by name
; up front, like topics; peers add the ones they send as they come
; (AcceptNodes, below).
; kitchen
[BakaShrot.Retention]
; How long this server keeps each topic's messages, counted from when they
; were pushed (to whichever server they were first pushed to). Past that,
; they may be deleted: checked every RetentionInterval seconds. Each server
; has its own: a peer keeps its copies as long as its own config says.
; One line per topic: name or id = age, a pattern (sensors.*), or * for
; every topic not listed. A topic takes its id's line, else its name's,
; else the first pattern matching it, else *'s.
; Ages: numbers with a unit, s m h d w, added up (1d12h), or forever.
; Without any line, everything is kept forever.
; Deleting doesn't shrink the file, SQLite reuses the space for new
; messages; the "vacuum" console command gives it back to the disk.
; logs = 30d
; sensors.* = 12h
; * = 365d
[BakaShrot.Server]
; IPV4 that the server will be bound to.
Host =
; Used port.
Port =
; The topics replicated with every peer that doesn't say otherwise
; (SendTopics, AcceptTopics below).
; Format: logs;0;100-150;... or * for every topic.
ReplicatingTopics =
; Amount of threads used for networking-related tasks.
NetThreadPoolSize = 4
; SQLite database file holding the messages.
DatabasePath = ./test.sqlite
; Seconds to wait before connecting to a peer again, after failing to
; connect or losing the connection.
PeerRetryDelay = 10
; Seconds between two check-ins with a linked peer, where it's sent the
; messages it's missing.
PeerSyncInterval = 5
; Most messages sent to a peer per packet when it's missing some, 1-10000.
; A batch is also cut short at about 64 KB, a bigger message goes alone.
PeerBatchSize = 100
; Seconds between two passes deleting the messages past their topic's age
; ([BakaShrot.Retention] above), and the attachments' leftovers.
RetentionInterval = 60
; Biggest attachment this server takes (one per message, see
; Design/Attachments.md): pushed to it, or replicated (a bigger one's message
; is kept, its attachment isn't). Bytes, or K M G T (1024-based). 0: none.
MaxAttachmentSize = 1G
; Seconds a client may take to upload an attachment and push its message,
; after which the upload is deleted.
UploadTimeout = 3600
; How hard the database makes sure a push is on disk before answering it.
; FULL (default) every commit is flushed to disk: a message the server
; acknowledged survives a power loss or an OS crash.
; NORMAL flushed about once a second only (at the checkpoints): faster
; (twice the pushes under full load, measured), but a power loss
; or an OS crash loses the last second or so of acknowledged
; messages, and their ids are handed out again, which peers that
; already got them can't tell (Design/ReplicationIssues.md #1).
; A crash of the server alone loses nothing either way.
; The cost of FULL is the disk's flush time, once per group of pushes: well
; under a millisecond on a server SSD, ~10 ms on a hard disk, which then
; caps one client pushing one message at a time to ~100/s.
; See Design/StorageConcurrency.md for the numbers.
Synchronous = FULL
; One [BakaShrot.Peer.<name>] section per peer this node talks to.
; <name> is only a key for this file; it is never sent on the wire.
[BakaShrot.Peer.example]
; Remote address of the peer. Can be a domain name, IPV4 or IPV6.
Host =
; Remote port of the peer (0-65535).
Port =
; The server links to every peer on start, and retries every PeerRetryDelay.
; The peer must register this server in one of its [BakaShrot.Client.<name>].
; The link only goes through if the peer proves it holds the private key
; of PublicKey below, and it's encrypted.
; The peer's node, a name or an id: the one in its own [BakaShrot] Node.
; It authenticates as it when it links to here.
Node =
; The topics sent to this peer (if it takes them), and the topics taken
; from it. Both default to ReplicatingTopics.
; SendTopics = logs;sensors.*
; AcceptTopics = logs;sensors.*
; The nodes whose messages are sent to this peer (default: every one), and
; the nodes whose messages are taken from it (default: every one, the names
; this server doesn't have yet are added as they come). AcceptNodes =
; kitchen-*;garage only takes those, named here or not.
; SendNodes = *
; AcceptNodes = kitchen-*;garage
; This peer's Ed25519 public key (Base64), required: the link's Hello is
; sealed for it, and the peer must sign the handshake with its private key.
; It's also the key the peer authenticates with when it links to here.
PublicKey =
; One [BakaShrot.Client.<name>] section per client allowed to connect.
; <name> is only a key for this file; it is never sent on the wire.
[BakaShrot.Client.example]
; Ed25519 public keys (Base64) this client is allowed to authenticate with.
; Format: Key;Key;...
PublicKeys =
; The node this client writes as, a name or an id, required. Every message
; it pushes is stored under it, so the server decides which node each key
; writes as, and no client can push as another's node (or as a peer's).
; Its client.ini's Node must say the same. A key that writes as several
; nodes is listed in a section per node.
; ONE SERVER PER NODE: give a node a client section on the one server it
; pushes to, the others get its messages by replication. Two servers taking
; pushes for the same node end up with different messages under the same
; ids, which nothing detects (Design/ReplicationIssues.md #1). To read from
; another server, give the client another node there (or no write access:
; AllowWrite = 0).
Node =
; Where its pushes go when they don't name a topic, a name or an id.
; Optional: without it, every push must name its topic. Only a default, it
; may push to any topic in PushTopics.
; DefaultTopic = logs
; (Identities, the Topic:Node pairs before protocol 5, isn't read any more:
; the server refuses to start with it, saying what to write instead.)
; The topics it may push to (always under its own node), and the topics it
; may read the latest messages of. Both default to its DefaultTopic,
; nothing without one; empty allows none.
; PushTopics = logs;sensors
; ReadTopics = *
; What this client may do once authenticated, 1 to allow, 0 to deny.
; Read: GetLatestMessage. Write: PushMessage.
; Query: raw read-only SQL, which can read every topic's data, whatever
; ReadTopics says. The "messages" view has the names:
; SELECT * FROM messages WHERE topic = 'logs' AND node = 'kitchen'
AllowRead = 1
AllowWrite = 1
AllowQuery = 0
+14
View File
@@ -0,0 +1,14 @@
[BakaShrot]
PrivateKey =
TopicId = 0
NodeId = 0
[BakaShrot.Server]
Host =
Port = 0
ReplicatingTopicIds =
[BakaShrot.Peer.example]
Host =
Port = 0
TopicId = 0
NodeId = 0
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,7 @@
IDE Options = PureBasic 6.41 beta 2 (Windows - x64)
EnableThread
EnableXP
DPIAware
CompileSourceDirectory
EnableCompileCount = 0
EnableBuildCount = 0
+733
View File
@@ -0,0 +1,733 @@
;{- Code Header
; ==- Basic Info -================================
; Name: Peers.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; BakaShrot Server Peers
;
; Links this server to the other servers in its config's
; [BakaShrot.Peer.<name>] sections, one thread per peer. Each thread:
; 1. Connects to the peer and authenticates with this server's own identity
; ([BakaShrot] PrivateKey/TopicId/NodeId), like a client would. The peer
; must have it registered in one of its [BakaShrot.Client.<name>].
; 2. Stays connected until the link drops.
; 3. Waits [BakaShrot.Server] PeerRetryDelay seconds, then starts over.
; Same after a failed attempt.
;
; Once linked, it checks in with the peer every [BakaShrot.Server]
; PeerSyncInterval seconds, starting right away:
; 1. Asks the peer for its sync state: the topics it takes from this
; server, and the highest message id it has for each of their
; topic/node ids, in its own ids, with their names.
; 2. Compares it with this server's own (GetSyncState() in Storage.pbi),
; matching topics and nodes by name: each server has its own ids, see
; Server/Storage/Names.pbi. Only what's named on both sides replicates:
; an unnamed one, or one whose name the peer doesn't list, is dropped
; (BakaShrot_Names_NoteDropped()).
; 3. For every topic/node the peer takes, this server sends it
; (the peer section's SendTopics), and the peer is behind on, sends it
; the missing messages in order, in batches of up to
; [BakaShrot.Server] PeerBatchSize messages, about 64 KB at most (a
; bigger message goes alone, see ReplicateMessagesPacket.pbi), each
; batch stored in one transaction and answered before the next. The
; batches carry the names, the peer stores them under its own ids.
; A message's attachment only has its size and SHA-256 in the batch.
; 4. Once the messages are caught up, asks the peer which attachments it's
; missing (MissingAttachmentsRequest) and sends those it has, a part
; (1 MB) per request, from where the peer stopped (Design/Attachments.md).
; The peer does the same over its own link to this server, which covers the
; other direction. Any packet from the peer outside of a check-in drops the
; link as unexpected.
; Known issues, like two servers drifting apart: Design/ReplicationIssues.md.
;
; Each link thread opens its own database connection when it starts, and
; closes it when it ends. See the top of Storage/Storage.pbi.
;
; The peer proves itself in the handshake: the Hello is sealed for the peer
; section's PublicKey and the peer must sign the handshake with the matching
; private key, so a link only reaches the real peer, and is encrypted
; (Commons/Networking/Connections.pbi).
;
; Logs with PrintN(), so the program must have a console open.
; Must be compiled with the thread-safe option enabled.
; ============================================================================
CompilerIf Not #PB_Compiler_Thread
CompilerError "Peers.pbi needs the thread-safe option (Compiler Options > Create threadsafe executable)."
CompilerEndIf
XIncludeFile "../../Commons/Networking/Outbound.pbi"
XIncludeFile "../Config/Config.pbi"
XIncludeFile "../Storage/Storage.pbi"
XIncludeFile "../Storage/Names.pbi"
Structure BakaShrot_PeerLink
*Links
; [BakaShrot.Peer.<name>]
Name.s
Host.s
Port.i
; The peer section's PublicKey: who the peer must prove to be.
ServerPublicKey.a[#BakaShrot_Ed25519_PublicKeySize]
ThreadId.i
; Only used by the link's thread.
Outbound.BakaShrot_Outbound
DbId.i
; The peer section's SendTopics and SendNodes, copied for the link's thread.
SendTopics.BakaShrot_NameSet
SendNodes.BakaShrot_NameSet
EndStructure
Structure BakaShrot_PeerLinks
; Set by BakaShrot_PeerLinks_Stop(), makes every link's thread return.
StopRequested.i
RetryDelayMs.i
SyncIntervalMs.i
; Most messages sent per ReplicateMessages packet.
BatchSize.i
; Every link's thread opens its own connection to it.
DatabasePath.s
; This server's identity, read by every link's thread.
Identity.BakaShrot_OutboundIdentity
PrivateKey.a[#BakaShrot_Ed25519_PrivateKeySize]
PublicKey.a[#BakaShrot_Ed25519_PublicKeySize]
List Links.BakaShrot_PeerLink()
EndStructure
; Waits the retry delay, returns early if stopping.
Procedure BakaShrot_PeerLink_WaitRetry(*Link.BakaShrot_PeerLink)
Protected *Links.BakaShrot_PeerLinks = *Link\Links
Protected StartTime.i
StartTime = ElapsedMilliseconds()
While Not *Links\StopRequested And ElapsedMilliseconds() - StartTime < *Links\RetryDelayMs
Delay(100)
Wend
EndProcedure
; Sends a request to the peer and waits for its answer.
; Returns the answer (free it with FreeMemory) with its size in *OutSize\i,
; or 0 if the link failed.
Procedure.i BakaShrot_PeerLink_Request(*Link.BakaShrot_PeerLink, *Request, RequestSize.i, *OutSize.Integer)
If Not BakaShrot_Outbound_Send(@*Link\Outbound, *Request, RequestSize)
ProcedureReturn 0
EndIf
ProcedureReturn BakaShrot_Outbound_WaitPacket(@*Link\Outbound, *OutSize, #BakaShrot_Outbound_Timeout)
EndProcedure
; Logs a RequestRefused answer from the peer.
; Returns #False if it's malformed, the link must then be dropped.
Procedure.i BakaShrot_PeerLink_LogRefusal(*Link.BakaShrot_PeerLink, *Answer, AnswerSize.i)
Protected *View.MsgPackData, *Refused.BakaShrot_RequestRefused
*Refused = 0
*View = MsgPackWrapMsgBuffer(*Answer, AnswerSize)
If *View
*Refused = BakaShrot_RequestRefusedPacket_Decode(*View)
MsgPackFree(*View, #False)
EndIf
If Not *Refused
ProcedureReturn #False
EndIf
PrintN("[Peer] '" + *Link\Name + "' refused (" + BakaShrot_ErrorName(*Refused\Code) + "): " + *Refused\Reason)
FreeStructure(*Refused)
ProcedureReturn #True
EndProcedure
; Sends the peer the attachment it's missing, *Missing, from the part it
; asked for on, if this server has all of it and sends that topic/node to it.
; Returns 1 once the peer has it, 0 if it's skipped (not here, not sent to
; that peer, refused: logged), -1 if the link must be dropped.
Procedure.i BakaShrot_PeerLink_SendAttachment(*Link.BakaShrot_PeerLink, *Missing.BakaShrot_MissingAttachment)
Protected *Links.BakaShrot_PeerLinks = *Link\Links
Protected Attachment.BakaShrot_StorageAttachment, Chunk.BakaShrot_ReplicateAttachmentChunk
Protected *Stored.BakaShrot_ChunkStored
Protected TopicId.i, NodeId.i, Index.q, Count.q, DataSize.Integer, Complete.i
Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer, *View.MsgPackData, IsRefusal.i
TopicId = BakaShrot_Names_TopicByName(*Missing\Topic)
NodeId = BakaShrot_Names_NodeByName(*Missing\Node)
If TopicId < 0 Or NodeId < 0
ProcedureReturn 0
EndIf
If Not NameSetHas(@*Link\SendTopics, TopicId, *Missing\Topic) Or Not NameSetHas(@*Link\SendNodes, NodeId, *Missing\Node)
ProcedureReturn 0
EndIf
; Not here either (yet, or not kept): another server may have it.
If Not GetStorageAttachment(*Link\DbId, TopicId, NodeId, *Missing\MessageId, @Attachment) Or Attachment\State <> #BakaShrot_Attachment_Ready
ProcedureReturn 0
EndIf
Count = BakaShrot_AttachmentChunkCount(Attachment\Size)
Chunk\Topic = *Missing\Topic
Chunk\Node = *Missing\Node
Chunk\MessageId = *Missing\MessageId
For Index = *Missing\NextChunk To Count - 1
If *Links\StopRequested
ProcedureReturn -1
EndIf
Chunk\ChunkIndex = Index
Chunk\Data = ReadStorageBlobChunk(*Link\DbId, Attachment\BlobId, Index, @DataSize)
If Not Chunk\Data
PrintN("[Peer] Can't read part " + Str(Index) + " of the attachment of " + *Missing\Topic + ":" + *Missing\Node + "#" + Str(*Missing\MessageId) + " for '" + *Link\Name + "'")
ProcedureReturn 0
EndIf
Chunk\DataSize = DataSize\i
*Packet = BakaShrot_ReplicateAttachmentChunkPacket_Encode(@Chunk, @PacketSize)
FreeMemory(Chunk\Data)
Chunk\Data = 0
If Not *Packet
ProcedureReturn -1
EndIf
*Answer = BakaShrot_PeerLink_Request(*Link, *Packet, PacketSize\i, @AnswerSize)
FreeMemory(*Packet)
If Not *Answer
ProcedureReturn -1
EndIf
If BakaShrot_GetPacketType(*Answer, AnswerSize\i) = #BakaShrot_PacketType_RequestRefused
IsRefusal = BakaShrot_PeerLink_LogRefusal(*Link, *Answer, AnswerSize\i)
FreeMemory(*Answer)
If Not IsRefusal
ProcedureReturn -1
EndIf
ProcedureReturn 0
EndIf
*Stored = 0
*View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i)
If *View
*Stored = BakaShrot_ChunkStoredPacket_Decode(*View)
MsgPackFree(*View, #False)
EndIf
FreeMemory(*Answer)
If Not *Stored
PrintN("[Peer] '" + *Link\Name + "' sent an invalid answer to an attachment's part")
ProcedureReturn -1
EndIf
Complete = *Stored\Complete
FreeStructure(*Stored)
If Complete
ProcedureReturn 1
EndIf
Next
; All sent, and the peer didn't say it's complete: it'll ask again.
ProcedureReturn 0
EndProcedure
; Once the messages are caught up: asks the peer which attachments it's
; missing, and sends those this server has, one after the other.
; Returns #False if the link must be dropped.
Procedure.i BakaShrot_PeerLink_SendAttachments(*Link.BakaShrot_PeerLink)
Protected Request.BakaShrot_MissingAttachmentsRequest, *Missing.BakaShrot_MissingAttachments
Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer, *View.MsgPackData, IsRefusal.i
Protected Result.i, StartTime.i, Attachment.BakaShrot_StorageAttachment, Key.s
*Packet = BakaShrot_MissingAttachmentsRequestPacket_Encode(@Request, @PacketSize)
If Not *Packet
ProcedureReturn #False
EndIf
*Answer = BakaShrot_PeerLink_Request(*Link, *Packet, PacketSize\i, @AnswerSize)
FreeMemory(*Packet)
If Not *Answer
PrintN("[Peer] '" + *Link\Name + "' didn't answer which attachments it's missing")
ProcedureReturn #False
EndIf
If BakaShrot_GetPacketType(*Answer, AnswerSize\i) = #BakaShrot_PacketType_RequestRefused
IsRefusal = BakaShrot_PeerLink_LogRefusal(*Link, *Answer, AnswerSize\i)
FreeMemory(*Answer)
ProcedureReturn IsRefusal
EndIf
*Missing = 0
*View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i)
If *View
*Missing = BakaShrot_MissingAttachmentsPacket_Decode(*View)
MsgPackFree(*View, #False)
EndIf
FreeMemory(*Answer)
If Not *Missing
PrintN("[Peer] '" + *Link\Name + "' sent an invalid list of missing attachments")
ProcedureReturn #False
EndIf
ForEach *Missing\Attachments()
StartTime = ElapsedMilliseconds()
Result = BakaShrot_PeerLink_SendAttachment(*Link, @*Missing\Attachments())
If Result < 0
FreeStructure(*Missing)
ProcedureReturn #False
EndIf
If Result > 0
Key = *Missing\Attachments()\Topic + ":" + *Missing\Attachments()\Node + "#" + Str(*Missing\Attachments()\MessageId)
PrintN("[Peer] Sent the attachment of " + Key + " to '" + *Link\Name + "' in " + Str(ElapsedMilliseconds() - StartTime) + " ms, from part " + Str(*Missing\Attachments()\NextChunk))
EndIf
Next
FreeStructure(*Missing)
ProcedureReturn #True
EndProcedure
; Sends a batch of messages the peer is missing and checks its answer.
; Returns 1 once stored, 0 if the peer refused it (logged), or -1 if the
; link must be dropped.
Procedure.i BakaShrot_PeerLink_SendBatch(*Link.BakaShrot_PeerLink, *Batch.BakaShrot_ReplicateMessages)
Protected *Pushed.BakaShrot_MessagePushed
Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer
Protected *View.MsgPackData, IsRefusal.i, IsAcknowledged.i, LastMessageId.q
LastElement(*Batch\Messages())
LastMessageId = *Batch\Messages()\MessageId
*Packet = BakaShrot_ReplicateMessagesPacket_Encode(*Batch, @PacketSize)
If Not *Packet
ProcedureReturn -1
EndIf
*Answer = BakaShrot_PeerLink_Request(*Link, *Packet, PacketSize\i, @AnswerSize)
FreeMemory(*Packet)
If Not *Answer
ProcedureReturn -1
EndIf
If BakaShrot_GetPacketType(*Answer, AnswerSize\i) = #BakaShrot_PacketType_RequestRefused
IsRefusal = BakaShrot_PeerLink_LogRefusal(*Link, *Answer, AnswerSize\i)
FreeMemory(*Answer)
If Not IsRefusal
ProcedureReturn -1
EndIf
ProcedureReturn 0
EndIf
*Pushed = 0
*View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i)
If *View
*Pushed = BakaShrot_MessagePushedPacket_Decode(*View)
MsgPackFree(*View, #False)
EndIf
FreeMemory(*Answer)
If Not *Pushed
ProcedureReturn -1
EndIf
; An acknowledgement for anything but the batch's last message is out of order.
IsAcknowledged = Bool(*Pushed\MessageId = LastMessageId)
FreeStructure(*Pushed)
If Not IsAcknowledged
ProcedureReturn -1
EndIf
ProcedureReturn 1
EndProcedure
; Sends every message of a topic/node id above AfterMessageId, in order, in
; batches of up to [BakaShrot.Server] PeerBatchSize messages, each one cut
; short at about #BakaShrot_ReplicateBatchBytes (a bigger message alone). TopicRef and NodeRef are what they
; go by on the wire: their names, or their ids in digits.
; Stops at the first refusal, or if the server is stopping.
; Returns how many were stored, or -1 if the link must be dropped.
Procedure.i BakaShrot_PeerLink_SendMissing(*Link.BakaShrot_PeerLink, TopicId.i, NodeId.i, TopicRef.s, NodeRef.s, AfterMessageId.q)
Protected *Links.BakaShrot_PeerLinks = *Link\Links
Protected NewList Messages.BakaShrot_Message()
Protected Batch.BakaShrot_ReplicateMessages
Protected SentCount.i, Result.i, BatchSize.i, MessageSize.i
Batch\Topic = TopicRef
Batch\Node = NodeRef
Repeat
If *Links\StopRequested
ProcedureReturn SentCount
EndIf
If Not GetMessagesAfter(*Link\DbId, TopicId, NodeId, AfterMessageId, *Links\BatchSize, #BakaShrot_ReplicateBatchBytes, Messages())
PrintN("[Peer] Failed to read the messages to send to '" + *Link\Name + "': " + DatabaseError())
ProcedureReturn SentCount
EndIf
If ListSize(Messages()) = 0
ProcedureReturn SentCount
EndIf
; As many as fit in #BakaShrot_ReplicateBatchBytes, the rest goes in the
; next batch. A bigger message goes alone, if it fits in a packet.
ClearList(Batch\Messages())
BatchSize = #BakaShrot_ReplicateBatchOverhead
ForEach Messages()
MessageSize = #BakaShrot_ReplicateMessageOverhead + StringByteLength(Messages()\JsonData, #PB_UTF8)
If ListSize(Batch\Messages()) > 0 And BatchSize + MessageSize > #BakaShrot_ReplicateBatchBytes
Break
EndIf
If BatchSize + MessageSize > #BakaShrot_MaxPacketSize
Break
EndIf
BatchSize + MessageSize
AddElement(Batch\Messages())
Batch\Messages()\MessageId = Messages()\MessageId
; As stored: when it was pushed to its origin, whichever server that was.
Batch\Messages()\PushedAt = Messages()\PushedAt
Batch\Messages()\JsonData = Messages()\JsonData
; Its attachment's size and SHA-256 only: the data goes once the
; messages are caught up (BakaShrot_PeerLink_SendAttachments()).
Batch\Messages()\AttachmentSize = Messages()\AttachmentSize
CopyMemory(@Messages()\AttachmentSha256[0], @Batch\Messages()\AttachmentSha256[0], #BakaShrot_Sha256Size)
Next
If ListSize(Batch\Messages()) = 0
FirstElement(Messages())
PrintN("[Peer] Message " + TopicRef + ":" + NodeRef + "#" + Str(Messages()\MessageId) + " is too big to replicate to '" + *Link\Name + "', skipping the rest of this pair")
ProcedureReturn SentCount
EndIf
Result = BakaShrot_PeerLink_SendBatch(*Link, @Batch)
If Result = -1
ProcedureReturn -1
EndIf
If Result = 0
ProcedureReturn SentCount
EndIf
SentCount + ListSize(Batch\Messages())
LastElement(Batch\Messages())
AfterMessageId = Batch\Messages()\MessageId
ForEver
EndProcedure
; #True if Name matches one of Patterns() (Commons/Networking/Names.pbi).
Procedure.i BakaShrot_MatchesAny(List Patterns.s(), Name.s)
ForEach Patterns()
If BakaShrot_GlobMatch(Patterns(), Name)
ProcedureReturn #True
EndIf
Next
ProcedureReturn #False
EndProcedure
; Asks the peer where it's at, and sends it the messages it's missing.
; Returns #False if the link must be dropped.
Procedure.i BakaShrot_PeerLink_CheckIn(*Link.BakaShrot_PeerLink)
Protected *Links.BakaShrot_PeerLinks = *Link\Links
Protected Request.BakaShrot_SyncStateRequest
Protected *State.BakaShrot_SyncState
Protected NewList LocalPairs.BakaShrot_SyncPair()
Protected NewMap RemoteTopics.i(), NewMap RemoteNodes.i()
Protected NewList RemoteTopicPatterns.s(), NewList RemoteNodePatterns.s()
Protected NewMap RemoteMessageIds.q()
Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer
Protected *View.MsgPackData, IsRefusal.i, Key.s, RemoteMessageId.q, SentCount.i, StartTime.i
Protected TopicRef.s, NodeRef.s, RemoteTopicId.i, RemoteNodeId.i
; 1. The peer's state
*Packet = BakaShrot_SyncStateRequestPacket_Encode(@Request, @PacketSize)
If Not *Packet
ProcedureReturn #False
EndIf
*Answer = BakaShrot_PeerLink_Request(*Link, *Packet, PacketSize\i, @AnswerSize)
FreeMemory(*Packet)
If Not *Answer
PrintN("[Peer] '" + *Link\Name + "' didn't answer the check-in")
ProcedureReturn #False
EndIf
If BakaShrot_GetPacketType(*Answer, AnswerSize\i) = #BakaShrot_PacketType_RequestRefused
IsRefusal = BakaShrot_PeerLink_LogRefusal(*Link, *Answer, AnswerSize\i)
FreeMemory(*Answer)
ProcedureReturn IsRefusal
EndIf
*State = 0
*View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i)
If *View
*State = BakaShrot_SyncStatePacket_Decode(*View)
MsgPackFree(*View, #False)
EndIf
FreeMemory(*Answer)
If Not *State
PrintN("[Peer] '" + *Link\Name + "' sent an invalid sync state")
ProcedureReturn #False
EndIf
; The peer's ids, by LCase(name): every name it knows.
ForEach *State\Topics()
RemoteTopics(LCase(*State\Topics()\Name)) = *State\Topics()\Id
Next
ForEach *State\Nodes()
RemoteNodes(LCase(*State\Nodes()\Name)) = *State\Nodes()\Id
Next
; And what it takes without having it yet.
CopyList(*State\TopicPatterns(), RemoteTopicPatterns())
CopyList(*State\NodePatterns(), RemoteNodePatterns())
ForEach *State\Pairs()
RemoteMessageIds(Str(*State\Pairs()\TopicId) + ":" + Str(*State\Pairs()\NodeId)) = *State\Pairs()\MessageId
Next
FreeStructure(*State)
; 2. This server's state
If Not GetSyncState(*Link\DbId, LocalPairs())
PrintN("[Peer] Failed to read the sync state for '" + *Link\Name + "': " + DatabaseError())
ProcedureReturn #True
EndIf
; 3. The delta, matching this server's topics and nodes to the peer's by
; name. Anything not named on both sides is dropped, unless a wildcard
; of the peer takes it.
ForEach LocalPairs()
TopicRef = BakaShrot_Names_TopicName(LocalPairs()\TopicId)
NodeRef = BakaShrot_Names_NodeName(LocalPairs()\NodeId)
If Not NameSetHas(@*Link\SendTopics, LocalPairs()\TopicId, TopicRef) Or Not NameSetHas(@*Link\SendNodes, LocalPairs()\NodeId, NodeRef)
Continue
EndIf
If TopicRef = ""
BakaShrot_Names_NoteDropped(*Link\Name, "topic", Str(LocalPairs()\TopicId), "unnamed here")
Continue
EndIf
If NodeRef = ""
BakaShrot_Names_NoteDropped(*Link\Name, "node", Str(LocalPairs()\NodeId), "unnamed here")
Continue
EndIf
; -1: the peer doesn't have it yet, but a wildcard of its takes it.
RemoteTopicId = -1
If FindMapElement(RemoteTopics(), LCase(TopicRef))
RemoteTopicId = RemoteTopics()
ElseIf Not BakaShrot_MatchesAny(RemoteTopicPatterns(), TopicRef)
BakaShrot_Names_NoteDropped(*Link\Name, "topic", TopicRef, "not taken by the peer")
Continue
EndIf
RemoteNodeId = -1
If FindMapElement(RemoteNodes(), LCase(NodeRef))
RemoteNodeId = RemoteNodes()
ElseIf Not BakaShrot_MatchesAny(RemoteNodePatterns(), NodeRef)
BakaShrot_Names_NoteDropped(*Link\Name, "node", NodeRef, "not taken by the peer")
Continue
EndIf
RemoteMessageId = 0
If RemoteTopicId >= 0 And RemoteNodeId >= 0 And FindMapElement(RemoteMessageIds(), Str(RemoteTopicId) + ":" + Str(RemoteNodeId))
RemoteMessageId = RemoteMessageIds()
EndIf
Key = TopicRef + ":" + NodeRef
If LocalPairs()\MessageId > RemoteMessageId
StartTime = ElapsedMilliseconds()
SentCount = BakaShrot_PeerLink_SendMissing(*Link, LocalPairs()\TopicId, LocalPairs()\NodeId, TopicRef, NodeRef, RemoteMessageId)
If SentCount < 0
ProcedureReturn #False
EndIf
If SentCount > 0
PrintN("[Peer] Sent " + Str(SentCount) + " messages of " + Key + " to '" + *Link\Name + "' in " + Str(ElapsedMilliseconds() - StartTime) + " ms, it had up to #" + Str(RemoteMessageId))
EndIf
EndIf
Next
; 4. Then the attachments: only for messages the peer has now.
ProcedureReturn BakaShrot_PeerLink_SendAttachments(*Link)
EndProcedure
; Keeps a linked peer's connection, checking in every sync interval, until it
; drops, a check-in fails, the peer sends something unasked, or the server is
; stopping. The connection is closed when it returns.
Procedure BakaShrot_PeerLink_StayLinked(*Link.BakaShrot_PeerLink)
Protected *Links.BakaShrot_PeerLinks = *Link\Links
Protected LastCheckIn.i
; Checks in right away.
LastCheckIn = ElapsedMilliseconds() - *Links\SyncIntervalMs
While Not *Links\StopRequested
If ElapsedMilliseconds() - LastCheckIn >= *Links\SyncIntervalMs
If Not BakaShrot_PeerLink_CheckIn(*Link)
PrintN("[Peer] Dropping the link to '" + *Link\Name + "', the check-in failed")
BakaShrot_Outbound_Close(@*Link\Outbound, #BakaShrot_ConnectionStatus_Aborted)
ProcedureReturn
EndIf
LastCheckIn = ElapsedMilliseconds()
EndIf
Select NetworkClientEvent(*Link\Outbound\ConnectionId)
Case #PB_NetworkEvent_Data
PrintN("[Peer] '" + *Link\Name + "' sent a packet it wasn't asked for")
BakaShrot_Outbound_Close(@*Link\Outbound, #BakaShrot_ConnectionStatus_Aborted)
ProcedureReturn
Case #PB_NetworkEvent_Disconnect
PrintN("[Peer] Lost the link to '" + *Link\Name + "'")
BakaShrot_Outbound_Close(@*Link\Outbound, #BakaShrot_ConnectionStatus_Disconnected)
ProcedureReturn
Default
Delay(50)
EndSelect
Wend
BakaShrot_Outbound_Close(@*Link\Outbound, #BakaShrot_ConnectionStatus_Disconnected)
EndProcedure
Procedure BakaShrot_PeerLink_Thread(*Link.BakaShrot_PeerLink)
Protected *Links.BakaShrot_PeerLinks = *Link\Links
Protected Target.s = "'" + *Link\Name + "' (" + *Link\Host + ":" + Str(*Link\Port) + ")"
*Link\DbId = OpenStorageDatabase(*Links\DatabasePath)
If Not *Link\DbId
PrintN("[Peer] Failed to open the database for " + Target + ", not linking to it: " + DatabaseError())
ProcedureReturn
EndIf
; Waits for the peer's answers stop early when the server is stopping.
*Link\Outbound\StopRequested = @*Links\StopRequested
While Not *Links\StopRequested
If BakaShrot_Outbound_Connect(@*Link\Outbound, *Link\Host, *Link\Port, @*Links\Identity, @*Link\ServerPublicKey[0])
PrintN("[Peer] Linked to " + Target)
BakaShrot_PeerLink_StayLinked(*Link)
Else
PrintN("[Peer] Failed to link to " + Target + ", unreachable, or the handshake failed (is its PublicKey right?)")
EndIf
If Not *Links\StopRequested
PrintN("[Peer] Retrying " + Target + " in " + Str(*Links\RetryDelayMs / 1000) + "s")
BakaShrot_PeerLink_WaitRetry(*Link)
EndIf
Wend
CloseDatabase(*Link\DbId)
*Link\DbId = 0
EndProcedure
; Stops every link's thread, closes their connections and frees *Links.
; Once it returns, no link thread is left, so none holds a database
; connection either.
; Waits for a peer's answer stop within a few ms, but a thread opening a
; connection is blocked in OpenNetworkConnection() until it succeeds or
; fails.
Procedure BakaShrot_PeerLinks_Stop(*Links.BakaShrot_PeerLinks)
*Links\StopRequested = #True
ForEach *Links\Links()
If *Links\Links()\ThreadId
WaitThread(*Links\Links()\ThreadId)
EndIf
Next
; Don't leave the private key lying around in freed memory.
FillMemory(@*Links\PrivateKey[0], #BakaShrot_Ed25519_PrivateKeySize, 0)
FreeStructure(*Links)
EndProcedure
; Starts a link to every [BakaShrot.Peer.<name>] in *Config, replicating
; the messages in its [BakaShrot.Server] DatabasePath. *Config must outlive
; the links.
; Returns 0 if *Config's PrivateKey is invalid or a thread couldn't start,
; stop the returned links with BakaShrot_PeerLinks_Stop().
Procedure.i BakaShrot_PeerLinks_Start(*Config.BakaShrot_CoreConfig)
Protected *Links.BakaShrot_PeerLinks
If Not InitCryptography()
ProcedureReturn 0
EndIf
*Links = AllocateStructure(BakaShrot_PeerLinks)
If Not *Links
ProcedureReturn 0
EndIf
; Identity
If Not DecodeKeyFromString(*Config\PrivateKey, @*Links\PrivateKey[0], #BakaShrot_Ed25519_PrivateKeySize)
FreeStructure(*Links)
ProcedureReturn 0
EndIf
GetPublicKeyFromPrivateKey(@*Links\PrivateKey[0], @*Links\PublicKey[0])
; By name: the peer has its own ids for them.
*Links\Identity\Node = BakaShrot_Names_NodeRef(*Config\NodeId)
*Links\Identity\PublicKey = EncodeKeyToString(@*Links\PublicKey[0], #BakaShrot_Ed25519_PublicKeySize)
*Links\Identity\PrivateKey = @*Links\PrivateKey[0]
*Links\DatabasePath = *Config\Server\DatabasePath
*Links\RetryDelayMs = *Config\Server\PeerRetryDelay * 1000
If *Links\RetryDelayMs < 1000
*Links\RetryDelayMs = 1000
EndIf
*Links\SyncIntervalMs = *Config\Server\PeerSyncInterval * 1000
If *Links\SyncIntervalMs < 1000
*Links\SyncIntervalMs = 1000
EndIf
*Links\BatchSize = *Config\Server\PeerBatchSize
If *Links\BatchSize < 1
*Links\BatchSize = 1
EndIf
If *Links\BatchSize > #BakaShrot_MaxReplicateBatch
*Links\BatchSize = #BakaShrot_MaxReplicateBatch
EndIf
; Links
ForEach *Config\Peers()
AddElement(*Links\Links())
*Links\Links()\Links = *Links
*Links\Links()\Name = MapKey(*Config\Peers())
*Links\Links()\Host = *Config\Peers()\Host
*Links\Links()\Port = *Config\Peers()\Port
If Not DecodeKeyFromString(*Config\Peers()\PublicKey, @*Links\Links()\ServerPublicKey[0], #BakaShrot_Ed25519_PublicKeySize)
PrintN("[Peer] [BakaShrot.Peer." + MapKey(*Config\Peers()) + "] PublicKey is missing or invalid")
BakaShrot_PeerLinks_Stop(*Links)
ProcedureReturn 0
EndIf
CopyStructure(@*Config\Peers()\SendTopics, @*Links\Links()\SendTopics, BakaShrot_NameSet)
CopyStructure(@*Config\Peers()\SendNodes, @*Links\Links()\SendNodes, BakaShrot_NameSet)
; List elements never move, so the thread can keep this pointer.
*Links\Links()\ThreadId = CreateThread(@BakaShrot_PeerLink_Thread(), @*Links\Links())
If Not *Links\Links()\ThreadId
BakaShrot_PeerLinks_Stop(*Links)
ProcedureReturn 0
EndIf
Next
ProcedureReturn *Links
EndProcedure
+256
View File
@@ -0,0 +1,256 @@
;{- Code Header
; ==- Basic Info -================================
; Name: Root.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; BakaShrot Server Root
;
; What the main ("root") thread owns and does:
; - The config.
; - Its own database connection: setup, and maintenance while the workers
; are stopped.
; - The workers: the network server (its listener and one thread per
; client, see Networking/Networking.pbi) and the peer links (one thread
; per peer, see Networking/Peers.pbi).
;
; Stopping the workers is the root's signal to every other thread.
; BakaShrot_Root_StopWorkers() sets the StopRequested flag of the network
; server and the peer links, which every one of their threads checks within a
; few ms, then waits until each of those threads has exited. Each one closes
; its own database connection on its way out. So once it returns, the root's
; connection is the only one left, and the root can:
; - BakaShrot_Root_Restart(): reload the config, reopen the database, start
; again. Picks up config changes, like a client's permissions.
; - BakaShrot_Root_Vacuum(): VACUUM the database, start again.
; - Anything else that needs the database or the config to itself.
; Clients and peer links are dropped meanwhile. Peers relink on their own,
; clients have to reconnect.
;
; Only call these from the root thread.
; ============================================================================
XIncludeFile "Config/Config.pbi"
XIncludeFile "Storage/Storage.pbi"
XIncludeFile "Storage/Names.pbi"
XIncludeFile "Storage/Retention.pbi"
XIncludeFile "Networking/Networking.pbi"
XIncludeFile "Networking/Peers.pbi"
Structure BakaShrot_Root
ConfigPath.s
*Config.BakaShrot_CoreConfig
; The root's own connection, only used for setup, and while the workers
; are stopped.
DbId.i
; Both 0 while the workers are stopped.
*Server.BakaShrot_NetServer
*Peers.BakaShrot_PeerLinks
EndStructure
; Loads *Root\ConfigPath into *Root\Config, replacing the current one.
; Returns #False if it can't be loaded, the current one is then kept.
; Only while the workers are stopped, they use the config.
Procedure.i BakaShrot_Root_LoadConfig(*Root.BakaShrot_Root)
Protected *Config.BakaShrot_CoreConfig
Protected Known.BakaShrot_KnownNames, KnownError.String, DatabasePath.s, DbId.i
; The names the database has first, so the ones the config lists without
; an id keep theirs (Storage/Names.pbi). Nothing to read on a new one.
DatabasePath = ReadConfigDatabasePath(*Root\ConfigPath)
If DatabasePath <> "" And FileSize(DatabasePath) > 0
DbId = OpenStorageDatabase(DatabasePath)
If Not DbId Or Not SetupStorageDatabase(DbId) Or Not BakaShrot_Names_ReadKnown(DbId, @Known, @KnownError)
PrintN("[Root] Failed to read the names of the database '" + DatabasePath + "': " + KnownError\s + DatabaseError())
If DbId
CloseDatabase(DbId)
EndIf
ProcedureReturn #False
EndIf
CloseDatabase(DbId)
EndIf
*Config = LoadConfig(*Root\ConfigPath, @Known)
If Not *Config
PrintN("[Root] Failed to load the config from '" + *Root\ConfigPath + "': " + BakaShrot_ConfigError)
ProcedureReturn #False
EndIf
If *Root\Config
FreeConfig(*Root\Config)
EndIf
*Root\Config = *Config
PrintN("[Root] Loaded config '" + *Root\ConfigPath + "' (Node=" + *Config\NodeText + ", " + Str(MapSize(*Config\TopicNames())) + " named topics, " +
Str(MapSize(*Config\NodeNames())) + " named nodes, " + Str(MapSize(*Config\Peers())) + " peers, " + Str(MapSize(*Config\Clients())) + " clients)")
ProcedureReturn #True
EndProcedure
; Opens the root's connection to the config's database, sets it up, and
; reconciles the config's topic and node names with it (Storage/Names.pbi).
; Returns #False if it can't be opened or set up, or if the names conflict.
Procedure.i BakaShrot_Root_OpenDatabase(*Root.BakaShrot_Root)
Protected DatabasePath.s = *Root\Config\Server\DatabasePath
Protected NamesError.String
; Every connection opened from here on, the workers' included (they're
; stopped meanwhile), takes it.
BakaShrot_Storage_Synchronous = *Root\Config\Server\Synchronous
*Root\DbId = OpenStorageDatabase(DatabasePath)
If Not *Root\DbId
PrintN("[Root] Failed to open the database '" + DatabasePath + "': " + DatabaseError())
ProcedureReturn #False
EndIf
If Not SetupStorageDatabase(*Root\DbId)
PrintN("[Root] Failed to set up the database '" + DatabasePath + "': " + DatabaseError())
CloseDatabase(*Root\DbId)
*Root\DbId = 0
ProcedureReturn #False
EndIf
If Not BakaShrot_Names_Load(*Root\DbId, *Root\Config, @NamesError)
PrintN("[Root] The config's names don't match the database '" + DatabasePath + "': " + NamesError\s)
CloseDatabase(*Root\DbId)
*Root\DbId = 0
ProcedureReturn #False
EndIf
PrintN("[Root] Database '" + DatabasePath + "' is ready (synchronous " + BakaShrot_Storage_Synchronous + ")")
ProcedureReturn #True
EndProcedure
Procedure BakaShrot_Root_CloseDatabase(*Root.BakaShrot_Root)
If *Root\DbId
CloseDatabase(*Root\DbId)
*Root\DbId = 0
EndIf
EndProcedure
; Starts the network server and the peer links.
; Returns #False if either can't start, nothing is left running then.
Procedure.i BakaShrot_Root_StartWorkers(*Root.BakaShrot_Root)
Protected *Config.BakaShrot_CoreConfig = *Root\Config
Protected WriterError.String
; Every write goes through it, see Storage/Writer.pbi.
If Not OpenStorageWriter(*Config\Server\DatabasePath, @WriterError)
PrintN("[Root] Failed to open the storage writer: " + WriterError\s)
ProcedureReturn #False
EndIf
; Deletes the messages past their topic's max age, see Storage/Retention.pbi.
If Not StartStorageRetention(*Config)
PrintN("[Root] Failed to start the retention thread")
CloseStorageWriter()
ProcedureReturn #False
EndIf
*Root\Server = BakaShrot_NetServer_Start(*Config\Server\Host, *Config\Server\Port, *Config)
If Not *Root\Server
PrintN("[Root] Failed to listen on '" + *Config\Server\Host + ":" + Str(*Config\Server\Port) + "'")
StopStorageRetention()
CloseStorageWriter()
ProcedureReturn #False
EndIf
PrintN("[Root] Listening on '" + *Config\Server\Host + ":" + Str(*Config\Server\Port) + "'")
*Root\Peers = BakaShrot_PeerLinks_Start(*Config)
If Not *Root\Peers
PrintN("[Root] Failed to start the peer links, are [BakaShrot] PrivateKey and every peer's PublicKey valid?")
BakaShrot_NetServer_Stop(*Root\Server)
*Root\Server = 0
StopStorageRetention()
CloseStorageWriter()
ProcedureReturn #False
EndIf
ProcedureReturn #True
EndProcedure
; The signal: stops every worker thread and waits until they've all exited,
; which closes every database connection but the root's own.
; Peer links first, so they don't relink to a server that's going away.
Procedure BakaShrot_Root_StopWorkers(*Root.BakaShrot_Root)
Protected StartTime.i = ElapsedMilliseconds()
If *Root\Peers
BakaShrot_PeerLinks_Stop(*Root\Peers)
*Root\Peers = 0
EndIf
If *Root\Server
BakaShrot_NetServer_Stop(*Root\Server)
*Root\Server = 0
EndIf
StopStorageRetention()
; Nothing writes anymore. Checkpoints the WAL into the database file.
CloseStorageWriter()
PrintN("[Root] Workers stopped in " + Str(ElapsedMilliseconds() - StartTime) + " ms")
EndProcedure
; Stops the workers, reloads the config (keeping the current one if the new
; one can't be loaded), reopens the database, and starts the workers again.
; Returns #False if the database can't be reopened or the workers can't
; start again, the server is then left stopped.
Procedure.i BakaShrot_Root_Restart(*Root.BakaShrot_Root)
PrintN("[Root] Restarting")
BakaShrot_Root_StopWorkers(*Root)
If Not BakaShrot_Root_LoadConfig(*Root)
PrintN("[Root] Keeping the current config")
EndIf
; The database path may have changed.
BakaShrot_Root_CloseDatabase(*Root)
If Not BakaShrot_Root_OpenDatabase(*Root)
ProcedureReturn #False
EndIf
ProcedureReturn BakaShrot_Root_StartWorkers(*Root)
EndProcedure
; Stops the workers, VACUUMs the database, and starts the workers again.
; Returns #False if the workers can't start again, a failed VACUUM is only
; logged.
Procedure.i BakaShrot_Root_Vacuum(*Root.BakaShrot_Root)
Protected StartTime.i
PrintN("[Root] Vacuuming the database")
BakaShrot_Root_StopWorkers(*Root)
StartTime = ElapsedMilliseconds()
If VacuumStorageDatabase(*Root\DbId)
PrintN("[Root] Vacuumed in " + Str(ElapsedMilliseconds() - StartTime) + " ms")
Else
PrintN("[Root] Failed to vacuum: " + DatabaseError())
EndIf
ProcedureReturn BakaShrot_Root_StartWorkers(*Root)
EndProcedure
+467
View File
@@ -0,0 +1,467 @@
;{- Code Header
; ==- Basic Info -================================
; Name: Attachments.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; BakaShrot Storage Attachments
;
; A message has at most one attachment, of any size up to the server's
; MaxAttachmentSize, stored in parts (Design/Attachments.md):
; blobs the data of one attachment, being received or stored
; blob_chunks its parts, #BakaShrot_AttachmentChunkSize bytes each, the
; last one what's left
; attachments a message's: its size and SHA-256, and its blob once any
; of it is here
; See SetupStorageDatabase() in Storage.pbi for the columns and states.
;
; Pushed with a message:
; CreateStorageBlob() an upload starts (state 0), owned by the
; client's topic and node
; StoreStorageBlobChunk() each part, in order
; HashStorageBlob() once all of it is here, checked against the
; SHA-256 given at the start: complete (1), or
; dropped (3)
; then InsertNextMessage() (Writer.pbi) with its blob id attaches it to
; the message, in the same transaction (2).
; Replicated: the message comes first (ReplicateMessages), its attachments
; row in state 0, then once the messages are caught up:
; GetMissingStorageAttachments() what's missing, or started
; StartReplicatedAttachment() the first part makes its blob
; StoreStorageBlobChunk() each part, resuming where it stopped
; FinishReplicatedAttachment() ready (2), or back to missing if its
; SHA-256 doesn't match
; Deleting a message (the retention) deletes its attachments row (trigger),
; which marks its blob (3); CleanUpStorageBlobs() deletes it a part at a
; time, along with uploads never completed or never attached.
;
; Writes go through the writer (Writer.pbi), under its mutex; reads take
; the caller's own connection.
; ============================================================================
; SHA-256 (BakaShrot_Sha256_*).
XIncludeFile "../../Commons/Cryptography/Libsodium.pbi"
Structure BakaShrot_StorageBlob
BlobId.q
TopicId.i
NodeId.i
Size.q
Sha256.a[#BakaShrot_Sha256Size]
Received.q
State.i
EndStructure
Structure BakaShrot_StorageAttachment
Size.q
Sha256.a[#BakaShrot_Sha256Size]
; 0 while none of it is here.
BlobId.q
; 0 missing, 1 receiving, 2 ready, 3 not kept here.
State.i
; Of its blob, 0 without one.
Received.q
EndStructure
Structure BakaShrot_StorageMissingAttachment
TopicId.i
NodeId.i
Topic.s
Node.s
MessageId.q
Received.q
EndStructure
#BakaShrot_Blob_Receiving = 0
#BakaShrot_Blob_Complete = 1
#BakaShrot_Blob_Attached = 2
#BakaShrot_Blob_Deleted = 3
#BakaShrot_Attachment_Missing = 0
#BakaShrot_Attachment_Receiving = 1
#BakaShrot_Attachment_Ready = 2
#BakaShrot_Attachment_NotKept = 3
; --- Reads, on the caller's connection -----------------------------------------
; Fills *Blob with blob BlobId. Returns #False if there's none.
Procedure.i GetStorageBlob(DbId.i, BlobId.q, *Blob.BakaShrot_StorageBlob)
Protected Found.i
SetDatabaseQuad(DbId, 0, BlobId)
If Not DatabaseQuery(DbId, "SELECT topic_id, node_id, size, sha256, received, state FROM blobs WHERE blob_id = ?")
ProcedureReturn #False
EndIf
Found = NextDatabaseRow(DbId)
If Found
*Blob\BlobId = BlobId
*Blob\TopicId = GetDatabaseLong(DbId, 0)
*Blob\NodeId = GetDatabaseLong(DbId, 1)
*Blob\Size = GetDatabaseQuad(DbId, 2)
FillMemory(@*Blob\Sha256[0], #BakaShrot_Sha256Size, 0)
If DatabaseColumnSize(DbId, 3) = #BakaShrot_Sha256Size
GetDatabaseBlob(DbId, 3, @*Blob\Sha256[0], #BakaShrot_Sha256Size)
EndIf
*Blob\Received = GetDatabaseQuad(DbId, 4)
*Blob\State = GetDatabaseLong(DbId, 5)
EndIf
FinishDatabaseQuery(DbId)
ProcedureReturn Found
EndProcedure
; Fills *Attachment with the attachment of TopicId:NodeId#MessageId.
; Returns #False if that message has none (or doesn't exist).
Procedure.i GetStorageAttachment(DbId.i, TopicId.i, NodeId.i, MessageId.q, *Attachment.BakaShrot_StorageAttachment)
Protected Found.i
SetDatabaseLong(DbId, 0, TopicId)
SetDatabaseLong(DbId, 1, NodeId)
SetDatabaseQuad(DbId, 2, MessageId)
If Not DatabaseQuery(DbId, "SELECT a.size, a.sha256, COALESCE(a.blob_id, 0), a.state, COALESCE(b.received, 0) " +
"FROM attachments a LEFT JOIN blobs b ON b.blob_id = a.blob_id " +
"WHERE a.topic_id = ? AND a.node_id = ? AND a.message_id = ?")
ProcedureReturn #False
EndIf
Found = NextDatabaseRow(DbId)
If Found
*Attachment\Size = GetDatabaseQuad(DbId, 0)
FillMemory(@*Attachment\Sha256[0], #BakaShrot_Sha256Size, 0)
If DatabaseColumnSize(DbId, 1) = #BakaShrot_Sha256Size
GetDatabaseBlob(DbId, 1, @*Attachment\Sha256[0], #BakaShrot_Sha256Size)
EndIf
*Attachment\BlobId = GetDatabaseQuad(DbId, 2)
*Attachment\State = GetDatabaseLong(DbId, 3)
*Attachment\Received = GetDatabaseQuad(DbId, 4)
EndIf
FinishDatabaseQuery(DbId)
ProcedureReturn Found
EndProcedure
; Part Index of blob BlobId, in a freshly allocated buffer, its size in
; *OutSize\i. Returns 0 if it isn't stored. The caller frees it.
Procedure.i ReadStorageBlobChunk(DbId.i, BlobId.q, Index.q, *OutSize.Integer)
Protected *Data, Size.i
SetDatabaseQuad(DbId, 0, BlobId)
SetDatabaseQuad(DbId, 1, Index)
If Not DatabaseQuery(DbId, "SELECT chunk_data FROM blob_chunks WHERE blob_id = ? AND chunk_index = ?")
ProcedureReturn 0
EndIf
If NextDatabaseRow(DbId)
Size = DatabaseColumnSize(DbId, 0)
If Size > 0
*Data = AllocateMemory(Size, #PB_Memory_NoClear)
If *Data
GetDatabaseBlob(DbId, 0, *Data, Size)
*OutSize\i = Size
EndIf
EndIf
EndIf
FinishDatabaseQuery(DbId)
ProcedureReturn *Data
EndProcedure
; Reads all of blob BlobId back (Size bytes, in parts) and checks its SHA-256
; is *Sha256. Returns #False if it isn't, or a part is missing or the wrong
; size. ~3 s per GB.
Procedure.i HashStorageBlob(DbId.i, BlobId.q, Size.q, *Sha256)
Protected Hash.BakaShrot_Sha256, Index.q, Count.q, *Data, DataSize.Integer
Protected Dim Result.a(#BakaShrot_Sha256Size - 1)
If Not BakaShrot_Sha256_Start(@Hash)
ProcedureReturn #False
EndIf
Count = BakaShrot_AttachmentChunkCount(Size)
For Index = 0 To Count - 1
*Data = ReadStorageBlobChunk(DbId, BlobId, Index, @DataSize)
If Not *Data
ProcedureReturn #False
EndIf
If DataSize\i <> BakaShrot_AttachmentChunkBytes(Size, Index)
FreeMemory(*Data)
ProcedureReturn #False
EndIf
BakaShrot_Sha256_Add(@Hash, *Data, DataSize\i)
FreeMemory(*Data)
Next
BakaShrot_Sha256_Finish(@Hash, @Result(0))
ProcedureReturn CompareMemory(@Result(0), *Sha256, #BakaShrot_Sha256Size)
EndProcedure
; Fills Missing() with attachments of messages here that aren't all here
; yet (missing or receiving), with their topic and node names, up to Limit.
; Unnamed topics or nodes are left out: replication goes by name.
; Returns #False if the query failed.
Procedure.i GetMissingStorageAttachments(DbId.i, Limit.i, List Missing.BakaShrot_StorageMissingAttachment())
ClearList(Missing())
SetDatabaseLong(DbId, 0, Limit)
If Not DatabaseQuery(DbId, "SELECT a.topic_id, a.node_id, t.name, n.name, a.message_id, COALESCE(b.received, 0) " +
"FROM attachments a JOIN topics t ON t.topic_id = a.topic_id JOIN nodes n ON n.node_id = a.node_id " +
"LEFT JOIN blobs b ON b.blob_id = a.blob_id " +
"WHERE a.state IN (0, 1) ORDER BY a.topic_id, a.node_id, a.message_id LIMIT ?")
ProcedureReturn #False
EndIf
While NextDatabaseRow(DbId)
AddElement(Missing())
Missing()\TopicId = GetDatabaseLong(DbId, 0)
Missing()\NodeId = GetDatabaseLong(DbId, 1)
Missing()\Topic = GetDatabaseString(DbId, 2)
Missing()\Node = GetDatabaseString(DbId, 3)
Missing()\MessageId = GetDatabaseQuad(DbId, 4)
Missing()\Received = GetDatabaseQuad(DbId, 5)
Wend
FinishDatabaseQuery(DbId)
ProcedureReturn #True
EndProcedure
; --- Writes, through the writer ------------------------------------------------
; Starts an upload for TopicId/NodeId: Size bytes whose SHA-256 is *Sha256.
; Returns its blob id, 0 with the reason in *Error\s.
Procedure.q CreateStorageBlob(TopicId.i, NodeId.i, Size.q, *Sha256, *Error.String)
Protected DbId.i, BlobId.q
LockMutex(BakaShrot_Storage_WriteMutex)
DbId = BakaShrot_Storage_Writer\DbId
If Not DbId
UnlockMutex(BakaShrot_Storage_WriteMutex)
*Error\s = "the storage writer isn't open"
ProcedureReturn 0
EndIf
SetDatabaseLong(DbId, 0, TopicId)
SetDatabaseLong(DbId, 1, NodeId)
SetDatabaseQuad(DbId, 2, Size)
SetDatabaseBlob(DbId, 3, *Sha256, #BakaShrot_Sha256Size)
SetDatabaseQuad(DbId, 4, BakaShrot_NowUtcMs())
If DatabaseUpdate(DbId, "INSERT INTO blobs (topic_id, node_id, size, sha256, received, state, created_at) VALUES (?, ?, ?, ?, 0, 0, ?)")
If DatabaseQuery(DbId, "SELECT last_insert_rowid()")
If NextDatabaseRow(DbId)
BlobId = GetDatabaseQuad(DbId, 0)
EndIf
FinishDatabaseQuery(DbId)
EndIf
EndIf
If Not BlobId
*Error\s = DatabaseError()
EndIf
UnlockMutex(BakaShrot_Storage_WriteMutex)
ProcedureReturn BlobId
EndProcedure
; Stores part Index (DataSize bytes at *Data) of blob BlobId, which must be
; the next one: Index * #BakaShrot_AttachmentChunkSize bytes received so far.
; Returns how many are received now, -1 with the reason in *Error\s (nothing
; stored then).
Procedure.q StoreStorageBlobChunk(BlobId.q, Index.q, *Data, DataSize.i, *Error.String)
Protected DbId.i, Received.q = -1, Ok.i
LockMutex(BakaShrot_Storage_WriteMutex)
DbId = BakaShrot_Storage_Writer\DbId
If Not DbId
UnlockMutex(BakaShrot_Storage_WriteMutex)
*Error\s = "the storage writer isn't open"
ProcedureReturn -1
EndIf
If DatabaseUpdate(DbId, "BEGIN IMMEDIATE")
; Only if it's the next one, and the blob is still being received.
SetDatabaseQuad(DbId, 0, DataSize)
SetDatabaseQuad(DbId, 1, BlobId)
SetDatabaseQuad(DbId, 2, Index * #BakaShrot_AttachmentChunkSize)
Ok = DatabaseUpdate(DbId, "UPDATE blobs SET received = received + ? WHERE blob_id = ? AND received = ? AND state = 0")
If Ok And AffectedDatabaseRows(DbId) <> 1
Ok = #False
*Error\s = "not the next part, or not being received"
ElseIf Not Ok
*Error\s = DatabaseError()
EndIf
If Ok
SetDatabaseQuad(DbId, 0, BlobId)
SetDatabaseQuad(DbId, 1, Index)
SetDatabaseBlob(DbId, 2, *Data, DataSize)
Ok = DatabaseUpdate(DbId, "INSERT INTO blob_chunks (blob_id, chunk_index, chunk_data) VALUES (?, ?, ?)")
If Not Ok
*Error\s = DatabaseError()
EndIf
EndIf
If Ok And DatabaseUpdate(DbId, "COMMIT")
Received = Index * #BakaShrot_AttachmentChunkSize + DataSize
Else
If Ok
*Error\s = DatabaseError()
EndIf
DatabaseUpdate(DbId, "ROLLBACK")
EndIf
Else
*Error\s = DatabaseError()
EndIf
UnlockMutex(BakaShrot_Storage_WriteMutex)
ProcedureReturn Received
EndProcedure
; Sets blob BlobId's state (#BakaShrot_Blob_*). Returns #False if it failed.
Procedure.i SetStorageBlobState(BlobId.q, State.i)
Protected DbId.i, Ok.i
LockMutex(BakaShrot_Storage_WriteMutex)
DbId = BakaShrot_Storage_Writer\DbId
If DbId
SetDatabaseLong(DbId, 0, State)
SetDatabaseQuad(DbId, 1, BlobId)
Ok = DatabaseUpdate(DbId, "UPDATE blobs SET state = ? WHERE blob_id = ?")
EndIf
UnlockMutex(BakaShrot_Storage_WriteMutex)
ProcedureReturn Ok
EndProcedure
; Makes the blob of a replicated attachment that's still missing (state 0),
; from its row's size and SHA-256, and links it: receiving (1).
; Returns its blob id, 0 with the reason in *Error\s.
Procedure.q StartReplicatedAttachment(TopicId.i, NodeId.i, MessageId.q, *Error.String)
Protected DbId.i, BlobId.q, Ok.i
LockMutex(BakaShrot_Storage_WriteMutex)
DbId = BakaShrot_Storage_Writer\DbId
If Not DbId
UnlockMutex(BakaShrot_Storage_WriteMutex)
*Error\s = "the storage writer isn't open"
ProcedureReturn 0
EndIf
If DatabaseUpdate(DbId, "BEGIN IMMEDIATE")
SetDatabaseLong(DbId, 0, TopicId)
SetDatabaseLong(DbId, 1, NodeId)
SetDatabaseQuad(DbId, 2, BakaShrot_NowUtcMs())
SetDatabaseLong(DbId, 3, TopicId)
SetDatabaseLong(DbId, 4, NodeId)
SetDatabaseQuad(DbId, 5, MessageId)
Ok = DatabaseUpdate(DbId, "INSERT INTO blobs (topic_id, node_id, size, sha256, received, state, created_at) " +
"SELECT ?, ?, size, sha256, 0, 0, ? FROM attachments WHERE topic_id = ? AND node_id = ? AND message_id = ? AND state = 0 AND blob_id IS NULL")
If Ok And AffectedDatabaseRows(DbId) = 1 And DatabaseQuery(DbId, "SELECT last_insert_rowid()")
If NextDatabaseRow(DbId)
BlobId = GetDatabaseQuad(DbId, 0)
EndIf
FinishDatabaseQuery(DbId)
EndIf
If BlobId
SetDatabaseQuad(DbId, 0, BlobId)
SetDatabaseLong(DbId, 1, TopicId)
SetDatabaseLong(DbId, 2, NodeId)
SetDatabaseQuad(DbId, 3, MessageId)
Ok = DatabaseUpdate(DbId, "UPDATE attachments SET blob_id = ?, state = 1 WHERE topic_id = ? AND node_id = ? AND message_id = ?")
EndIf
If BlobId And Ok And DatabaseUpdate(DbId, "COMMIT")
; Done.
Else
*Error\s = DatabaseError()
If *Error\s = ""
*Error\s = "the attachment isn't missing"
EndIf
DatabaseUpdate(DbId, "ROLLBACK")
BlobId = 0
EndIf
Else
*Error\s = DatabaseError()
EndIf
UnlockMutex(BakaShrot_Storage_WriteMutex)
ProcedureReturn BlobId
EndProcedure
; A replicated attachment is all here: ready (2) if its SHA-256 checked out
; (IsValid), else its blob is dropped and it's missing again (0), to be sent
; again from the start. Returns #False if it failed.
Procedure.i FinishReplicatedAttachment(TopicId.i, NodeId.i, MessageId.q, BlobId.q, IsValid.i)
Protected DbId.i, Ok.i
LockMutex(BakaShrot_Storage_WriteMutex)
DbId = BakaShrot_Storage_Writer\DbId
If DbId And DatabaseUpdate(DbId, "BEGIN IMMEDIATE")
SetDatabaseQuad(DbId, 0, BlobId)
If IsValid
Ok = DatabaseUpdate(DbId, "UPDATE blobs SET state = 2 WHERE blob_id = ?")
Else
Ok = DatabaseUpdate(DbId, "UPDATE blobs SET state = 3 WHERE blob_id = ?")
EndIf
If Ok
SetDatabaseLong(DbId, 0, TopicId)
SetDatabaseLong(DbId, 1, NodeId)
SetDatabaseQuad(DbId, 2, MessageId)
If IsValid
Ok = DatabaseUpdate(DbId, "UPDATE attachments SET state = 2 WHERE topic_id = ? AND node_id = ? AND message_id = ?")
Else
Ok = DatabaseUpdate(DbId, "UPDATE attachments SET state = 0, blob_id = NULL WHERE topic_id = ? AND node_id = ? AND message_id = ?")
EndIf
EndIf
If Ok
Ok = DatabaseUpdate(DbId, "COMMIT")
EndIf
If Not Ok
DatabaseUpdate(DbId, "ROLLBACK")
EndIf
EndIf
UnlockMutex(BakaShrot_Storage_WriteMutex)
ProcedureReturn Ok
EndProcedure
; Marks uploads never completed nor attached, started before BeforeMs (ms
; since 1970 UTC), to delete, then deletes up to Limit parts of what's to
; delete, and the blobs left with none. Call it again while it returns
; Limit. Returns how many parts were deleted, -1 with the reason in *Error\s.
Procedure.i CleanUpStorageBlobs(BeforeMs.q, Limit.i, *Error.String)
Protected DbId.i, Deleted.i = -1
LockMutex(BakaShrot_Storage_WriteMutex)
DbId = BakaShrot_Storage_Writer\DbId
If Not DbId
UnlockMutex(BakaShrot_Storage_WriteMutex)
*Error\s = "the storage writer isn't open"
ProcedureReturn -1
EndIf
; Uploads (no attachments row points to them) left behind.
SetDatabaseQuad(DbId, 0, BeforeMs)
If DatabaseUpdate(DbId, "UPDATE blobs SET state = 3 WHERE state IN (0, 1) AND created_at < ? " +
"AND NOT EXISTS (SELECT 1 FROM attachments a WHERE a.blob_id = blobs.blob_id)")
SetDatabaseLong(DbId, 0, Limit)
If DatabaseUpdate(DbId, "DELETE FROM blob_chunks WHERE rowid IN (SELECT c.rowid FROM blob_chunks c JOIN blobs b ON b.blob_id = c.blob_id WHERE b.state = 3 LIMIT ?)")
Deleted = AffectedDatabaseRows(DbId)
If Deleted < Limit
DatabaseUpdate(DbId, "DELETE FROM blobs WHERE state = 3 AND NOT EXISTS (SELECT 1 FROM blob_chunks c WHERE c.blob_id = blobs.blob_id)")
EndIf
EndIf
EndIf
If Deleted < 0
*Error\s = DatabaseError()
EndIf
UnlockMutex(BakaShrot_Storage_WriteMutex)
ProcedureReturn Deleted
EndProcedure
+548
View File
@@ -0,0 +1,548 @@
;{- Code Header
; ==- Basic Info -================================
; Name: Names.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; BakaShrot Storage Names
;
; Which name every topic and node id has on this server. Names are what's
; shared between servers (Commons/Networking/Names.pbi): replication sends
; them, and each server stores the messages under its own ids for them. Say
; topic "logs" is 1 here and 200 on a peer: the peer sends "logs", this
; server stores it under 1. Hand-written configs drift, the names keep them
; matching anyway.
;
; Only what's named on BOTH servers replicates: a topic or node without a
; name, or with a name the other server doesn't know, is dropped. Unless the
; receiver takes it by a wildcard: "*" or a pattern ("sensors.*") in that
; peer's AcceptTopics / AcceptNodes takes matching names it doesn't have,
; and adds them (BakaShrot_Names_Ingest(), origin "peer") under the highest
; free id counting down from 65535, out of the way of the ids picked in the
; config. To not be refused over and over, each check-in's sync state lists
; every name the receiver knows and takes, and its patterns, and the sender
; only sends those. Every drop goes through BakaShrot_Names_NoteDropped().
;
; Kept in the "topics" and "nodes" tables (Storage.pbi), so raw queries can
; join on them (the "messages" view), and in memory for the server, guarded
; by BakaShrot_Names_Mutex. Every id in "data" has a row:
; origin "config" named by the config: in [BakaShrot.Topics] /
; [BakaShrot.Nodes], or a peer's or client's Node
; origin "id" unnamed, its name is its id in digits
; origin "peer" sent by a peer, taken by a wildcard, named by the peer
;
; Ids are this server's to pick: a name the config lists without one keeps
; the one these tables have for it, a new one gets the lowest free one
; (LoadConfig(), after BakaShrot_Names_ReadKnown()). The config may still
; pin one ("logs = 1").
;
; BakaShrot_Names_Load() reconciles the config with the tables at start (and
; on restart). The config wins, except when it would give a name to another
; id than the one the database has it under (or rename a "peer" one): that
; would relabel stored messages, so the server refuses to start and says
; which id to use.
;
; Lock order: BakaShrot_Names_Mutex, then the write mutex (Writer.pbi).
; ============================================================================
XIncludeFile "../Config/Config.pbi"
XIncludeFile "Storage.pbi"
XIncludeFile "../../Commons/Networking/Packets/NamesListPacket.pbi"
#BakaShrot_Names_OriginConfig = "config"
#BakaShrot_Names_OriginPeer = "peer"
#BakaShrot_Names_OriginId = "id"
; One of the two tables, in memory.
Structure BakaShrot_NameTable
Table.s
IdColumn.s
Kind.s
; LCase(name) -> id, named ones only.
Map IdByName.i()
; Str(id) -> name, "" if unnamed. Every id with a row.
Map NameById.s()
; Str(id) -> origin.
Map OriginById.s()
EndStructure
Global BakaShrot_Names_Mutex.i = CreateMutex()
Global BakaShrot_Names_Topics.BakaShrot_NameTable
Global BakaShrot_Names_Nodes.BakaShrot_NameTable
BakaShrot_Names_Topics\Table = "topics"
BakaShrot_Names_Topics\IdColumn = "topic_id"
BakaShrot_Names_Topics\Kind = "topic"
BakaShrot_Names_Nodes\Table = "nodes"
BakaShrot_Names_Nodes\IdColumn = "node_id"
BakaShrot_Names_Nodes\Kind = "node"
; --- Loading -----------------------------------------------------------------
; Reconciles one table with the config's names (ConfigNames: Str(id) ->
; name) and the ids it uses (UsedIds), plus every id already in "data"
; (node_heads), then fills *Names from it.
; Runs inside the transaction of BakaShrot_Names_Load().
Procedure.i BakaShrot_Names_LoadTable(DbId.i, *Names.BakaShrot_NameTable, Map ConfigNames.s(), Map UsedIds.i(), *Error.String)
Protected NewMap DbName.s(), NewMap DbOrigin.s(), NewMap DbIdByName.i(), NewMap AllIds.i()
Protected Id.i, Name.s, Key.s, Section.s
If *Names = @BakaShrot_Names_Topics
Section = "[BakaShrot.Topics]"
Else
Section = "[BakaShrot.Nodes]"
EndIf
; What the database has.
If Not DatabaseQuery(DbId, "SELECT " + *Names\IdColumn + ", name, origin FROM " + *Names\Table)
*Error\s = "can't read the " + *Names\Table + " table: " + DatabaseError()
ProcedureReturn #False
EndIf
While NextDatabaseRow(DbId)
Key = Str(GetDatabaseLong(DbId, 0))
DbName(Key) = GetDatabaseString(DbId, 1)
DbOrigin(Key) = GetDatabaseString(DbId, 2)
If Not BakaShrot_IsDigits(DbName(Key))
DbIdByName(LCase(DbName(Key))) = Val(Key)
EndIf
Wend
FinishDatabaseQuery(DbId)
; The config's names.
ForEach ConfigNames()
Key = MapKey(ConfigNames())
Name = ConfigNames()
Id = Val(Key)
If FindMapElement(DbIdByName(), LCase(Name)) And DbIdByName() <> Id
*Error\s = *Names\Kind + " '" + Name + "' is id " + Str(Id) + " in " + Section + ", but its messages are stored under id " +
Str(DbIdByName()) + ": give it id " + Str(DbIdByName()) + " in the config"
ProcedureReturn #False
EndIf
If FindMapElement(DbName(), Key)
If DbName(Key) = Name And DbOrigin(Key) = #BakaShrot_Names_OriginConfig
Continue
EndIf
If DbOrigin(Key) = #BakaShrot_Names_OriginPeer And LCase(DbName(Key)) <> LCase(Name)
*Error\s = *Names\Kind + " id " + Str(Id) + " is '" + DbName(Key) + "', added by a peer, " + Section + " can't rename it to '" + Name +
"': give '" + Name + "' another id, or name id " + Str(Id) + " '" + DbName(Key) + "'"
ProcedureReturn #False
EndIf
If LCase(DbName(Key)) <> LCase(Name) And DbOrigin(Key) = #BakaShrot_Names_OriginConfig
PrintN("[Names] Renaming " + *Names\Kind + " " + Key + " from '" + DbName(Key) + "' to '" + Name + "'")
EndIf
EndIf
SetDatabaseLong(DbId, 0, Id)
SetDatabaseString(DbId, 1, Name)
SetDatabaseString(DbId, 2, #BakaShrot_Names_OriginConfig)
If Not DatabaseUpdate(DbId, "INSERT INTO " + *Names\Table + " (" + *Names\IdColumn + ", name, origin) VALUES (?, ?, ?) " +
"ON CONFLICT (" + *Names\IdColumn + ") DO UPDATE SET name = excluded.name, origin = excluded.origin")
*Error\s = "can't store " + *Names\Kind + " '" + Name + "': " + DatabaseError()
ProcedureReturn #False
EndIf
Next
; Every id the config uses, and every one already in "data", gets a row.
ForEach UsedIds()
AllIds(MapKey(UsedIds())) = #True
Next
If Not DatabaseQuery(DbId, "SELECT DISTINCT " + *Names\IdColumn + " FROM node_heads")
*Error\s = "can't read node_heads: " + DatabaseError()
ProcedureReturn #False
EndIf
While NextDatabaseRow(DbId)
AllIds(Str(GetDatabaseLong(DbId, 0))) = #True
Wend
FinishDatabaseQuery(DbId)
ForEach AllIds()
Key = MapKey(AllIds())
If FindMapElement(ConfigNames(), Key) Or FindMapElement(DbName(), Key)
Continue
EndIf
SetDatabaseLong(DbId, 0, Val(Key))
SetDatabaseString(DbId, 1, Key)
SetDatabaseString(DbId, 2, #BakaShrot_Names_OriginId)
If Not DatabaseUpdate(DbId, "INSERT OR IGNORE INTO " + *Names\Table + " (" + *Names\IdColumn + ", name, origin) VALUES (?, ?, ?)")
*Error\s = "can't store " + *Names\Kind + " id " + Key + ": " + DatabaseError()
ProcedureReturn #False
EndIf
Next
; In memory, from what the table now holds.
ClearMap(*Names\IdByName())
ClearMap(*Names\NameById())
ClearMap(*Names\OriginById())
If Not DatabaseQuery(DbId, "SELECT " + *Names\IdColumn + ", name, origin FROM " + *Names\Table)
*Error\s = "can't read the " + *Names\Table + " table: " + DatabaseError()
ProcedureReturn #False
EndIf
While NextDatabaseRow(DbId)
Id = GetDatabaseLong(DbId, 0)
Name = GetDatabaseString(DbId, 1)
*Names\OriginById(Str(Id)) = GetDatabaseString(DbId, 2)
If BakaShrot_IsDigits(Name)
*Names\NameById(Str(Id)) = ""
Else
*Names\NameById(Str(Id)) = Name
*Names\IdByName(LCase(Name)) = Id
EndIf
Wend
FinishDatabaseQuery(DbId)
ProcedureReturn #True
EndProcedure
; Reconciles the config's names with the database, see the top of this
; file. Only from the root, with the workers stopped, on its own connection.
; Returns #False with the reason in *Error\s, nothing is changed then.
Procedure.i BakaShrot_Names_Load(DbId.i, *Config.BakaShrot_CoreConfig, *Error.String)
Protected Loaded.i
LockMutex(BakaShrot_Names_Mutex)
If Not DatabaseUpdate(DbId, "BEGIN IMMEDIATE")
*Error\s = DatabaseError()
UnlockMutex(BakaShrot_Names_Mutex)
ProcedureReturn #False
EndIf
Loaded = Bool(BakaShrot_Names_LoadTable(DbId, @BakaShrot_Names_Topics, *Config\TopicNames(), *Config\UsedTopicIds(), *Error) And
BakaShrot_Names_LoadTable(DbId, @BakaShrot_Names_Nodes, *Config\NodeNames(), *Config\UsedNodeIds(), *Error))
If Loaded And Not DatabaseUpdate(DbId, "COMMIT")
*Error\s = DatabaseError()
Loaded = #False
EndIf
If Not Loaded
DatabaseUpdate(DbId, "ROLLBACK")
EndIf
UnlockMutex(BakaShrot_Names_Mutex)
ProcedureReturn Loaded
EndProcedure
; Fills *Known with what the database has, for LoadConfig() (Config.pbi):
; the id of every name, and every id with a row or messages. Before the
; config is loaded, on a connection of its own, the database set up.
; Returns #False with the reason in *Error\s.
Procedure.i BakaShrot_Names_ReadKnown(DbId.i, *Known.BakaShrot_KnownNames, *Error.String)
Protected Name.s, Id.i
; Topics
If Not DatabaseQuery(DbId, "SELECT topic_id, name FROM topics UNION SELECT DISTINCT topic_id, '' FROM node_heads")
*Error\s = "can't read the topics: " + DatabaseError()
ProcedureReturn #False
EndIf
While NextDatabaseRow(DbId)
Id = GetDatabaseLong(DbId, 0)
Name = GetDatabaseString(DbId, 1)
*Known\TopicUsed(Str(Id)) = #True
If Name <> "" And Not BakaShrot_IsDigits(Name)
*Known\TopicIds(LCase(Name)) = Id
EndIf
Wend
FinishDatabaseQuery(DbId)
; Nodes
If Not DatabaseQuery(DbId, "SELECT node_id, name FROM nodes UNION SELECT DISTINCT node_id, '' FROM node_heads")
*Error\s = "can't read the nodes: " + DatabaseError()
ProcedureReturn #False
EndIf
While NextDatabaseRow(DbId)
Id = GetDatabaseLong(DbId, 0)
Name = GetDatabaseString(DbId, 1)
*Known\NodeUsed(Str(Id)) = #True
If Name <> "" And Not BakaShrot_IsDigits(Name)
*Known\NodeIds(LCase(Name)) = Id
EndIf
Wend
FinishDatabaseQuery(DbId)
ProcedureReturn #True
EndProcedure
; --- Lookups -----------------------------------------------------------------
; The id Ref stands for: an id in digits is that id, a name must be known.
; -1 if it's neither. Holding the names mutex.
Procedure.i BakaShrot_Names_ResolveIn(*Names.BakaShrot_NameTable, Ref.s)
Protected Id.i = BakaShrot_RefToId(Ref)
If Id >= 0
ProcedureReturn Id
EndIf
If BakaShrot_IsValidName(Ref) And FindMapElement(*Names\IdByName(), LCase(Ref))
ProcedureReturn *Names\IdByName()
EndIf
ProcedureReturn -1
EndProcedure
; Its name, "" if it has none. Holding the names mutex.
Procedure.s BakaShrot_Names_NameIn(*Names.BakaShrot_NameTable, Id.i)
If FindMapElement(*Names\NameById(), Str(Id))
ProcedureReturn *Names\NameById()
EndIf
ProcedureReturn ""
EndProcedure
; The topic id Ref stands for here, -1 if none.
Procedure.i BakaShrot_Names_ResolveTopic(Ref.s)
Protected Id.i
LockMutex(BakaShrot_Names_Mutex)
Id = BakaShrot_Names_ResolveIn(@BakaShrot_Names_Topics, Ref)
UnlockMutex(BakaShrot_Names_Mutex)
ProcedureReturn Id
EndProcedure
; The node id Ref stands for here, -1 if none.
Procedure.i BakaShrot_Names_ResolveNode(Ref.s)
Protected Id.i
LockMutex(BakaShrot_Names_Mutex)
Id = BakaShrot_Names_ResolveIn(@BakaShrot_Names_Nodes, Ref)
UnlockMutex(BakaShrot_Names_Mutex)
ProcedureReturn Id
EndProcedure
; The topic id of a known name (never an id in digits), -1 if none: what
; replication goes by.
Procedure.i BakaShrot_Names_TopicByName(Name.s)
If Not BakaShrot_IsValidName(Name)
ProcedureReturn -1
EndIf
ProcedureReturn BakaShrot_Names_ResolveTopic(Name)
EndProcedure
; Same for a node.
Procedure.i BakaShrot_Names_NodeByName(Name.s)
If Not BakaShrot_IsValidName(Name)
ProcedureReturn -1
EndIf
ProcedureReturn BakaShrot_Names_ResolveNode(Name)
EndProcedure
; A topic's name, "" if it has none.
Procedure.s BakaShrot_Names_TopicName(Id.i)
Protected Name.s
LockMutex(BakaShrot_Names_Mutex)
Name = BakaShrot_Names_NameIn(@BakaShrot_Names_Topics, Id)
UnlockMutex(BakaShrot_Names_Mutex)
ProcedureReturn Name
EndProcedure
; A node's name, "" if it has none.
Procedure.s BakaShrot_Names_NodeName(Id.i)
Protected Name.s
LockMutex(BakaShrot_Names_Mutex)
Name = BakaShrot_Names_NameIn(@BakaShrot_Names_Nodes, Id)
UnlockMutex(BakaShrot_Names_Mutex)
ProcedureReturn Name
EndProcedure
; What a topic goes by in answers and logs: its name, or its id in digits.
Procedure.s BakaShrot_Names_TopicRef(Id.i)
Protected Name.s = BakaShrot_Names_TopicName(Id)
If Name = ""
ProcedureReturn Str(Id)
EndIf
ProcedureReturn Name
EndProcedure
; Same for a node.
Procedure.s BakaShrot_Names_NodeRef(Id.i)
Protected Name.s = BakaShrot_Names_NodeName(Id)
If Name = ""
ProcedureReturn Str(Id)
EndIf
ProcedureReturn Name
EndProcedure
; Fills Names() with every named topic (Kind #BakaShrot_NameKind_Topic) or
; node, by id, for the sync state. *Filter: only the ones it holds, 0 for
; all of them.
Procedure BakaShrot_Names_GetNamed(Kind.i, List Names.BakaShrot_SyncName(), *Filter.BakaShrot_NameSet = 0)
Protected *Names.BakaShrot_NameTable, Id.i
*Names = @BakaShrot_Names_Topics
If Kind = #BakaShrot_NameKind_Node
*Names = @BakaShrot_Names_Nodes
EndIf
ClearList(Names())
LockMutex(BakaShrot_Names_Mutex)
ForEach *Names\IdByName()
Id = *Names\IdByName()
If *Filter And Not NameSetHas(*Filter, Id, BakaShrot_Names_NameIn(*Names, Id))
Continue
EndIf
AddElement(Names())
Names()\Id = Id
Names()\Name = BakaShrot_Names_NameIn(*Names, Id)
Next
UnlockMutex(BakaShrot_Names_Mutex)
SortStructuredList(Names(), #PB_Sort_Ascending, OffsetOf(BakaShrot_SyncName\Id), #PB_Long)
EndProcedure
; Fills Entries() with every topic or node (Kind), named or not, by id, with
; where its name comes from. *Filter: only the topics it holds, 0 for all.
Procedure BakaShrot_Names_GetAll(Kind.i, List Entries.BakaShrot_NameEntry(), *Filter.BakaShrot_NameSet = 0)
Protected *Names.BakaShrot_NameTable, Id.i
*Names = @BakaShrot_Names_Topics
If Kind = #BakaShrot_NameKind_Node
*Names = @BakaShrot_Names_Nodes
EndIf
ClearList(Entries())
LockMutex(BakaShrot_Names_Mutex)
ForEach *Names\NameById()
Id = Val(MapKey(*Names\NameById()))
If *Filter And Not NameSetHas(*Filter, Id, *Names\NameById())
Continue
EndIf
AddElement(Entries())
Entries()\Id = Id
Entries()\Name = *Names\NameById()
Entries()\Origin = *Names\OriginById(Str(Id))
Next
UnlockMutex(BakaShrot_Names_Mutex)
SortStructuredList(Entries(), #PB_Sort_Ascending, OffsetOf(BakaShrot_NameEntry\Id), #PB_Long)
EndProcedure
; Prints every topic and node with its id, for the server's "names" command.
Procedure BakaShrot_Names_Print()
Protected NewList Entries.BakaShrot_NameEntry()
Protected Kind.i, Label.s, Name.s
For Kind = #BakaShrot_NameKind_Topic To #BakaShrot_NameKind_Node
BakaShrot_Names_GetAll(Kind, Entries())
If Kind = #BakaShrot_NameKind_Topic
Label = "Topics"
Else
Label = "Nodes"
EndIf
PrintN(Label + " (" + Str(ListSize(Entries())) + "):")
ForEach Entries()
Name = Entries()\Name
If Name = ""
Name = "(unnamed, not replicated)"
EndIf
PrintN(" " + RSet(Str(Entries()\Id), 5) + " " + LSet(Name, 30) + " " + Entries()\Origin)
Next
Next
EndProcedure
; --- Adding ------------------------------------------------------------------
; Makes sure Id has a row, as unnamed if it's new: for messages stored under
; an id the database didn't know yet (a push to a topic allowed by "*").
; Holding the names mutex. Returns #False with the reason in *Error\s.
Procedure.i BakaShrot_Names_EnsureIdIn(*Names.BakaShrot_NameTable, Id.i, *Error.String)
If FindMapElement(*Names\NameById(), Str(Id))
ProcedureReturn #True
EndIf
If Not RegisterStorageName(*Names\Table, Id, Str(Id), #BakaShrot_Names_OriginId, *Error)
ProcedureReturn #False
EndIf
*Names\NameById(Str(Id)) = ""
*Names\OriginById(Str(Id)) = #BakaShrot_Names_OriginId
ProcedureReturn #True
EndProcedure
Procedure.i BakaShrot_Names_EnsureTopicId(Id.i, *Error.String)
Protected Done.i
LockMutex(BakaShrot_Names_Mutex)
Done = BakaShrot_Names_EnsureIdIn(@BakaShrot_Names_Topics, Id, *Error)
UnlockMutex(BakaShrot_Names_Mutex)
ProcedureReturn Done
EndProcedure
; The id of a topic (Kind #BakaShrot_NameKind_Topic) or node a peer sent,
; by its name, which a wildcard in that peer's AcceptTopics / AcceptNodes
; took (the caller checks): a name this server doesn't have yet is added,
; under the highest free id counting down from 65535 (origin "peer").
; Returns -1 with the reason in *Error\s.
Procedure.i BakaShrot_Names_Ingest(Kind.i, Name.s, *Error.String)
Protected *Names.BakaShrot_NameTable, Id.i
*Names = @BakaShrot_Names_Topics
If Kind = #BakaShrot_NameKind_Node
*Names = @BakaShrot_Names_Nodes
EndIf
If Not BakaShrot_IsValidName(Name)
*Error\s = "'" + Name + "' isn't a valid " + *Names\Kind + " name"
ProcedureReturn -1
EndIf
LockMutex(BakaShrot_Names_Mutex)
If FindMapElement(*Names\IdByName(), LCase(Name))
Id = *Names\IdByName()
UnlockMutex(BakaShrot_Names_Mutex)
ProcedureReturn Id
EndIf
For Id = #BakaShrot_MaxId To 0 Step -1
If Not FindMapElement(*Names\NameById(), Str(Id))
Break
EndIf
Next
If Id < 0
UnlockMutex(BakaShrot_Names_Mutex)
*Error\s = "no " + *Names\Kind + " id left for '" + Name + "'"
ProcedureReturn -1
EndIf
If Not RegisterStorageName(*Names\Table, Id, Name, #BakaShrot_Names_OriginPeer, *Error)
UnlockMutex(BakaShrot_Names_Mutex)
ProcedureReturn -1
EndIf
*Names\NameById(Str(Id)) = Name
*Names\OriginById(Str(Id)) = #BakaShrot_Names_OriginPeer
*Names\IdByName(LCase(Name)) = Id
UnlockMutex(BakaShrot_Names_Mutex)
PrintN("[Names] New " + *Names\Kind + " '" + Name + "' from a peer, id " + Str(Id) + " here")
ProcedureReturn Id
EndProcedure
; --- Drops -------------------------------------------------------------------
; Called whenever a topic or node isn't replicated because one side doesn't
; know it: Peer is the peer section's name, Kind "topic" or "node", Ref what
; it goes by on the side that has it, Reason why it was dropped.
; !!! Does nothing for now, on purpose: it's called at every check-in for
; !!! every such pair, so logging each one would spam. Later: warn once per
; !!! peer and name (and again only if it changes), see Notes.md.
Procedure BakaShrot_Names_NoteDropped(Peer.s, Kind.s, Ref.s, Reason.s)
EndProcedure
+214
View File
@@ -0,0 +1,214 @@
;{- Code Header
; ==- Basic Info -================================
; Name: Retention.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; BakaShrot Storage Retention
;
; Deletes the messages past their topic's max age, so a server's database
; stops growing: [BakaShrot.Retention] in its config, see
; BakaShrot_RetentionRule in Server/Config/Config.pbi.
;
; A thread, started with the workers (StartStorageRetention(), see
; Server/Root.pbi), runs a pass right away then every [BakaShrot.Server]
; RetentionInterval seconds:
; - every topic of the database (node_heads), with its name (topics);
; - its max age from the rules; kept forever (0) is skipped;
; - deletes its messages pushed (pushed_at) before now minus that age,
; #BakaShrot_Retention_BatchSize at a time through the writer
; (DeleteStorageMessagesBefore(), Writer.pbi), so pushes go on between
; the batches;
; - then the attachments' leftovers (CleanUpStorageBlobs(),
; Attachments.pbi): those of the deleted messages, and uploads not
; pushed with a message within [BakaShrot.Server] UploadTimeout,
; #BakaShrot_Retention_ChunkBatchSize parts at a time.
; It runs without any [BakaShrot.Retention] too, for the leftovers.
;
; Messages "may be" deleted past their max age: up to RetentionInterval
; later. Those a peer replicates here already past it aren't stored at all
; (InsertReplicatedMessages() in Writer.pbi), only counted as received. pushed_at is the time the message was pushed to its origin, kept as
; is by replication, so a server deletes a replicated message by when it
; was first pushed, not when it got it.
;
; What deleting doesn't change:
; - node_heads: a pair's head stays its highest id ever. The next push
; still gets the next id, and the sync state still tells peers this
; server had those messages: they aren't sent again.
; - The file's size: SQLite reuses the freed pages for new messages, so
; it stops growing once deletions keep up with pushes. VACUUM (the
; "vacuum" console command) gives the space back to the disk.
; ============================================================================
; Most messages deleted in one statement, under the write mutex: a few ms.
#BakaShrot_Retention_BatchSize = 5000
; Most attachment parts (1 MB each) deleted in one statement.
#BakaShrot_Retention_ChunkBatchSize = 32
Structure BakaShrot_RetentionTopic
TopicId.i
Name.s
EndStructure
Structure BakaShrot_RetentionState
ThreadId.i
StopRequested.i
IntervalMs.i
UploadTimeoutMs.q
DatabasePath.s
List Rules.BakaShrot_RetentionRule()
EndStructure
Global BakaShrot_Retention.BakaShrot_RetentionState
; Ms (since 1970 UTC) as "2026-11-08T14:03:59Z", for the logs.
Procedure.s BakaShrot_Retention_FormatUtc(Ms.q)
ProcedureReturn FormatDate("%yyyy-%mm-%ddT%hh:%ii:%ssZ", Ms / 1000)
EndProcedure
; Deletes the attachments' leftovers, a few parts at a time.
Procedure BakaShrot_Retention_CleanUp()
Protected Deleted.i, Total.q, Error.String
Repeat
Deleted = CleanUpStorageBlobs(BakaShrot_NowUtcMs() - BakaShrot_Retention\UploadTimeoutMs, #BakaShrot_Retention_ChunkBatchSize, @Error)
If Deleted < 0
PrintN("[Storage] Retention: failed to delete the attachments' leftovers: " + Error\s)
Break
EndIf
Total + Deleted
Until Deleted < #BakaShrot_Retention_ChunkBatchSize Or BakaShrot_Retention\StopRequested
If Total > 0
PrintN("[Storage] Retention: deleted " + Str(Total) + " attachment parts (of deleted messages, or uploads never pushed)")
EndIf
EndProcedure
; Deletes what's past its max age in every topic. DbId is the thread's own
; connection, only read from (the deletes go through the writer).
; Returns how many messages were deleted.
Procedure.q BakaShrot_Retention_Pass(DbId.i)
Protected NewList Topics.BakaShrot_RetentionTopic()
Protected MaxAge.q, Before.q, Deleted.i, TopicDeleted.q, Total.q, Error.String
If Not DatabaseQuery(DbId, "SELECT DISTINCT h.topic_id, COALESCE(t.name, '') FROM node_heads h LEFT JOIN topics t ON t.topic_id = h.topic_id")
PrintN("[Storage] Retention: can't list the topics: " + DatabaseError())
ProcedureReturn 0
EndIf
While NextDatabaseRow(DbId)
AddElement(Topics())
Topics()\TopicId = GetDatabaseLong(DbId, 0)
Topics()\Name = GetDatabaseString(DbId, 1)
Wend
FinishDatabaseQuery(DbId)
ForEach Topics()
MaxAge = RetentionMaxAgeMs(BakaShrot_Retention\Rules(), Topics()\TopicId, Topics()\Name)
If MaxAge <= 0
Continue
EndIf
Before = BakaShrot_NowUtcMs() - MaxAge
TopicDeleted = 0
Repeat
Deleted = DeleteStorageMessagesBefore(Topics()\TopicId, Before, #BakaShrot_Retention_BatchSize, @Error)
If Deleted < 0
PrintN("[Storage] Retention: failed to delete from topic " + Str(Topics()\TopicId) + ": " + Error\s)
Break
EndIf
TopicDeleted + Deleted
Until Deleted < #BakaShrot_Retention_BatchSize Or BakaShrot_Retention\StopRequested
If TopicDeleted > 0
If Topics()\Name <> ""
PrintN("[Storage] Retention: deleted " + Str(TopicDeleted) + " messages of topic '" + Topics()\Name + "' pushed before " + BakaShrot_Retention_FormatUtc(Before))
Else
PrintN("[Storage] Retention: deleted " + Str(TopicDeleted) + " messages of topic " + Str(Topics()\TopicId) + " pushed before " + BakaShrot_Retention_FormatUtc(Before))
EndIf
EndIf
Total + TopicDeleted
If BakaShrot_Retention\StopRequested
Break
EndIf
Next
BakaShrot_Retention_CleanUp()
ProcedureReturn Total
EndProcedure
Procedure BakaShrot_Retention_Thread(Unused.i)
Protected DbId.i, LastPass.i
DbId = OpenStorageDatabase(BakaShrot_Retention\DatabasePath)
If Not DbId
PrintN("[Storage] Retention: can't open the database, nothing will be deleted: " + DatabaseError())
ProcedureReturn
EndIf
BakaShrot_Retention_Pass(DbId)
LastPass = ElapsedMilliseconds()
While Not BakaShrot_Retention\StopRequested
Delay(100)
If ElapsedMilliseconds() - LastPass >= BakaShrot_Retention\IntervalMs
BakaShrot_Retention_Pass(DbId)
LastPass = ElapsedMilliseconds()
EndIf
Wend
CloseDatabase(DbId)
EndProcedure
; Starts deleting what's past *Config's [BakaShrot.Retention] max ages, and
; the attachments' leftovers, once the writer is open.
; Returns #False if the thread can't start.
Procedure.i StartStorageRetention(*Config.BakaShrot_CoreConfig)
With BakaShrot_Retention
ClearList(\Rules())
CopyList(*Config\Retention(), \Rules())
ForEach \Rules()
If \Rules()\MaxAgeMs > 0
PrintN("[Storage] Retention: " + \Rules()\Ref + " = " + \Rules()\AgeText + ", checked every " + Str(*Config\Server\RetentionInterval) + " s")
EndIf
Next
\DatabasePath = *Config\Server\DatabasePath
\IntervalMs = *Config\Server\RetentionInterval * 1000
\UploadTimeoutMs = *Config\Server\UploadTimeout * 1000
\StopRequested = #False
\ThreadId = CreateThread(@BakaShrot_Retention_Thread(), 0)
ProcedureReturn Bool(\ThreadId)
EndWith
EndProcedure
; Stops it, before the writer closes. Waits for a pass under way to end its
; current batch.
Procedure StopStorageRetention()
With BakaShrot_Retention
If \ThreadId
\StopRequested = #True
WaitThread(\ThreadId)
\ThreadId = 0
EndIf
EndWith
EndProcedure
+971
View File
@@ -0,0 +1,971 @@
;{- Code Header
; ==- Basic Info -================================
; Name: Storage.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; BakaShrot Storage
;
; Opens the SQLite database file that backs the node's local storage, and
; provides the basic read/write operations on top of it.
; Schema: see db_schema_v8.dbml in this same folder. Attachments: see
; Attachments.pbi and Design/Attachments.md.
;
; Needs SQLite 3.38+ with its JSON functions (json_valid, ->>), which the one
; bundled with PureBasic 5.73 (3.33.0) doesn't have. On Windows, the official
; sqlite3.dll is used instead, it must be next to the program. Build.ps1
; extracts it from Libs/sqlite-dll-win-*.zip and copies it.
; On Linux, the system's libsqlite3.so.0 (libsqlite3-0 on Debian/Ubuntu,
; sqlite-libs on Fedora) is used, whatever the compiler, it must be 3.38+.
; Either way it's #BakaShrot_Storage_SqliteLibrary, which RunReadOnlyQuery()
; and the writer (Writer.pbi) also call directly. Elsewhere, PureBasic's own
; SQLite is linked in, and they make do without it.
;
; Threads: ONE CONNECTION PER THREAD, never share a handle.
; The SetDatabase*() parameters and query results belong to a handle, so two
; threads using the same one overwrite each other's. Every thread that touches
; the database opens its own with OpenStorageDatabase() and closes it when it
; ends: each client thread, each peer link thread, each raw query, and the
; root's own one (setup and maintenance, see Server/Root.pbi).
; The one exception: every write goes through the writer (Writer.pbi), a
; single connection only used while holding BakaShrot_Storage_WriteMutex.
; SQLite still serializes writes from other processes
; (#BakaShrot_Storage_BusyTimeout). WAL mode lets reads run alongside them.
; See Design/StorageConcurrency.md.
; ============================================================================
; For BakaShrot_SyncPair and BakaShrot_ReplicatedMessage.
XIncludeFile "../../Commons/Networking/Packets/SyncStatePacket.pbi"
XIncludeFile "../../Commons/Networking/Packets/ReplicateMessagesPacket.pbi"
CompilerSelect #PB_Compiler_OS
CompilerCase #PB_OS_Windows
#BakaShrot_Storage_ExternalSqlite = #True
#BakaShrot_Storage_SqliteLibrary = "sqlite3.dll"
CompilerCase #PB_OS_Linux
#BakaShrot_Storage_ExternalSqlite = #True
#BakaShrot_Storage_SqliteLibrary = "libsqlite3.so.0"
CompilerDefault
#BakaShrot_Storage_ExternalSqlite = #False
#BakaShrot_Storage_SqliteLibrary = ""
CompilerEndSelect
CompilerIf #BakaShrot_Storage_ExternalSqlite
UseSQLiteDatabase(#BakaShrot_Storage_SqliteLibrary)
CompilerElse
UseSQLiteDatabase()
CompilerEndIf
; One row of the "data" table (see db_schema_v8.dbml).
; PushedAt: when it was pushed, ms since 1970 UTC (Packets.pbi).
; AttachmentSize: its attachment's size, 0 for none (the "attachments"
; table), AttachmentReady #True once all of it is here, AttachmentSha256 its
; SHA-256.
Structure BakaShrot_Message
MessageId.q
PushedAt.q
JsonData.s
AttachmentSize.q
AttachmentReady.i
AttachmentSha256.a[#BakaShrot_Sha256Size]
EndStructure
CompilerIf #PB_Compiler_OS <> #PB_OS_Windows
ImportC ""
BakaShrot_GetTimeOfDay.l(*TimeVal, *TimeZone) As "gettimeofday"
EndImport
CompilerEndIf
; Now, in milliseconds since 1970-01-01 00:00:00 UTC: what a pushed message
; is stamped with (pushed_at).
Procedure.q BakaShrot_NowUtcMs()
CompilerIf #PB_Compiler_OS = #PB_OS_Windows
; 100 ns intervals since 1601-01-01 UTC.
Protected FileTime.q
GetSystemTimeAsFileTime_(@FileTime)
ProcedureReturn (FileTime - 116444736000000000) / 10000
CompilerElse
; struct timeval, 64-bit (checked on Linux x64 by Tests/Retention-Test.ps1).
Protected Dim TimeVal.q(1)
BakaShrot_GetTimeOfDay(@TimeVal(0), 0)
ProcedureReturn TimeVal(0) * 1000 + TimeVal(1) / 1000
CompilerEndIf
EndProcedure
; How long a connection waits for another one's lock before a statement
; fails with "database is locked", in ms.
#BakaShrot_Storage_BusyTimeout = 5000
; The database runs in WAL mode (set up by SetupStorageDatabase(), stored in
; the file): readers and the writer don't block each other anymore, so a
; long raw query no longer stalls every push.
; PRAGMA synchronous of every connection: [BakaShrot.Server] Synchronous,
; set by the root before it opens any (Server/Root.pbi). FULL by default.
; FULL syncs the WAL on every commit: an acknowledged push is on disk. It
; costs one flush per transaction, shared by a group commit's pushes.
; NORMAL only syncs at checkpoints (about every second, Writer.pbi): the
; database can't get corrupted, but the last commits before a power loss or
; an OS crash (not a crash of the server itself) can be lost. Those messages
; were acknowledged, and maybe replicated already, so their ids could then
; be handed out again for other messages: drift, see
; Design/ReplicationIssues.md #1. Measured: Design/StorageConcurrency.md.
#BakaShrot_Storage_DefaultSynchronous = "FULL"
Global BakaShrot_Storage_Synchronous.s = #BakaShrot_Storage_DefaultSynchronous
; Opens (and creates, if missing) the SQLite database at DatabasePath, as a
; new connection for the calling thread only.
; Returns the PureBasic database number, or 0 if the file could not be opened.
Procedure.i OpenStorageDatabase(DatabasePath.s)
Protected FileId.i, DbId.i
; PureBasic's SQLite driver refuses to open a file that doesn't exist,
; so an empty one has to be created first.
If FileSize(DatabasePath) = -1
FileId = CreateFile(#PB_Any, DatabasePath)
If Not FileId
ProcedureReturn 0
EndIf
CloseFile(FileId)
EndIf
DbId = OpenDatabase(#PB_Any, DatabasePath, "", "")
If Not DbId
ProcedureReturn 0
EndIf
; Without it, a write fails right away while another connection writes.
If Not DatabaseUpdate(DbId, "PRAGMA busy_timeout = " + Str(#BakaShrot_Storage_BusyTimeout))
CloseDatabase(DbId)
ProcedureReturn 0
EndIf
; Per connection, see BakaShrot_Storage_Synchronous.
If Not DatabaseUpdate(DbId, "PRAGMA synchronous = " + BakaShrot_Storage_Synchronous)
CloseDatabase(DbId)
ProcedureReturn 0
EndIf
ProcedureReturn DbId
EndProcedure
; Rebuilds the database file, reclaiming the space of deleted rows.
; Only run it from the root while every worker is stopped: it needs every
; other connection to be idle. See BakaShrot_Root_Vacuum() in Server/Root.pbi.
Procedure.i VacuumStorageDatabase(DbId.i)
ProcedureReturn DatabaseUpdate(DbId, "VACUUM")
EndProcedure
; #True if Table has a column named Column, #False if not (or no such table),
; -1 on failure.
Procedure.i StorageHasColumn(DbId.i, Table.s, Column.s)
Protected Found.i = #False
SetDatabaseString(DbId, 0, Table)
SetDatabaseString(DbId, 1, Column)
If Not DatabaseQuery(DbId, "SELECT COUNT(*) FROM pragma_table_info(?) WHERE name = ?")
ProcedureReturn -1
EndIf
If NextDatabaseRow(DbId)
Found = Bool(GetDatabaseLong(DbId, 0) > 0)
EndIf
FinishDatabaseQuery(DbId)
ProcedureReturn Found
EndProcedure
; v3 -> v4: "group_id" became "topic_id" in every table. Renames the
; columns of a database made before, in one transaction. The trigger and the
; attachements index are dropped, SetupStorageDatabase() makes them again
; with the new names. The UNIQUE and PRIMARY KEY indexes follow the columns.
; Nothing to do on a new or already renamed database.
Procedure.i MigrateStorageTopicIds(DbId.i)
Protected Table.s, Has.i, i.i
Has = StorageHasColumn(DbId, "data", "group_id")
If Has = -1
ProcedureReturn #False
ElseIf Not Has
ProcedureReturn #True
EndIf
If Not DatabaseUpdate(DbId, "BEGIN IMMEDIATE")
ProcedureReturn #False
EndIf
If Not DatabaseUpdate(DbId, "DROP TRIGGER IF EXISTS trg_data_node_heads") Or
Not DatabaseUpdate(DbId, "DROP INDEX IF EXISTS idx_attachements_group_node")
DatabaseUpdate(DbId, "ROLLBACK")
ProcedureReturn #False
EndIf
For i = 1 To 3
Table = StringField("data,node_heads,attachements", i, ",")
Has = StorageHasColumn(DbId, Table, "group_id")
If Has = -1 Or (Has And Not DatabaseUpdate(DbId, "ALTER TABLE " + Table + " RENAME COLUMN group_id TO topic_id"))
DatabaseUpdate(DbId, "ROLLBACK")
ProcedureReturn #False
EndIf
Next
If Not DatabaseUpdate(DbId, "COMMIT")
DatabaseUpdate(DbId, "ROLLBACK")
ProcedureReturn #False
EndIf
ProcedureReturn #True
EndProcedure
; v5 -> v6: "data" got pushed_at. Adds it to a database made before, every
; message stamped with the time of the upgrade (their real one is unknown),
; in one transaction. Nothing to do on a new or already upgraded database.
Procedure.i MigrateStoragePushedAt(DbId.i)
Protected Has.i
Has = StorageHasColumn(DbId, "data", "pushed_at")
If Has = -1
ProcedureReturn #False
ElseIf Has
ProcedureReturn #True
EndIf
If Not DatabaseUpdate(DbId, "BEGIN IMMEDIATE")
ProcedureReturn #False
EndIf
If Not DatabaseUpdate(DbId, "ALTER TABLE data ADD COLUMN pushed_at INTEGER NOT NULL DEFAULT 0")
DatabaseUpdate(DbId, "ROLLBACK")
ProcedureReturn #False
EndIf
; Bound for the next statement run, so right before it.
SetDatabaseQuad(DbId, 0, BakaShrot_NowUtcMs())
If Not DatabaseUpdate(DbId, "UPDATE data SET pushed_at = ?")
DatabaseUpdate(DbId, "ROLLBACK")
ProcedureReturn #False
EndIf
If Not DatabaseUpdate(DbId, "COMMIT")
DatabaseUpdate(DbId, "ROLLBACK")
ProcedureReturn #False
EndIf
ProcedureReturn #True
EndProcedure
; Creates the tables and indexes described by db_schema_v8.dbml, if they
; don't exist yet. Plain "CREATE IF NOT EXISTS" for now - a real versioned
; upgrade mechanism (DbUpdater) will replace this later.
; Fails on a database made with an older schema, since it would be left as is.
Procedure.i SetupStorageDatabase(DbId.i)
Protected JournalMode.s, HeadsExist.i
; Stored in the file, every later connection uses it. Fails while another
; connection has the database open, so only the root does it, at start.
If Not DatabaseQuery(DbId, "PRAGMA journal_mode = WAL")
ProcedureReturn #False
EndIf
If NextDatabaseRow(DbId)
JournalMode = LCase(GetDatabaseString(DbId, 0))
EndIf
FinishDatabaseQuery(DbId)
If JournalMode <> "wal"
ProcedureReturn #False
EndIf
; Before anything below, which uses the new names.
If Not MigrateStorageTopicIds(DbId)
ProcedureReturn #False
EndIf
; A leftover of the first schemas, never used: the retention deletes
; instead (Retention.pbi).
If Not DatabaseUpdate(DbId, "DROP TABLE IF EXISTS archives")
ProcedureReturn #False
EndIf
; is_json is set by SQLite on insert, and can't be written.
; pushed_at: when it was pushed to its origin, ms since 1970 UTC, kept as
; is when replicated. Last, like the ALTER TABLE below adds it.
; The UNIQUE constraint's index also serves (topic_id, node_id) lookups.
If Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS data (" +
"topic_id INTEGER NOT NULL, " +
"node_id INTEGER NOT NULL, " +
"message_id INTEGER NOT NULL, " +
"message_data TEXT NOT NULL, " +
"is_json INTEGER NOT NULL GENERATED ALWAYS AS (json_valid(message_data)) STORED, " +
"pushed_at INTEGER NOT NULL DEFAULT 0, " +
"UNIQUE (topic_id, node_id, message_id))")
ProcedureReturn #False
EndIf
; An older "data" table is kept by CREATE IF NOT EXISTS, its lack of
; is_json gives it away. Fails with "no such column: is_json".
If Not DatabaseQuery(DbId, "SELECT is_json FROM data LIMIT 0")
ProcedureReturn #False
EndIf
FinishDatabaseQuery(DbId)
If Not DatabaseUpdate(DbId, "CREATE INDEX IF NOT EXISTS idx_data_message_id ON data (message_id)")
ProcedureReturn #False
EndIf
; A database from before pushed_at: its messages get the time of this
; upgrade, so a topic's max age (Server/Storage/Retention.pbi) counts
; from now for them instead of deleting them all at once.
If Not MigrateStoragePushedAt(DbId)
ProcedureReturn #False
EndIf
; What the retention deletes by: a topic's messages pushed before a time.
If Not DatabaseUpdate(DbId, "CREATE INDEX IF NOT EXISTS idx_data_topic_pushed_at ON data (topic_id, pushed_at)")
ProcedureReturn #False
EndIf
; The first schemas' placeholder, never used (and misspelled), replaced
; by the three tables below. Its indexes go with it.
If Not DatabaseUpdate(DbId, "DROP TABLE IF EXISTS attachements")
ProcedureReturn #False
EndIf
; Attachments, see Attachments.pbi and Design/Attachments.md.
; blobs: an attachment's data, being uploaded or replicated, or stored.
; topic_id, node_id: an upload's, who may attach it (or the message's).
; received: bytes stored so far, in blob_chunks.
; state: 0 receiving, 1 complete (an upload waiting for its message),
; 2 attached to its message, 3 to delete (Retention.pbi deletes it).
; created_at: ms since 1970 UTC, uploads left incomplete expire.
; blob_chunks: its parts, #BakaShrot_AttachmentChunkSize bytes each.
; attachments: a message's (one at most), with its size and SHA-256
; from the start, its data in blob_id once any is here.
; state: 0 missing (a replicated message, none of it here yet),
; 1 receiving, 2 ready, 3 not kept (bigger than this server takes).
If Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS blobs (" +
"blob_id INTEGER PRIMARY KEY, " +
"topic_id INTEGER NOT NULL, " +
"node_id INTEGER NOT NULL, " +
"size INTEGER NOT NULL, " +
"sha256 BLOB NOT NULL, " +
"received INTEGER NOT NULL DEFAULT 0, " +
"state INTEGER NOT NULL, " +
"created_at INTEGER NOT NULL)") Or
Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS blob_chunks (" +
"blob_id INTEGER NOT NULL, " +
"chunk_index INTEGER NOT NULL, " +
"chunk_data BLOB NOT NULL, " +
"PRIMARY KEY (blob_id, chunk_index))") Or
Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS attachments (" +
"topic_id INTEGER NOT NULL, " +
"node_id INTEGER NOT NULL, " +
"message_id INTEGER NOT NULL, " +
"size INTEGER NOT NULL, " +
"sha256 BLOB NOT NULL, " +
"blob_id INTEGER, " +
"state INTEGER NOT NULL, " +
"PRIMARY KEY (topic_id, node_id, message_id)) WITHOUT ROWID") Or
Not DatabaseUpdate(DbId, "CREATE INDEX IF NOT EXISTS idx_blobs_state ON blobs (state)") Or
Not DatabaseUpdate(DbId, "CREATE INDEX IF NOT EXISTS idx_attachments_state ON attachments (state)")
ProcedureReturn #False
EndIf
; A message deleted (the retention) takes its attachment with it, and an
; attachment its data: marked, Retention.pbi deletes it a bit at a time.
If Not DatabaseUpdate(DbId, "CREATE TRIGGER IF NOT EXISTS trg_data_attachments AFTER DELETE ON data BEGIN " +
"DELETE FROM attachments WHERE topic_id = OLD.topic_id AND node_id = OLD.node_id AND message_id = OLD.message_id; " +
"END") Or
Not DatabaseUpdate(DbId, "CREATE TRIGGER IF NOT EXISTS trg_attachments_blobs AFTER DELETE ON attachments WHEN OLD.blob_id IS NOT NULL BEGIN " +
"UPDATE blobs SET state = 3 WHERE blob_id = OLD.blob_id; " +
"END")
ProcedureReturn #False
EndIf
; The highest message id of every topic/node id, kept by a trigger on
; every insert, whoever does it. The sync state comes from it instead of
; a GROUP BY over every message (131 ms at 1.9M rows, on every check-in).
; Filled from "data" when it's created on an existing database.
; Deleting from "data" (the retention) leaves it alone, on purpose: a
; pair's head stays its highest id ever, so the next push still gets the
; id after it, and peers aren't sent again what was deleted here.
If Not DatabaseQuery(DbId, "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'node_heads'")
ProcedureReturn #False
EndIf
HeadsExist = #False
If NextDatabaseRow(DbId)
HeadsExist = Bool(GetDatabaseLong(DbId, 0) > 0)
EndIf
FinishDatabaseQuery(DbId)
If Not HeadsExist
If Not DatabaseUpdate(DbId, "BEGIN IMMEDIATE")
ProcedureReturn #False
EndIf
If Not DatabaseUpdate(DbId, "CREATE TABLE node_heads (" +
"topic_id INTEGER NOT NULL, " +
"node_id INTEGER NOT NULL, " +
"max_message_id INTEGER NOT NULL, " +
"PRIMARY KEY (topic_id, node_id)) WITHOUT ROWID") Or
Not DatabaseUpdate(DbId, "INSERT INTO node_heads (topic_id, node_id, max_message_id) " +
"SELECT topic_id, node_id, MAX(message_id) FROM data GROUP BY topic_id, node_id")
DatabaseUpdate(DbId, "ROLLBACK")
ProcedureReturn #False
EndIf
If Not DatabaseUpdate(DbId, "COMMIT")
DatabaseUpdate(DbId, "ROLLBACK")
ProcedureReturn #False
EndIf
EndIf
; Only fires for rows actually inserted, not the ones INSERT OR IGNORE drops.
If Not DatabaseUpdate(DbId, "CREATE TRIGGER IF NOT EXISTS trg_data_node_heads AFTER INSERT ON data BEGIN " +
"INSERT INTO node_heads (topic_id, node_id, max_message_id) VALUES (NEW.topic_id, NEW.node_id, NEW.message_id) " +
"ON CONFLICT (topic_id, node_id) DO UPDATE SET max_message_id = MAX(max_message_id, excluded.max_message_id); " +
"END")
ProcedureReturn #False
EndIf
; Every topic and node id in "data" has a row, with its name, or its id
; in digits if it has none. origin: "config" (named in the config),
; "peer" (a node a peer sent messages of, given an id here), "id"
; (unnamed). Kept up to date by Server/Storage/Names.pbi.
; No foreign keys from "data": see Notes.md, a replicated batch would
; fail as a whole on an unknown id.
If Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS topics (" +
"topic_id INTEGER PRIMARY KEY, " +
"name TEXT NOT NULL UNIQUE COLLATE NOCASE, " +
"origin TEXT NOT NULL)") Or
Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS nodes (" +
"node_id INTEGER PRIMARY KEY, " +
"name TEXT NOT NULL UNIQUE COLLATE NOCASE, " +
"origin TEXT NOT NULL)")
ProcedureReturn #False
EndIf
; For queries by name: SELECT * FROM messages WHERE topic = 'logs' AND
; node = 'kitchen' still goes through the indexes. pushed_utc is
; pushed_at as text, "2026-11-08T14:03:59.123Z".
; Made again on every start, so an older one gets the newer columns.
If Not DatabaseUpdate(DbId, "DROP VIEW IF EXISTS messages") Or
Not DatabaseUpdate(DbId, "CREATE VIEW messages AS " +
"SELECT t.name AS topic, n.name AS node, d.message_id, d.message_data, d.is_json, d.topic_id, d.node_id, " +
"d.pushed_at, strftime('%Y-%m-%dT%H:%M:%fZ', d.pushed_at / 1000.0, 'unixepoch') AS pushed_utc " +
"FROM data d JOIN topics t ON t.topic_id = d.topic_id JOIN nodes n ON n.node_id = d.node_id")
ProcedureReturn #False
EndIf
; For browsing with a database tool: set browse's one row to a topic
; (and optionally a node), open browse_messages. The foreign keys are
; only there for the tools: SQLiteStudio shows a dropdown of the names
; for a column that references them. The server never turns foreign keys
; on, so they never get in its way (a topic renamed in the config only
; leaves a stale name here). The server never writes to browse either.
If Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS browse (" +
"id INTEGER PRIMARY KEY CHECK (id = 1), " +
"topic TEXT COLLATE NOCASE REFERENCES topics (name), " +
"node TEXT COLLATE NOCASE REFERENCES nodes (name))") Or
Not DatabaseUpdate(DbId, "INSERT OR IGNORE INTO browse (id) VALUES (1)")
ProcedureReturn #False
EndIf
; Newest first, by the (topic_id, pushed_at) index. Made again on every
; start, like messages.
If Not DatabaseUpdate(DbId, "DROP VIEW IF EXISTS browse_messages") Or
Not DatabaseUpdate(DbId, "CREATE VIEW browse_messages AS " +
"SELECT m.node, m.message_id, m.pushed_utc, m.message_data, m.is_json, " +
"a.size AS attachment_size, m.topic " +
"FROM browse b JOIN messages m ON m.topic = b.topic " +
"LEFT JOIN attachments a ON a.topic_id = m.topic_id AND a.node_id = m.node_id AND a.message_id = m.message_id " +
"WHERE b.id = 1 AND (b.node IS NULL OR m.node = b.node) " +
"ORDER BY m.pushed_at DESC, m.node, m.message_id DESC")
ProcedureReturn #False
EndIf
ProcedureReturn #True
EndProcedure
; Inserts one JSON message into the "data" table, pushed now.
Procedure.i Insert(DbId.i, TopicId.i, NodeId.i, MessageId.i, JsonData.s)
SetDatabaseLong(DbId, 0, TopicId)
SetDatabaseLong(DbId, 1, NodeId)
SetDatabaseLong(DbId, 2, MessageId)
SetDatabaseString(DbId, 3, JsonData)
SetDatabaseQuad(DbId, 4, BakaShrot_NowUtcMs())
ProcedureReturn DatabaseUpdate(DbId, "INSERT INTO data (topic_id, node_id, message_id, message_data, pushed_at) VALUES (?, ?, ?, ?, ?)")
EndProcedure
; Gets every message stored for a given topic_id/node_id pair - the
; "(topic_id, node_id)" index - ordered by message_id.
Procedure.i GetMessagesByTopicAndNode(DbId.i, TopicId.i, NodeId.i, List Messages.BakaShrot_Message())
ClearList(Messages())
SetDatabaseLong(DbId, 0, TopicId)
SetDatabaseLong(DbId, 1, NodeId)
If Not DatabaseQuery(DbId, "SELECT message_id, message_data FROM data WHERE topic_id = ? AND node_id = ? ORDER BY message_id")
ProcedureReturn #False
EndIf
While NextDatabaseRow(DbId)
AddElement(Messages())
Messages()\MessageId = GetDatabaseLong(DbId, 0)
Messages()\JsonData = GetDatabaseString(DbId, 1)
Wend
FinishDatabaseQuery(DbId)
ProcedureReturn #True
EndProcedure
; Gets every message stored under a given message_id, regardless of which
; topic/node it belongs to - the standalone "message_id" index.
Procedure.i GetMessagesByMessageId(DbId.i, MessageId.i, List Messages.BakaShrot_Message())
ClearList(Messages())
SetDatabaseLong(DbId, 0, MessageId)
If Not DatabaseQuery(DbId, "SELECT message_id, message_data FROM data WHERE message_id = ?")
ProcedureReturn #False
EndIf
While NextDatabaseRow(DbId)
AddElement(Messages())
Messages()\MessageId = GetDatabaseLong(DbId, 0)
Messages()\JsonData = GetDatabaseString(DbId, 1)
Wend
FinishDatabaseQuery(DbId)
ProcedureReturn #True
EndProcedure
; Test helper: scans every stored message and collects the value found at
; JsonPath (e.g. "$.messageData.MsgType"), skipping messages where it's
; missing or null, and those that aren't JSON (is_json = 0: ->> fails the
; whole query on one). Kept basic on purpose - no paging, no topic/node filter.
Procedure.i GetValuesAtJsonPath(DbId.i, JsonPath.s, List Values.s())
ClearList(Values())
SetDatabaseString(DbId, 0, JsonPath)
SetDatabaseString(DbId, 1, JsonPath)
If Not DatabaseQuery(DbId, "SELECT message_data ->> ? FROM data WHERE is_json = 1 AND message_data ->> ? IS NOT NULL")
ProcedureReturn #False
EndIf
While NextDatabaseRow(DbId)
AddElement(Values())
Values() = GetDatabaseString(DbId, 0)
Wend
FinishDatabaseQuery(DbId)
ProcedureReturn #True
EndProcedure
; Returns the highest message_id stored for a given topic_id/node_id pair,
; or -1 if there's none yet. Will likely grow into a cached counter later.
Procedure.i GetLatestMessageId(DbId.i, TopicId.i, NodeId.i)
Protected MessageId.i = -1
SetDatabaseLong(DbId, 0, TopicId)
SetDatabaseLong(DbId, 1, NodeId)
If DatabaseQuery(DbId, "SELECT COALESCE(MAX(message_id), -1) FROM data WHERE topic_id = ? AND node_id = ?")
If NextDatabaseRow(DbId)
MessageId = GetDatabaseLong(DbId, 0)
EndIf
FinishDatabaseQuery(DbId)
EndIf
ProcedureReturn MessageId
EndProcedure
; Reads the attachment's size, state and SHA-256 (COALESCE(a.size, 0),
; COALESCE(a.state, 0), a.sha256) from Column on into *Message.
Procedure BakaShrot_ReadAttachmentColumns(DbId.i, Column.i, *Message.BakaShrot_Message)
*Message\AttachmentSize = GetDatabaseQuad(DbId, Column)
*Message\AttachmentReady = Bool(*Message\AttachmentSize > 0 And GetDatabaseLong(DbId, Column + 1) = 2)
FillMemory(@*Message\AttachmentSha256[0], #BakaShrot_Sha256Size, 0)
If *Message\AttachmentSize > 0 And DatabaseColumnSize(DbId, Column + 2) = #BakaShrot_Sha256Size
GetDatabaseBlob(DbId, Column + 2, @*Message\AttachmentSha256[0], #BakaShrot_Sha256Size)
EndIf
EndProcedure
; Fills *Message with the message that has the highest message_id for a
; topic_id/node_id pair.
; Returns #False if there's none, or if the query failed.
Procedure.i GetLatestMessage(DbId.i, TopicId.i, NodeId.i, *Message.BakaShrot_Message)
Protected Found.i
SetDatabaseLong(DbId, 0, TopicId)
SetDatabaseLong(DbId, 1, NodeId)
If Not DatabaseQuery(DbId, "SELECT d.message_id, d.message_data, d.pushed_at, COALESCE(a.size, 0), COALESCE(a.state, 0), a.sha256 " +
"FROM data d LEFT JOIN attachments a ON a.topic_id = d.topic_id AND a.node_id = d.node_id AND a.message_id = d.message_id " +
"WHERE d.topic_id = ? AND d.node_id = ? ORDER BY d.message_id DESC LIMIT 1")
ProcedureReturn #False
EndIf
Found = NextDatabaseRow(DbId)
If Found
*Message\MessageId = GetDatabaseQuad(DbId, 0)
*Message\JsonData = GetDatabaseString(DbId, 1)
*Message\PushedAt = GetDatabaseQuad(DbId, 2)
BakaShrot_ReadAttachmentColumns(DbId, 3, *Message)
EndIf
FinishDatabaseQuery(DbId)
ProcedureReturn Found
EndProcedure
; --- Raw queries -------------------------------------------------------------
; Most rows a raw query can return.
#BakaShrot_Query_MaxRows = 10000
; Telling the end of a query's rows from an error that cut them short.
; PureBasic's NextDatabaseRow() returns #False for both, and DatabaseError()
; stays empty after such an error: a JSON function (->>, json_extract())
; reaching a row that isn't JSON stops the query with "malformed JSON", and
; the query looked like it simply had no (more) rows. So once the rows end,
; SQLite itself is asked: sqlite3_errcode() on the connection is SQLITE_DONE
; (or SQLITE_ROW/SQLITE_OK) if they really ended, the error otherwise, with
; sqlite3_errmsg16() telling which. Same #BakaShrot_Storage_SqliteLibrary as
; PureBasic's (DatabaseID() is its sqlite3 handle), like Writer.pbi.
; Without #BakaShrot_Storage_ExternalSqlite, PureBasic's own SQLite is linked
; in and not reachable this way: DatabaseError() is checked instead, which
; misses it.
#BakaShrot_Query_SqliteOk = 0
#BakaShrot_Query_SqliteRow = 100
#BakaShrot_Query_SqliteDone = 101
CompilerIf #BakaShrot_Storage_ExternalSqlite
PrototypeC.l BakaShrot_Query_SqliteErrCode(Db.i)
PrototypeC.i BakaShrot_Query_SqliteErrMsg16(Db.i)
Structure BakaShrot_Query_SqliteApi
Library.i
ErrCode.BakaShrot_Query_SqliteErrCode
ErrMsg16.BakaShrot_Query_SqliteErrMsg16
EndStructure
Global BakaShrot_Query_Sqlite.BakaShrot_Query_SqliteApi
; Queries run on every client's thread, the first one loads it.
Global BakaShrot_Query_SqliteMutex.i = CreateMutex()
; Returns #False if the SQLite library or its functions can't be found.
Procedure.i BakaShrot_Query_LoadSqlite()
Protected Loaded.i
LockMutex(BakaShrot_Query_SqliteMutex)
With BakaShrot_Query_Sqlite
If Not \Library
\Library = OpenLibrary(#PB_Any, #BakaShrot_Storage_SqliteLibrary)
If \Library
\ErrCode = GetFunction(\Library, "sqlite3_errcode")
\ErrMsg16 = GetFunction(\Library, "sqlite3_errmsg16")
If Not \ErrCode Or Not \ErrMsg16
CloseLibrary(\Library)
\Library = 0
EndIf
EndIf
EndIf
Loaded = Bool(\Library)
EndWith
UnlockMutex(BakaShrot_Query_SqliteMutex)
ProcedureReturn Loaded
EndProcedure
CompilerEndIf
; Runs a raw SQL query from a client, read-only, and fills *Result\s with its
; rows as JSON: {"columns": ["name", ...], "rows": [["value", ...], ...]}.
; Every value is a string, or null for NULL: PureBasic reports no column
; types for SQLite. Wrap a blob in hex() to read it.
;
; Read-only, enforced three ways:
; 1. It must start with SELECT or WITH.
; 2. It runs on its own connection to DatabasePath, opened just for it,
; with PRAGMA query_only = ON. Writes fail, even WITH ... DELETE, and a
; query that turns the pragma off only does so for its own connection.
; 3. Only the first statement runs, anything after a ";" is ignored.
;
; An error while reading the rows fails the whole query, with SQLite's
; message: a JSON function on a row that isn't JSON gives "malformed JSON",
; add "is_json = 1" to the WHERE. Never a partial or empty result instead.
;
; Thread-safe, since it never touches a shared handle.
; Returns #False with *Error\s set if it's refused, fails, or has more than
; #BakaShrot_Query_MaxRows rows.
Procedure.i RunReadOnlyQuery(DatabasePath.s, Sql.s, *Result.String, *Error.String)
Protected DbId.i, JsonId.i, *Root, *Columns, *Rows, *Row
Protected Column.i, RowCount.i, Start.s, ErrorCode.l
Start = UCase(Trim(ReplaceString(ReplaceString(ReplaceString(Sql, #CR$, " "), #LF$, " "), #TAB$, " ")))
If Left(Start, 6) <> "SELECT" And Left(Start, 4) <> "WITH"
*Error\s = "Only SELECT and WITH queries are allowed"
ProcedureReturn #False
EndIf
; Without it, errors in the rows would go unnoticed: refused instead.
CompilerIf #BakaShrot_Storage_ExternalSqlite
If Not BakaShrot_Query_LoadSqlite()
*Error\s = "Queries can't be checked for errors: sqlite3_errcode() not found"
ProcedureReturn #False
EndIf
CompilerEndIf
DbId = OpenStorageDatabase(DatabasePath)
If Not DbId
*Error\s = "The database couldn't be opened"
ProcedureReturn #False
EndIf
If Not DatabaseUpdate(DbId, "PRAGMA query_only = ON")
*Error\s = "The database couldn't be made read-only"
CloseDatabase(DbId)
ProcedureReturn #False
EndIf
If Not DatabaseQuery(DbId, Sql)
*Error\s = DatabaseError()
CloseDatabase(DbId)
ProcedureReturn #False
EndIf
; WITH ... DELETE and the likes have no columns. query_only stops them
; anyway, but PureBasic doesn't report that, they'd look like no rows.
If DatabaseColumns(DbId) = 0
*Error\s = "The query doesn't return any column, only SELECT queries are allowed"
FinishDatabaseQuery(DbId)
CloseDatabase(DbId)
ProcedureReturn #False
EndIf
JsonId = CreateJSON(#PB_Any)
If Not JsonId
*Error\s = "Out of memory"
FinishDatabaseQuery(DbId)
CloseDatabase(DbId)
ProcedureReturn #False
EndIf
*Root = SetJSONObject(JSONValue(JsonId))
*Columns = SetJSONArray(AddJSONMember(*Root, "columns"))
For Column = 0 To DatabaseColumns(DbId) - 1
SetJSONString(AddJSONElement(*Columns), DatabaseColumnName(DbId, Column))
Next
*Rows = SetJSONArray(AddJSONMember(*Root, "rows"))
While NextDatabaseRow(DbId)
RowCount + 1
If RowCount > #BakaShrot_Query_MaxRows
*Error\s = "More than " + Str(#BakaShrot_Query_MaxRows) + " rows, add a LIMIT"
FreeJSON(JsonId)
FinishDatabaseQuery(DbId)
CloseDatabase(DbId)
ProcedureReturn #False
EndIf
*Row = SetJSONArray(AddJSONElement(*Rows))
For Column = 0 To DatabaseColumns(DbId) - 1
If CheckDatabaseNull(DbId, Column)
SetJSONNull(AddJSONElement(*Row))
Else
SetJSONString(AddJSONElement(*Row), GetDatabaseString(DbId, Column))
EndIf
Next
Wend
; Did the rows end, or did an error end them? (see above): "malformed
; JSON", a write stopped by query_only (DELETE ... RETURNING), ...
; Asked before FinishDatabaseQuery(), while the failed step is the last
; thing done on this connection. A false alarm would refuse a good
; query, it can't hide a bad one.
CompilerIf #BakaShrot_Storage_ExternalSqlite
ErrorCode = BakaShrot_Query_Sqlite\ErrCode(DatabaseID(DbId))
If ErrorCode <> #BakaShrot_Query_SqliteOk And ErrorCode <> #BakaShrot_Query_SqliteRow And ErrorCode <> #BakaShrot_Query_SqliteDone
*Error\s = PeekS(BakaShrot_Query_Sqlite\ErrMsg16(DatabaseID(DbId)), -1, #PB_Unicode)
If *Error\s = ""
*Error\s = "SQLite error " + Str(ErrorCode)
EndIf
If FindString(*Error\s, "JSON", 1, #PB_String_NoCase)
*Error\s + " (a row isn't JSON: add is_json = 1 to the WHERE)"
EndIf
FreeJSON(JsonId)
FinishDatabaseQuery(DbId)
CloseDatabase(DbId)
ProcedureReturn #False
EndIf
CompilerEndIf
FinishDatabaseQuery(DbId)
; Without #BakaShrot_Storage_ExternalSqlite, the only check there is. It
; misses errors in the rows: PureBasic doesn't report them.
; !!! DatabaseError() may be shared by every thread, see
; !!! Design/StorageConcurrency.md, another thread's error could show up here.
CompilerIf Not #BakaShrot_Storage_ExternalSqlite
If DatabaseError() <> ""
*Error\s = DatabaseError()
FreeJSON(JsonId)
CloseDatabase(DbId)
ProcedureReturn #False
EndIf
CompilerEndIf
*Result\s = ComposeJSON(JsonId)
FreeJSON(JsonId)
CloseDatabase(DbId)
ProcedureReturn #True
EndProcedure
; --- Replication -------------------------------------------------------------
; Fills Pairs() with where this node is at: the highest message id it has for
; every topic/node id combination, ordered by topic then node id. Read from
; node_heads, kept up to date by a trigger, see SetupStorageDatabase().
; Returns #False if the query failed.
Procedure.i GetSyncState(DbId.i, List Pairs.BakaShrot_SyncPair())
ClearList(Pairs())
If Not DatabaseQuery(DbId, "SELECT topic_id, node_id, max_message_id FROM node_heads ORDER BY topic_id, node_id")
ProcedureReturn #False
EndIf
While NextDatabaseRow(DbId)
AddElement(Pairs())
Pairs()\TopicId = GetDatabaseLong(DbId, 0)
Pairs()\NodeId = GetDatabaseLong(DbId, 1)
Pairs()\MessageId = GetDatabaseQuad(DbId, 2)
Wend
FinishDatabaseQuery(DbId)
ProcedureReturn #True
EndProcedure
; Fills Messages() with up to Limit messages of a topic/node id combination
; whose message_id is above AfterMessageId, in message_id order. Stops early
; once their JSON adds up to MaxChars characters or more (0: no such limit),
; the one that got there included, so big messages aren't all read at once.
; If *More is given, *More\i is set to #True if more messages follow the
; last one read.
; Returns #False if the query failed.
Procedure.i GetMessagesAfter(DbId.i, TopicId.i, NodeId.i, AfterMessageId.q, Limit.i, MaxChars.i, List Messages.BakaShrot_Message(), *More.Integer = 0)
Protected Chars.i, More.i
ClearList(Messages())
; One more than asked for, to tell if more follow.
SetDatabaseLong(DbId, 0, TopicId)
SetDatabaseLong(DbId, 1, NodeId)
SetDatabaseQuad(DbId, 2, AfterMessageId)
SetDatabaseLong(DbId, 3, Limit + 1)
If Not DatabaseQuery(DbId, "SELECT d.message_id, d.message_data, d.pushed_at, COALESCE(a.size, 0), COALESCE(a.state, 0), a.sha256 " +
"FROM data d LEFT JOIN attachments a ON a.topic_id = d.topic_id AND a.node_id = d.node_id AND a.message_id = d.message_id " +
"WHERE d.topic_id = ? AND d.node_id = ? AND d.message_id > ? ORDER BY d.message_id LIMIT ?")
ProcedureReturn #False
EndIf
While NextDatabaseRow(DbId)
If ListSize(Messages()) >= Limit Or (MaxChars > 0 And Chars >= MaxChars)
More = #True
Break
EndIf
AddElement(Messages())
Messages()\MessageId = GetDatabaseQuad(DbId, 0)
Messages()\JsonData = GetDatabaseString(DbId, 1)
Messages()\PushedAt = GetDatabaseQuad(DbId, 2)
BakaShrot_ReadAttachmentColumns(DbId, 3, @Messages())
Chars + Len(Messages()\JsonData)
Wend
FinishDatabaseQuery(DbId)
If *More
*More\i = More
EndIf
ProcedureReturn #True
EndProcedure
; Stores a message replicated from a peer, under the ids it has on its origin.
; If that topic/node/message id is already stored, it's kept as is, and the
; new one is dropped, even if it differs. See Design/ReplicationIssues.md.
; On its own connection: for tools writing while the server is stopped
; (BenchSeed). The server itself writes through Writer.pbi.
; PushedAt: when it was pushed to its origin, ms since 1970 UTC.
; Returns #False if the insert failed.
Procedure.i InsertReplicatedMessage(DbId.i, TopicId.i, NodeId.i, MessageId.q, JsonData.s, PushedAt.q)
SetDatabaseLong(DbId, 0, TopicId)
SetDatabaseLong(DbId, 1, NodeId)
SetDatabaseQuad(DbId, 2, MessageId)
SetDatabaseString(DbId, 3, JsonData)
SetDatabaseQuad(DbId, 4, PushedAt)
ProcedureReturn DatabaseUpdate(DbId, "INSERT OR IGNORE INTO data (topic_id, node_id, message_id, message_data, pushed_at) VALUES (?, ?, ?, ?, ?)")
EndProcedure
; Every write: pushes (group commit), replicated batches, the WAL checkpoints.
XIncludeFile "Writer.pbi"
; Attachments: uploads, parts, reading them back, the replicated ones.
XIncludeFile "Attachments.pbi"
; Usage example. Only compiled when this file is run directly (F5 in the
; IDE), not when it's included as a module by the rest of the project.
CompilerIf #PB_Compiler_IsMainFile
Define DbId = OpenStorageDatabase("storage.sqlite")
If DbId
If SetupStorageDatabase(DbId)
Insert(DbId, 1, 1, 1, ~"{\"messageData\": {\"MsgType\": \"hello\"}}")
Insert(DbId, 1, 1, 2, ~"{\"messageData\": {\"MsgType\": \"world\"}}")
NewList Messages.BakaShrot_Message()
GetMessagesByTopicAndNode(DbId, 1, 1, Messages())
ForEach Messages()
Debug "Message #" + Str(Messages()\MessageId) + ": " + Messages()\JsonData
Next
NewList MsgTypes.s()
GetValuesAtJsonPath(DbId, "$.messageData.MsgType", MsgTypes())
ForEach MsgTypes()
Debug "MsgType: " + MsgTypes()
Next
Debug "Latest message id: " + Str(GetLatestMessageId(DbId, 1, 1))
Else
Debug "Failed to set up database: " + DatabaseError()
EndIf
CloseDatabase(DbId)
Else
Debug "Failed to open database: " + DatabaseError()
EndIf
CompilerEndIf
File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More