From 12fbe5f4daaa0dd841b1459cb4ed4cfe1e7b9182 Mon Sep 17 00:00:00 2001 From: Herwin Bozet Date: Sun, 8 Nov 2026 13:16:37 +0100 Subject: [PATCH] Got close to the final version comitting Claude's code before the last mile improvements --- .gitignore | 11 + Build.ps1 | 334 ++++ Client/BakaShrot_Client.pbi | 1098 +++++++++++++ Client/BakaShrot_Client.pbi.cfg | 7 + Client/BakaShrot_Client_Prototypes.pbi | 335 ++++ Client/notes.txt | 4 + Commons/Cryptography/Cipher.pbi | 238 +++ Commons/Cryptography/Libsodium.pbi | 102 +- Commons/Cryptography/Session.pbi | 186 +++ Commons/Networking/Connections.pbi | 405 ++++- Commons/Networking/Names.pbi | 152 ++ Commons/Networking/Outbound.pbi | 329 ++++ Commons/Networking/Packets.pbi | 138 +- .../Networking/Packets/AuthAcceptedPacket.pbi | 65 + .../Packets/AuthenticationPacket.pbi | 303 ---- .../Packets/ChallengeRequestPacket.pbi | 131 ++ .../Packets/ChallengeResponsePacket.pbi | 101 ++ .../Packets/GetLatestMessagePacket.pbi | 99 ++ .../Networking/Packets/GetMessagesPacket.pbi | 138 ++ Commons/Networking/Packets/HelloPacket.pbi | 130 ++ .../Packets/LatestMessagePacket.pbi | 157 ++ .../Networking/Packets/ListNamesPacket.pbi | 87 ++ .../Packets/MessagePushedPacket.pbi | 82 + Commons/Networking/Packets/MessagesPacket.pbi | 219 +++ .../Networking/Packets/NameResolvedPacket.pbi | 116 ++ .../Networking/Packets/NamesListPacket.pbi | 177 +++ .../Networking/Packets/PushMessagePacket.pbi | 101 ++ .../Networking/Packets/QueryRequestPacket.pbi | 84 + .../Networking/Packets/QueryResultPacket.pbi | 84 + .../Packets/ReplicateMessagesPacket.pbi | 177 +++ .../Packets/RequestRefusedPacket.pbi | 83 + .../Networking/Packets/ResolveNamePacket.pbi | 107 ++ .../Networking/Packets/SyncStatePacket.pbi | 279 ++++ .../Packets/SyncStateRequestPacket.pbi | 65 + Commons/Networking/SocketWait.pbi | 124 ++ Commons/Threading/Signal.pbi | 69 + Core/Config/Config.pbi | 260 ---- Core/Config/schema.ini | 56 - Core/Storage/Storage.pbi | 203 --- Design/Cryptography.md | 225 +++ Design/Packets.md | 313 ++++ Design/Release.md | 235 +++ Design/ReplicationIssues.md | 168 ++ Design/StorageConcurrency.md | 148 ++ Design/Suggestions.md | 125 ++ Interactors/Python/bakashrot.py | 451 ++++++ Interactors/Python/check_bakashrot.py | 168 ++ Interactors/Python/example.py | 42 + Interactors/Python/notes.txt | 2 + Libs/redist/README.md | 26 + Libs/redist/x64/vcruntime140.dll | Bin 0 -> 178616 bytes Notes.md | 368 +++++ Release.ps1 | 336 ++++ Server/BakaShrot_Server.pb | 108 ++ Server/BakaShrot_Server.pb.cfg | 8 + Server/Config/Config.pbi | 893 +++++++++++ {Core => Server}/Config/Config.pbi.cfg | 0 Server/Config/schema.ini | 149 ++ {Core => Server}/Config/schema_out.ini | 6 +- Server/Networking/Networking.pbi | 1318 ++++++++++++++++ Server/Networking/Networking.pbi.cfg | 7 + Server/Networking/Peers.pbi | 568 +++++++ Server/Root.pbi | 207 +++ Server/Storage/Names.pbi | 484 ++++++ Server/Storage/Storage.pbi | 751 +++++++++ Server/Storage/Writer.pbi | 783 ++++++++++ {Core => Server}/Storage/db_schema_v0.dbml | 0 {Core => Server}/Storage/db_schema_v1.dbml | 0 Server/Storage/db_schema_v2.dbml | 45 + Server/Storage/db_schema_v3.dbml | 62 + Server/Storage/db_schema_v4.dbml | 61 + Server/Storage/db_schema_v5.dbml | 88 ++ Tests/Bench/Bench-Replication.ps1 | 658 ++++++++ Tests/Bench/BenchClient.pb | 1356 +++++++++++++++++ Tests/Bench/BenchSeed.pb | 181 +++ Tests/Bench/BenchServer.pb | 58 + Tests/Bench/Compare-Runs.ps1 | 106 ++ Tests/Bench/Results-2026-11-07.md | 182 +++ Tests/Bench/queries.txt | 30 + Tests/Bench/queries_load.txt | 13 + Tests/BigMessages-Test.ps1 | 336 ++++ Tests/CipherTest.pb | 387 +++++ Tests/GetMessages-Test.ps1 | 250 +++ Tests/HandshakeTest.pb | 162 ++ Tests/Names-Test.ps1 | 283 ++++ Tests/Python-Test.ps1 | 116 ++ Tests/wire_check.py | 144 ++ Tools/Common/ToolClient.pbi | 133 ++ Tools/GetLatestMessage/GetLatestMessage.pb | 62 + Tools/GetMessages/GetMessages.pb | 180 +++ Tools/KeyGen/KeyGen.pb | 50 + Tools/ListNames/ListNames.pb | 96 ++ Tools/PushMessage/PushMessage.pb | 80 + Tools/Query/Query.pb | 58 + Tools/Resolve/Resolve.pb | 69 + 95 files changed, 19130 insertions(+), 841 deletions(-) create mode 100644 Build.ps1 create mode 100644 Client/BakaShrot_Client.pbi create mode 100644 Client/BakaShrot_Client.pbi.cfg create mode 100644 Client/BakaShrot_Client_Prototypes.pbi create mode 100644 Client/notes.txt create mode 100644 Commons/Cryptography/Cipher.pbi create mode 100644 Commons/Cryptography/Session.pbi create mode 100644 Commons/Networking/Names.pbi create mode 100644 Commons/Networking/Outbound.pbi create mode 100644 Commons/Networking/Packets/AuthAcceptedPacket.pbi delete mode 100644 Commons/Networking/Packets/AuthenticationPacket.pbi create mode 100644 Commons/Networking/Packets/ChallengeRequestPacket.pbi create mode 100644 Commons/Networking/Packets/ChallengeResponsePacket.pbi create mode 100644 Commons/Networking/Packets/GetLatestMessagePacket.pbi create mode 100644 Commons/Networking/Packets/GetMessagesPacket.pbi create mode 100644 Commons/Networking/Packets/HelloPacket.pbi create mode 100644 Commons/Networking/Packets/LatestMessagePacket.pbi create mode 100644 Commons/Networking/Packets/ListNamesPacket.pbi create mode 100644 Commons/Networking/Packets/MessagePushedPacket.pbi create mode 100644 Commons/Networking/Packets/MessagesPacket.pbi create mode 100644 Commons/Networking/Packets/NameResolvedPacket.pbi create mode 100644 Commons/Networking/Packets/NamesListPacket.pbi create mode 100644 Commons/Networking/Packets/PushMessagePacket.pbi create mode 100644 Commons/Networking/Packets/QueryRequestPacket.pbi create mode 100644 Commons/Networking/Packets/QueryResultPacket.pbi create mode 100644 Commons/Networking/Packets/ReplicateMessagesPacket.pbi create mode 100644 Commons/Networking/Packets/RequestRefusedPacket.pbi create mode 100644 Commons/Networking/Packets/ResolveNamePacket.pbi create mode 100644 Commons/Networking/Packets/SyncStatePacket.pbi create mode 100644 Commons/Networking/Packets/SyncStateRequestPacket.pbi create mode 100644 Commons/Networking/SocketWait.pbi create mode 100644 Commons/Threading/Signal.pbi delete mode 100644 Core/Config/Config.pbi delete mode 100644 Core/Config/schema.ini delete mode 100644 Core/Storage/Storage.pbi create mode 100644 Design/Cryptography.md create mode 100644 Design/Packets.md create mode 100644 Design/Release.md create mode 100644 Design/ReplicationIssues.md create mode 100644 Design/StorageConcurrency.md create mode 100644 Design/Suggestions.md create mode 100644 Interactors/Python/bakashrot.py create mode 100644 Interactors/Python/check_bakashrot.py create mode 100644 Interactors/Python/example.py create mode 100644 Interactors/Python/notes.txt create mode 100644 Libs/redist/README.md create mode 100644 Libs/redist/x64/vcruntime140.dll create mode 100644 Notes.md create mode 100644 Release.ps1 create mode 100644 Server/BakaShrot_Server.pb create mode 100644 Server/BakaShrot_Server.pb.cfg create mode 100644 Server/Config/Config.pbi rename {Core => Server}/Config/Config.pbi.cfg (100%) create mode 100644 Server/Config/schema.ini rename {Core => Server}/Config/schema_out.ini (73%) create mode 100644 Server/Networking/Networking.pbi create mode 100644 Server/Networking/Networking.pbi.cfg create mode 100644 Server/Networking/Peers.pbi create mode 100644 Server/Root.pbi create mode 100644 Server/Storage/Names.pbi create mode 100644 Server/Storage/Storage.pbi create mode 100644 Server/Storage/Writer.pbi rename {Core => Server}/Storage/db_schema_v0.dbml (100%) rename {Core => Server}/Storage/db_schema_v1.dbml (100%) create mode 100644 Server/Storage/db_schema_v2.dbml create mode 100644 Server/Storage/db_schema_v3.dbml create mode 100644 Server/Storage/db_schema_v4.dbml create mode 100644 Server/Storage/db_schema_v5.dbml create mode 100644 Tests/Bench/Bench-Replication.ps1 create mode 100644 Tests/Bench/BenchClient.pb create mode 100644 Tests/Bench/BenchSeed.pb create mode 100644 Tests/Bench/BenchServer.pb create mode 100644 Tests/Bench/Compare-Runs.ps1 create mode 100644 Tests/Bench/Results-2026-11-07.md create mode 100644 Tests/Bench/queries.txt create mode 100644 Tests/Bench/queries_load.txt create mode 100644 Tests/BigMessages-Test.ps1 create mode 100644 Tests/CipherTest.pb create mode 100644 Tests/GetMessages-Test.ps1 create mode 100644 Tests/HandshakeTest.pb create mode 100644 Tests/Names-Test.ps1 create mode 100644 Tests/Python-Test.ps1 create mode 100644 Tests/wire_check.py create mode 100644 Tools/Common/ToolClient.pbi create mode 100644 Tools/GetLatestMessage/GetLatestMessage.pb create mode 100644 Tools/GetMessages/GetMessages.pb create mode 100644 Tools/KeyGen/KeyGen.pb create mode 100644 Tools/ListNames/ListNames.pb create mode 100644 Tools/PushMessage/PushMessage.pb create mode 100644 Tools/Query/Query.pb create mode 100644 Tools/Resolve/Resolve.pb diff --git a/.gitignore b/.gitignore index 65cfc43..a311434 100644 --- a/.gitignore +++ b/.gitignore @@ -5,8 +5,19 @@ # Build Artifacts *.exe *.dll +# ... except the runtime redistributables the release packages, see Libs/redist/README.md +!Libs/redist/**/*.dll *.so *.a *.pdb *.lib *.exp + +# Build output, holds generated private keys +Build/ + +# Release builds, see Release.ps1 +Release/ + +# Python +__pycache__/ diff --git a/Build.ps1 b/Build.ps1 new file mode 100644 index 0000000..52ae66a --- /dev/null +++ b/Build.ps1 @@ -0,0 +1,334 @@ +# ============================================================================ +# 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 KeyGen, the server, the client DLL, its example app and the +# tools (PushMessage, GetLatestMessage, GetMessages, Query, Resolve, +# ListNames) 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.: +# .\PushMessage.exe -t sensors @msg.json client.ini +# .\GetLatestMessage.exe sensors local client2.ini +# .\GetMessages.exe logs local --follow client2.ini +# .\Resolve.exe topic sensors client2.ini (201 there, 2 on server) +# .\Query.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 ] +# +# 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 { + # KeyGen prints "PrivateKey = ..." then "PublicKey = ...". + $Lines = & (Join-Path $Output "KeyGen.exe") + if ($LASTEXITCODE -ne 0) { + throw "KeyGen 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\KeyGen\KeyGen.pb" "KeyGen.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: + # PushMessage [-t ] [ClientIni] + # GetLatestMessage [ClientIni] + Invoke-Compiler "Tools\PushMessage\PushMessage.pb" "PushMessage.exe" @("/CONSOLE") + Invoke-Compiler "Tools\GetLatestMessage\GetLatestMessage.pb" "GetLatestMessage.exe" @("/CONSOLE") + # GetMessages [--after ] [--limit ] [--follow] [ClientIni] + Invoke-Compiler "Tools\GetMessages\GetMessages.pb" "GetMessages.exe" @("/CONSOLE") + # Query [ClientIni] + Invoke-Compiler "Tools\Query\Query.pb" "Query.exe" @("/CONSOLE") + # Resolve [ClientIni] + Invoke-Compiler "Tools\Resolve\Resolve.pb" "Resolve.exe" @("/CONSOLE") + # ListNames [topics|nodes|all] [ClientIni] [--json] + Invoke-Compiler "Tools\ListNames\ListNames.pb" "ListNames.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) +Topic = logs +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 +Topic = logs +Node = server2 +PublicKey = $($Server2Keys.PublicKey) + +[BakaShrot.Client.local] +PublicKeys = $($ClientKeys.PublicKey) +Identities = logs:local +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) +Identities = logs:server2 +AllowRead = 0 +AllowWrite = 0 +AllowQuery = 0 +"@ + Set-Content -Path (Join-Path $Output "server.ini") -Value $ServerConfig -Encoding Ascii + + $Server2Config = @" +[BakaShrot] +PrivateKey = $($Server2Keys.PrivateKey) +Topic = logs +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 +Topic = logs +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) +Identities = logs:server1 +AllowRead = 0 +AllowWrite = 0 +AllowQuery = 0 + +; No raw queries through this server. +[BakaShrot.Client.local] +PublicKeys = $($ClientKeys.PublicKey) +Identities = logs:local2 +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) +Topic = logs +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) +Topic = logs +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 +} diff --git a/Client/BakaShrot_Client.pbi b/Client/BakaShrot_Client.pbi new file mode 100644 index 0000000..d2d9cf4 --- /dev/null +++ b/Client/BakaShrot_Client.pbi @@ -0,0 +1,1098 @@ +; ============================================================================ +; BakaShrot Client DLL +; +; Lets an app connect to a BakaShrot server, one step at a time: +; 1. BakaShrot_SetPrivateKey(), BakaShrot_SetPublicKey(), +; BakaShrot_SetServerPublicKey() (the server's, from its log or its +; KeyGen output), BakaShrot_SetTopic() and BakaShrot_SetNode() (names +; or ids), or BakaShrot_SetTopicId() and BakaShrot_SetNodeId() +; 2. BakaShrot_Connect(Host, Port), connects and authenticates, see the +; handshake in Commons/Networking/Connections.pbi: only to the server +; holding the private key of BakaShrot_SetServerPublicKey()'s, and +; everything is encrypted +; 3. Requests, once connected: +; BakaShrot_PushMessage(JsonData), into the client's own topic, or +; BakaShrot_PushMessageTo(Topic, JsonData), returns the new +; message's id +; BakaShrot_GetLatestMessageOf(Topic, Node), or +; BakaShrot_GetLatestMessage(TopicId, NodeId), then +; BakaShrot_GetMessageId(), BakaShrot_GetMessageData(), +; BakaShrot_GetMessageTopic() / BakaShrot_GetMessageNode() (names) +; and BakaShrot_GetMessageTopicId() / BakaShrot_GetMessageNodeId() +; BakaShrot_GetMessages(Topic, Node, AfterMessageId, Limit): the +; messages after an id, returns how many came, then +; BakaShrot_SelectMessage(Index) (0 is selected already) and the +; same getters for each, BakaShrot_HasMoreMessages() if more +; follow the last one +; BakaShrot_ResolveTopic(Ref), BakaShrot_ResolveNode(Ref): the +; server's id for a name (or the other way), then +; BakaShrot_GetResolvedName() +; BakaShrot_ListTopics(), BakaShrot_ListNodes(): every one with its +; id and name, then BakaShrot_GetNamesList() as JSON +; BakaShrot_Query(Sql), raw read-only SQL, then +; BakaShrot_GetQueryResult() +; If the server refuses a request, the connection stays open and +; BakaShrot_GetRefusalReason() tells why. +; 4. BakaShrot_IsConnected(), BakaShrot_Disconnect() +; +; Topics and nodes are "refs": a name, or an id in digits, see +; Commons/Networking/Names.pbi. Ids are the server's own, each server can +; have different ones for the same names. +; +; The DLL holds a single connection. +; Every function returns #True (1) on success, #False (0) on failure, unless +; said otherwise. +; +; String getters copy into a caller-provided buffer of BufferSize bytes, and +; return the size in bytes needed for it, terminator included. Call them +; with a null *Buffer to get that size first. Nothing is copied if it +; doesn't fit. +; +; Functions taking strings come in two exported variants, like the Win32 API: +; A takes a null-terminated UTF-8 string (plain ASCII works too). +; W takes a null-terminated UTF-16 string (wchar_t* on Windows). +; Both only receive a pointer and read it with PeekS(), so apps built with +; any compiler or PureBasic version can call them. +; +; Apps should include BakaShrot_Client_Prototypes.pbi instead of this file. +; Compile as a shared DLL. +; ============================================================================ + +EnableExplicit + +XIncludeFile "../Commons/Networking/Outbound.pbi" + + +Structure BakaShrot_ClientPrivateKey + Bytes.a[#BakaShrot_Ed25519_PrivateKeySize] +EndStructure + + +Structure BakaShrot_ClientServerKey + Bytes.a[#BakaShrot_Ed25519_PublicKeySize] +EndStructure + + +Global BakaShrot_PrivateKey.BakaShrot_ClientPrivateKey +Global BakaShrot_HasPrivateKey.i = #False +Global BakaShrot_PublicKey.s = "" +Global BakaShrot_ServerPublicKey.BakaShrot_ClientServerKey +Global BakaShrot_HasServerPublicKey.i = #False +Global BakaShrot_Topic.s = "" +Global BakaShrot_Node.s = "" + +; The connection, see Commons/Networking/Outbound.pbi. +Global BakaShrot_Outbound.BakaShrot_Outbound + +; Filled by the requests, see BakaShrot_GetLatestMessage() and BakaShrot_GetRefusalReasonA/W(). +Global BakaShrot_MessageId.q = 0 +Global BakaShrot_MessageData.s = "" +Global BakaShrot_MessageTopicId.l = -1 +Global BakaShrot_MessageNodeId.l = -1 +Global BakaShrot_MessageTopic.s = "" +Global BakaShrot_MessageNode.s = "" +Global BakaShrot_RefusalReason.s = "" +Global BakaShrot_QueryResult.s = "" +Global BakaShrot_ResolvedName.s = "" +Global BakaShrot_NamesList.s = "" + +; Every message of the last answer, BakaShrot_GetMessages() or +; BakaShrot_GetLatestMessage(). The BakaShrot_Message* globals above are the +; selected one, see BakaShrot_SelectMessage(). +Global NewList BakaShrot_Messages.BakaShrot_MessagesEntry() +Global BakaShrot_MessagesMore.i = #False + + +; Sets the Ed25519 private key (Base64) used to answer the server's challenge. +; Must be done before connecting. +Procedure.i BakaShrot_SetPrivateKeyString(PrivateKey.s) + If BakaShrot_Outbound\ConnectionId + ProcedureReturn #False + EndIf + + If Not DecodeKeyFromString(PrivateKey, @BakaShrot_PrivateKey\Bytes[0], #BakaShrot_Ed25519_PrivateKeySize) + ProcedureReturn #False + EndIf + + BakaShrot_HasPrivateKey = #True + ProcedureReturn #True +EndProcedure + +ProcedureCDLL.i BakaShrot_SetPrivateKeyA(*PrivateKey) + If Not *PrivateKey + ProcedureReturn #False + EndIf + ProcedureReturn BakaShrot_SetPrivateKeyString(PeekS(*PrivateKey, -1, #PB_UTF8)) +EndProcedure + +ProcedureCDLL.i BakaShrot_SetPrivateKeyW(*PrivateKey) + If Not *PrivateKey + ProcedureReturn #False + EndIf + ProcedureReturn BakaShrot_SetPrivateKeyString(PeekS(*PrivateKey, -1, #PB_Unicode)) +EndProcedure + + +; Sets the Ed25519 public key (Base64) sent to the server in the Hello. +; Must be done before connecting. +Procedure.i BakaShrot_SetPublicKeyString(PublicKey.s) + If BakaShrot_Outbound\ConnectionId + ProcedureReturn #False + EndIf + + If PublicKey = "" + ProcedureReturn #False + EndIf + + BakaShrot_PublicKey = PublicKey + ProcedureReturn #True +EndProcedure + +ProcedureCDLL.i BakaShrot_SetPublicKeyA(*PublicKey) + If Not *PublicKey + ProcedureReturn #False + EndIf + ProcedureReturn BakaShrot_SetPublicKeyString(PeekS(*PublicKey, -1, #PB_UTF8)) +EndProcedure + +ProcedureCDLL.i BakaShrot_SetPublicKeyW(*PublicKey) + If Not *PublicKey + ProcedureReturn #False + EndIf + ProcedureReturn BakaShrot_SetPublicKeyString(PeekS(*PublicKey, -1, #PB_Unicode)) +EndProcedure + + +; Sets the server's Ed25519 public key (Base64): the Hello is sealed for it, +; and the server must prove it holds the matching private key. +; Must be done before connecting. +Procedure.i BakaShrot_SetServerPublicKeyString(PublicKey.s) + If BakaShrot_Outbound\ConnectionId + ProcedureReturn #False + EndIf + + If Not DecodeKeyFromString(PublicKey, @BakaShrot_ServerPublicKey\Bytes[0], #BakaShrot_Ed25519_PublicKeySize) + ProcedureReturn #False + EndIf + + BakaShrot_HasServerPublicKey = #True + ProcedureReturn #True +EndProcedure + +ProcedureCDLL.i BakaShrot_SetServerPublicKeyA(*PublicKey) + If Not *PublicKey + ProcedureReturn #False + EndIf + ProcedureReturn BakaShrot_SetServerPublicKeyString(PeekS(*PublicKey, -1, #PB_UTF8)) +EndProcedure + +ProcedureCDLL.i BakaShrot_SetServerPublicKeyW(*PublicKey) + If Not *PublicKey + ProcedureReturn #False + EndIf + ProcedureReturn BakaShrot_SetServerPublicKeyString(PeekS(*PublicKey, -1, #PB_Unicode)) +EndProcedure + + +; Sets the topic the client identifies as, a name or an id in digits. +; Must be done before connecting. +Procedure.i BakaShrot_SetTopicString(Topic.s) + If BakaShrot_Outbound\ConnectionId Or Not BakaShrot_IsValidRef(Topic) + ProcedureReturn #False + EndIf + BakaShrot_Topic = Topic + ProcedureReturn #True +EndProcedure + +ProcedureCDLL.i BakaShrot_SetTopicA(*Topic) + If Not *Topic + ProcedureReturn #False + EndIf + ProcedureReturn BakaShrot_SetTopicString(PeekS(*Topic, -1, #PB_UTF8)) +EndProcedure + +ProcedureCDLL.i BakaShrot_SetTopicW(*Topic) + If Not *Topic + ProcedureReturn #False + EndIf + ProcedureReturn BakaShrot_SetTopicString(PeekS(*Topic, -1, #PB_Unicode)) +EndProcedure + +; Same, by id, 0-65535. +ProcedureCDLL.i BakaShrot_SetTopicId(TopicId.l) + If TopicId < 0 Or TopicId > 65535 + ProcedureReturn #False + EndIf + ProcedureReturn BakaShrot_SetTopicString(Str(TopicId)) +EndProcedure + + +; Sets the node the client identifies as, a name or an id in digits. +; Must be done before connecting. +Procedure.i BakaShrot_SetNodeString(Node.s) + If BakaShrot_Outbound\ConnectionId Or Not BakaShrot_IsValidRef(Node) + ProcedureReturn #False + EndIf + BakaShrot_Node = Node + ProcedureReturn #True +EndProcedure + +ProcedureCDLL.i BakaShrot_SetNodeA(*Node) + If Not *Node + ProcedureReturn #False + EndIf + ProcedureReturn BakaShrot_SetNodeString(PeekS(*Node, -1, #PB_UTF8)) +EndProcedure + +ProcedureCDLL.i BakaShrot_SetNodeW(*Node) + If Not *Node + ProcedureReturn #False + EndIf + ProcedureReturn BakaShrot_SetNodeString(PeekS(*Node, -1, #PB_Unicode)) +EndProcedure + +; Same, by id, 0-65535. +ProcedureCDLL.i BakaShrot_SetNodeId(NodeId.l) + If NodeId < 0 Or NodeId > 65535 + ProcedureReturn #False + EndIf + ProcedureReturn BakaShrot_SetNodeString(Str(NodeId)) +EndProcedure + + +; Connects to Host:Port and authenticates with the settings above, see +; BakaShrot_Outbound_Connect() in Commons/Networking/Outbound.pbi. +; Fails if already connected, if a setting is missing, or if anything in the +; handshake is out of order or unexpected, in which case the connection is +; closed. +Procedure.i BakaShrot_ConnectString(Host.s, Port.l) + Protected Identity.BakaShrot_OutboundIdentity + + If BakaShrot_Outbound\ConnectionId + ProcedureReturn #False + EndIf + + If Not BakaShrot_HasPrivateKey Or BakaShrot_PublicKey = "" Or Not BakaShrot_HasServerPublicKey Or BakaShrot_Topic = "" Or BakaShrot_Node = "" + ProcedureReturn #False + EndIf + + Identity\Topic = BakaShrot_Topic + Identity\Node = BakaShrot_Node + Identity\PublicKey = BakaShrot_PublicKey + Identity\PrivateKey = @BakaShrot_PrivateKey\Bytes[0] + + ProcedureReturn BakaShrot_Outbound_Connect(@BakaShrot_Outbound, Host, Port, @Identity, @BakaShrot_ServerPublicKey\Bytes[0]) +EndProcedure + +ProcedureCDLL.i BakaShrot_ConnectA(*Host, Port.l) + If Not *Host + ProcedureReturn #False + EndIf + ProcedureReturn BakaShrot_ConnectString(PeekS(*Host, -1, #PB_UTF8), Port) +EndProcedure + +ProcedureCDLL.i BakaShrot_ConnectW(*Host, Port.l) + If Not *Host + ProcedureReturn #False + EndIf + ProcedureReturn BakaShrot_ConnectString(PeekS(*Host, -1, #PB_Unicode), Port) +EndProcedure + + +; Returns #True while the connection is open and authenticated. +; Notices when the server closed it. +ProcedureCDLL.i BakaShrot_IsConnected() + ProcedureReturn BakaShrot_Outbound_IsConnected(@BakaShrot_Outbound) +EndProcedure + + +; Closes the connection, if any. The settings are kept. +ProcedureCDLL.i BakaShrot_Disconnect() + If Not BakaShrot_Outbound\ConnectionId + ProcedureReturn #False + EndIf + + BakaShrot_Outbound_Close(@BakaShrot_Outbound, #BakaShrot_ConnectionStatus_Disconnected) + ProcedureReturn #True +EndProcedure + + +; --- Requests ---------------------------------------------------------------- + +; Closes the connection after something went wrong in a request. +Procedure BakaShrot_AbortConnection() + BakaShrot_Outbound_Close(@BakaShrot_Outbound, #BakaShrot_ConnectionStatus_Aborted) +EndProcedure + + +; Sends a request and waits for its answer. +; Returns the answer (free it with FreeMemory) with its size in *OutSize\i, +; or 0 if the connection failed, in which case it's closed. +; A refusal is returned like any other answer. +Procedure.i BakaShrot_SendRequest(*Request, RequestSize.i, *OutSize.Integer) + Protected *Answer + + If Not BakaShrot_Outbound_Send(@BakaShrot_Outbound, *Request, RequestSize) + BakaShrot_AbortConnection() + ProcedureReturn 0 + EndIf + + *Answer = BakaShrot_Outbound_WaitPacket(@BakaShrot_Outbound, *OutSize, #BakaShrot_Outbound_Timeout) + If Not *Answer + BakaShrot_AbortConnection() + ProcedureReturn 0 + EndIf + + ProcedureReturn *Answer +EndProcedure + + +; Reads a RequestRefused answer into BakaShrot_RefusalReason. +; Returns #False if it's malformed, the connection must then be aborted. +Procedure.i BakaShrot_ReadRefusal(*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 + + BakaShrot_RefusalReason = *Refused\Reason + FreeStructure(*Refused) + ProcedureReturn #True +EndProcedure + + +; Copies Text into *Buffer as a null-terminated string in Format +; (#PB_UTF8 or #PB_Unicode), if it fits in BufferSize bytes. +; Returns the size in bytes needed for it, terminator included. +Procedure.i BakaShrot_CopyString(Text.s, *Buffer, BufferSize.i, Format.i) + Protected NeededSize.i + + If Format = #PB_UTF8 + NeededSize = StringByteLength(Text, #PB_UTF8) + 1 + Else + NeededSize = StringByteLength(Text, #PB_Unicode) + 2 + EndIf + + If *Buffer And BufferSize >= NeededSize + PokeS(*Buffer, Text, -1, Format) + EndIf + + ProcedureReturn NeededSize +EndProcedure + + +; Pushes a message (JSON or anything else, the server flags which in its +; is_json column) into Topic (a name or an id, "" for the client's own +; topic), the server stores it under that topic and this client's node, with +; the next message id. The client's PushTopics on the server must allow it. +; Returns the new message's id (1 or more), or -1 on failure. +; On -1, BakaShrot_IsConnected() tells if the server refused it (still +; connected, see BakaShrot_GetRefusalReason()) or if the connection failed. +Procedure.q BakaShrot_PushMessageToString(Topic.s, JsonData.s) + Protected Push.BakaShrot_PushMessage + Protected *Pushed.BakaShrot_MessagePushed + Protected *Request, RequestSize.Integer, *Answer, AnswerSize.Integer + Protected *View.MsgPackData, IsRefusal.i, MessageId.q + + BakaShrot_RefusalReason = "" + + If Not BakaShrot_Outbound\ConnectionId Or BakaShrot_Outbound\Metadata\Status <> #BakaShrot_ConnectionStatus_Authenticated + ProcedureReturn -1 + EndIf + + If Topic <> "" And Not BakaShrot_IsValidRef(Topic) + ProcedureReturn -1 + EndIf + + ; Refused here rather than sent for nothing, same reason as the server's. + If StringByteLength(JsonData, #PB_UTF8) > #BakaShrot_MaxMessageSize + BakaShrot_RefusalReason = "The message is too big: " + Str(StringByteLength(JsonData, #PB_UTF8)) + " bytes, at most " + Str(#BakaShrot_MaxMessageSize) + ProcedureReturn -1 + EndIf + + Push\Topic = Topic + Push\JsonData = JsonData + *Request = BakaShrot_PushMessagePacket_Encode(@Push, @RequestSize) + If Not *Request + ProcedureReturn -1 + EndIf + *Answer = BakaShrot_SendRequest(*Request, RequestSize\i, @AnswerSize) + FreeMemory(*Request) + If Not *Answer + ProcedureReturn -1 + EndIf + + If BakaShrot_GetPacketType(*Answer, AnswerSize\i) = #BakaShrot_PacketType_RequestRefused + IsRefusal = BakaShrot_ReadRefusal(*Answer, AnswerSize\i) + FreeMemory(*Answer) + If Not IsRefusal + BakaShrot_AbortConnection() + EndIf + ProcedureReturn -1 + EndIf + + *Pushed = 0 + *View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i) + If *View + *Pushed = BakaShrot_MessagePushedPacket_Decode(*View) + MsgPackFree(*View, #False) + EndIf + FreeMemory(*Answer) + If Not *Pushed + BakaShrot_AbortConnection() + ProcedureReturn -1 + EndIf + + MessageId = *Pushed\MessageId + FreeStructure(*Pushed) + ProcedureReturn MessageId +EndProcedure + +; A null *JsonData is an empty message (stored, is_json = 0): PureBasic +; passes empty strings to a DLL as null pointers. +ProcedureCDLL.q BakaShrot_PushMessageA(*JsonData) + If Not *JsonData + ProcedureReturn BakaShrot_PushMessageToString("", "") + EndIf + ProcedureReturn BakaShrot_PushMessageToString("", PeekS(*JsonData, -1, #PB_UTF8)) +EndProcedure + +ProcedureCDLL.q BakaShrot_PushMessageW(*JsonData) + If Not *JsonData + ProcedureReturn BakaShrot_PushMessageToString("", "") + EndIf + ProcedureReturn BakaShrot_PushMessageToString("", PeekS(*JsonData, -1, #PB_Unicode)) +EndProcedure + +; A null *Topic is the client's own topic, like "", and a null *JsonData an +; empty message: PureBasic passes empty strings to a DLL as null pointers. +ProcedureCDLL.q BakaShrot_PushMessageToA(*Topic, *JsonData) + Protected Topic.s, JsonData.s + If *Topic + Topic = PeekS(*Topic, -1, #PB_UTF8) + EndIf + If *JsonData + JsonData = PeekS(*JsonData, -1, #PB_UTF8) + EndIf + ProcedureReturn BakaShrot_PushMessageToString(Topic, JsonData) +EndProcedure + +ProcedureCDLL.q BakaShrot_PushMessageToW(*Topic, *JsonData) + Protected Topic.s, JsonData.s + If *Topic + Topic = PeekS(*Topic, -1, #PB_Unicode) + EndIf + If *JsonData + JsonData = PeekS(*JsonData, -1, #PB_Unicode) + EndIf + ProcedureReturn BakaShrot_PushMessageToString(Topic, JsonData) +EndProcedure + + +; Asks for the latest message of a topic/node, each a name or an id. The +; server refuses if the client's ReadTopics don't allow the topic, if +; either is unknown, or if there's no message. +; On success, read it with BakaShrot_GetMessageId(), BakaShrot_GetMessageData(), +; BakaShrot_GetMessageTopic/Node() and BakaShrot_GetMessageTopicId/NodeId(). +; On failure, BakaShrot_IsConnected() tells if it was refused (see +; BakaShrot_GetRefusalReason()) or if the connection failed. +Procedure.i BakaShrot_GetLatestMessageOfString(Topic.s, Node.s) + Protected Request.BakaShrot_GetLatestMessage + Protected *Latest.BakaShrot_LatestMessage + Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer + Protected *View.MsgPackData, IsRefusal.i, IsExpected.i + + BakaShrot_RefusalReason = "" + BakaShrot_MessageId = 0 + BakaShrot_MessageData = "" + BakaShrot_MessageTopicId = -1 + BakaShrot_MessageNodeId = -1 + BakaShrot_MessageTopic = "" + BakaShrot_MessageNode = "" + ClearList(BakaShrot_Messages()) + BakaShrot_MessagesMore = #False + + If Not BakaShrot_Outbound\ConnectionId Or BakaShrot_Outbound\Metadata\Status <> #BakaShrot_ConnectionStatus_Authenticated + ProcedureReturn #False + EndIf + + If Not BakaShrot_IsValidRef(Topic) Or Not BakaShrot_IsValidRef(Node) + ProcedureReturn #False + EndIf + + Request\Topic = Topic + Request\Node = Node + *Packet = BakaShrot_GetLatestMessagePacket_Encode(@Request, @PacketSize) + If Not *Packet + ProcedureReturn #False + EndIf + *Answer = BakaShrot_SendRequest(*Packet, PacketSize\i, @AnswerSize) + FreeMemory(*Packet) + If Not *Answer + ProcedureReturn #False + EndIf + + If BakaShrot_GetPacketType(*Answer, AnswerSize\i) = #BakaShrot_PacketType_RequestRefused + IsRefusal = BakaShrot_ReadRefusal(*Answer, AnswerSize\i) + FreeMemory(*Answer) + If Not IsRefusal + BakaShrot_AbortConnection() + EndIf + ProcedureReturn #False + EndIf + + *Latest = 0 + *View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i) + If *View + *Latest = BakaShrot_LatestMessagePacket_Decode(*View) + MsgPackFree(*View, #False) + EndIf + FreeMemory(*Answer) + If Not *Latest + BakaShrot_AbortConnection() + ProcedureReturn #False + EndIf + + ; An answer about another topic/node is out of order. + IsExpected = Bool(BakaShrot_RefMatches(Topic, *Latest\TopicId, *Latest\TopicName) And BakaShrot_RefMatches(Node, *Latest\NodeId, *Latest\NodeName)) + If IsExpected + BakaShrot_MessageId = *Latest\MessageId + BakaShrot_MessageData = *Latest\JsonData + BakaShrot_MessageTopicId = *Latest\TopicId + BakaShrot_MessageNodeId = *Latest\NodeId + BakaShrot_MessageTopic = *Latest\TopicName + BakaShrot_MessageNode = *Latest\NodeName + AddElement(BakaShrot_Messages()) + BakaShrot_Messages()\MessageId = *Latest\MessageId + BakaShrot_Messages()\JsonData = *Latest\JsonData + EndIf + FreeStructure(*Latest) + If Not IsExpected + BakaShrot_AbortConnection() + ProcedureReturn #False + EndIf + + ProcedureReturn #True +EndProcedure + + +ProcedureCDLL.i BakaShrot_GetLatestMessageOfA(*Topic, *Node) + If Not *Topic Or Not *Node + ProcedureReturn #False + EndIf + ProcedureReturn BakaShrot_GetLatestMessageOfString(PeekS(*Topic, -1, #PB_UTF8), PeekS(*Node, -1, #PB_UTF8)) +EndProcedure + +ProcedureCDLL.i BakaShrot_GetLatestMessageOfW(*Topic, *Node) + If Not *Topic Or Not *Node + ProcedureReturn #False + EndIf + ProcedureReturn BakaShrot_GetLatestMessageOfString(PeekS(*Topic, -1, #PB_Unicode), PeekS(*Node, -1, #PB_Unicode)) +EndProcedure + +; Same, by ids, 0-65535. +ProcedureCDLL.i BakaShrot_GetLatestMessage(TopicId.l, NodeId.l) + If TopicId < 0 Or TopicId > 65535 Or NodeId < 0 Or NodeId > 65535 + ProcedureReturn #False + EndIf + ProcedureReturn BakaShrot_GetLatestMessageOfString(Str(TopicId), Str(NodeId)) +EndProcedure + + +; Asks for the messages of a topic/node (each a name or an id) stored after +; AfterMessageId (0 for the first ones), in message id order: at most Limit +; (1-10000), fewer if they didn't fit in about 1 MB, a bigger one alone. The +; server refuses if the client's ReadTopics don't allow the topic, or if +; either is unknown. No more messages isn't a refusal, it returns 0. +; Returns how many came (0 or more), or -1 on failure: BakaShrot_IsConnected() +; tells if it was refused (see BakaShrot_GetRefusalReason()) or if the +; connection failed. +; On success, the first one is selected: read it with BakaShrot_GetMessageId(), +; BakaShrot_GetMessageData() and the others, select the next ones with +; BakaShrot_SelectMessage(). BakaShrot_GetMessageTopic/Node/TopicId/NodeId() +; are set even if none came. BakaShrot_HasMoreMessages() tells if more +; follow the last one: ask again after its id. +Procedure.l BakaShrot_GetMessagesString(Topic.s, Node.s, AfterMessageId.q, Limit.l) + Protected Request.BakaShrot_GetMessages + Protected *Answer.BakaShrot_Messages + Protected *Packet, PacketSize.Integer, *AnswerPacket, AnswerSize.Integer + Protected *View.MsgPackData, IsRefusal.i, IsExpected.i, Count.l + + BakaShrot_RefusalReason = "" + BakaShrot_MessageId = 0 + BakaShrot_MessageData = "" + BakaShrot_MessageTopicId = -1 + BakaShrot_MessageNodeId = -1 + BakaShrot_MessageTopic = "" + BakaShrot_MessageNode = "" + ClearList(BakaShrot_Messages()) + BakaShrot_MessagesMore = #False + + If Not BakaShrot_Outbound\ConnectionId Or BakaShrot_Outbound\Metadata\Status <> #BakaShrot_ConnectionStatus_Authenticated + ProcedureReturn -1 + EndIf + + If Not BakaShrot_IsValidRef(Topic) Or Not BakaShrot_IsValidRef(Node) + ProcedureReturn -1 + EndIf + If AfterMessageId < 0 Or Limit < 1 Or Limit > #BakaShrot_MaxGetMessages + ProcedureReturn -1 + EndIf + + Request\Topic = Topic + Request\Node = Node + Request\AfterMessageId = AfterMessageId + Request\Limit = Limit + *Packet = BakaShrot_GetMessagesPacket_Encode(@Request, @PacketSize) + If Not *Packet + ProcedureReturn -1 + EndIf + *AnswerPacket = BakaShrot_SendRequest(*Packet, PacketSize\i, @AnswerSize) + FreeMemory(*Packet) + If Not *AnswerPacket + ProcedureReturn -1 + EndIf + + If BakaShrot_GetPacketType(*AnswerPacket, AnswerSize\i) = #BakaShrot_PacketType_RequestRefused + IsRefusal = BakaShrot_ReadRefusal(*AnswerPacket, AnswerSize\i) + FreeMemory(*AnswerPacket) + If Not IsRefusal + BakaShrot_AbortConnection() + EndIf + ProcedureReturn -1 + EndIf + + *Answer = 0 + *View = MsgPackWrapMsgBuffer(*AnswerPacket, AnswerSize\i) + If *View + *Answer = BakaShrot_MessagesPacket_Decode(*View) + MsgPackFree(*View, #False) + EndIf + FreeMemory(*AnswerPacket) + If Not *Answer + BakaShrot_AbortConnection() + ProcedureReturn -1 + EndIf + + ; An answer about another topic/node, with more messages than asked for, + ; or with ones that aren't after AfterMessageId, is out of order. + IsExpected = Bool(BakaShrot_RefMatches(Topic, *Answer\TopicId, *Answer\TopicName) And BakaShrot_RefMatches(Node, *Answer\NodeId, *Answer\NodeName)) + If IsExpected And ListSize(*Answer\Messages()) > Limit + IsExpected = #False + EndIf + If IsExpected And FirstElement(*Answer\Messages()) + If *Answer\Messages()\MessageId <= AfterMessageId + IsExpected = #False + EndIf + EndIf + If Not IsExpected + FreeStructure(*Answer) + BakaShrot_AbortConnection() + ProcedureReturn -1 + EndIf + + BakaShrot_MessageTopicId = *Answer\TopicId + BakaShrot_MessageNodeId = *Answer\NodeId + BakaShrot_MessageTopic = *Answer\TopicName + BakaShrot_MessageNode = *Answer\NodeName + BakaShrot_MessagesMore = *Answer\More + CopyList(*Answer\Messages(), BakaShrot_Messages()) + Count = ListSize(BakaShrot_Messages()) + FreeStructure(*Answer) + + If FirstElement(BakaShrot_Messages()) + BakaShrot_MessageId = BakaShrot_Messages()\MessageId + BakaShrot_MessageData = BakaShrot_Messages()\JsonData + EndIf + ProcedureReturn Count +EndProcedure + +ProcedureCDLL.l BakaShrot_GetMessagesA(*Topic, *Node, AfterMessageId.q, Limit.l) + If Not *Topic Or Not *Node + ProcedureReturn -1 + EndIf + ProcedureReturn BakaShrot_GetMessagesString(PeekS(*Topic, -1, #PB_UTF8), PeekS(*Node, -1, #PB_UTF8), AfterMessageId, Limit) +EndProcedure + +ProcedureCDLL.l BakaShrot_GetMessagesW(*Topic, *Node, AfterMessageId.q, Limit.l) + If Not *Topic Or Not *Node + ProcedureReturn -1 + EndIf + ProcedureReturn BakaShrot_GetMessagesString(PeekS(*Topic, -1, #PB_Unicode), PeekS(*Node, -1, #PB_Unicode), AfterMessageId, Limit) +EndProcedure + +; How many messages the last BakaShrot_GetMessages() or +; BakaShrot_GetLatestMessage() got, 0 if it failed. +ProcedureCDLL.l BakaShrot_GetMessageCount() + ProcedureReturn ListSize(BakaShrot_Messages()) +EndProcedure + +; Selects the message at Index (0 to BakaShrot_GetMessageCount() - 1) of the +; last answer, for BakaShrot_GetMessageId() and BakaShrot_GetMessageData(). +; Returns #False if there's none at Index, the selection doesn't change then. +ProcedureCDLL.i BakaShrot_SelectMessage(Index.l) + If Index < 0 Or Index >= ListSize(BakaShrot_Messages()) + ProcedureReturn #False + EndIf + SelectElement(BakaShrot_Messages(), Index) + BakaShrot_MessageId = BakaShrot_Messages()\MessageId + BakaShrot_MessageData = BakaShrot_Messages()\JsonData + ProcedureReturn #True +EndProcedure + +; #True if more messages follow the last one the last BakaShrot_GetMessages() got. +ProcedureCDLL.i BakaShrot_HasMoreMessages() + ProcedureReturn BakaShrot_MessagesMore +EndProcedure + + +; Id of the selected message of the last successful BakaShrot_GetLatestMessage() +; or BakaShrot_GetMessages(), 0 if none. +ProcedureCDLL.q BakaShrot_GetMessageId() + ProcedureReturn BakaShrot_MessageId +EndProcedure + +; The server's topic and node ids of that message, -1 if none. +ProcedureCDLL.l BakaShrot_GetMessageTopicId() + ProcedureReturn BakaShrot_MessageTopicId +EndProcedure + +ProcedureCDLL.l BakaShrot_GetMessageNodeId() + ProcedureReturn BakaShrot_MessageNodeId +EndProcedure + +; The names of its topic and node, or their ids in digits if they have none. +ProcedureCDLL.i BakaShrot_GetMessageTopicA(*Buffer, BufferSize.i) + ProcedureReturn BakaShrot_CopyString(BakaShrot_MessageTopic, *Buffer, BufferSize, #PB_UTF8) +EndProcedure + +ProcedureCDLL.i BakaShrot_GetMessageTopicW(*Buffer, BufferSize.i) + ProcedureReturn BakaShrot_CopyString(BakaShrot_MessageTopic, *Buffer, BufferSize, #PB_Unicode) +EndProcedure + +ProcedureCDLL.i BakaShrot_GetMessageNodeA(*Buffer, BufferSize.i) + ProcedureReturn BakaShrot_CopyString(BakaShrot_MessageNode, *Buffer, BufferSize, #PB_UTF8) +EndProcedure + +ProcedureCDLL.i BakaShrot_GetMessageNodeW(*Buffer, BufferSize.i) + ProcedureReturn BakaShrot_CopyString(BakaShrot_MessageNode, *Buffer, BufferSize, #PB_Unicode) +EndProcedure + + +; Asks the server for its id and name of a topic or node (Kind, see +; ResolveNamePacket.pbi), Ref being a name or an id. The server only +; resolves the topics this client may push to or read, unless it may query. +; Returns the id (0-65535), or -1 on failure: refused (unknown) or the +; connection failed, see BakaShrot_IsConnected(). +; On success, BakaShrot_GetResolvedName() has its name, "" if it has none. +Procedure.l BakaShrot_ResolveString(Kind.i, Ref.s) + Protected Request.BakaShrot_ResolveName + Protected *Resolved.BakaShrot_NameResolved + Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer + Protected *View.MsgPackData, IsRefusal.i, Id.l + + BakaShrot_RefusalReason = "" + BakaShrot_ResolvedName = "" + + If Not BakaShrot_Outbound\ConnectionId Or BakaShrot_Outbound\Metadata\Status <> #BakaShrot_ConnectionStatus_Authenticated + ProcedureReturn -1 + EndIf + + If Not BakaShrot_IsValidRef(Ref) + ProcedureReturn -1 + EndIf + + Request\Kind = Kind + Request\Ref = Ref + *Packet = BakaShrot_ResolveNamePacket_Encode(@Request, @PacketSize) + If Not *Packet + ProcedureReturn -1 + EndIf + *Answer = BakaShrot_SendRequest(*Packet, PacketSize\i, @AnswerSize) + FreeMemory(*Packet) + If Not *Answer + ProcedureReturn -1 + EndIf + + If BakaShrot_GetPacketType(*Answer, AnswerSize\i) = #BakaShrot_PacketType_RequestRefused + IsRefusal = BakaShrot_ReadRefusal(*Answer, AnswerSize\i) + FreeMemory(*Answer) + If Not IsRefusal + BakaShrot_AbortConnection() + EndIf + ProcedureReturn -1 + EndIf + + *Resolved = 0 + *View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i) + If *View + *Resolved = BakaShrot_NameResolvedPacket_Decode(*View) + MsgPackFree(*View, #False) + EndIf + FreeMemory(*Answer) + If Not *Resolved + BakaShrot_AbortConnection() + ProcedureReturn -1 + EndIf + + ; An answer about something else is out of order. + If *Resolved\Kind <> Kind Or Not BakaShrot_RefMatches(Ref, *Resolved\Id, *Resolved\Name) + FreeStructure(*Resolved) + BakaShrot_AbortConnection() + ProcedureReturn -1 + EndIf + + Id = *Resolved\Id + BakaShrot_ResolvedName = *Resolved\Name + FreeStructure(*Resolved) + ProcedureReturn Id +EndProcedure + +ProcedureCDLL.l BakaShrot_ResolveTopicA(*Ref) + If Not *Ref + ProcedureReturn -1 + EndIf + ProcedureReturn BakaShrot_ResolveString(#BakaShrot_NameKind_Topic, PeekS(*Ref, -1, #PB_UTF8)) +EndProcedure + +ProcedureCDLL.l BakaShrot_ResolveTopicW(*Ref) + If Not *Ref + ProcedureReturn -1 + EndIf + ProcedureReturn BakaShrot_ResolveString(#BakaShrot_NameKind_Topic, PeekS(*Ref, -1, #PB_Unicode)) +EndProcedure + +ProcedureCDLL.l BakaShrot_ResolveNodeA(*Ref) + If Not *Ref + ProcedureReturn -1 + EndIf + ProcedureReturn BakaShrot_ResolveString(#BakaShrot_NameKind_Node, PeekS(*Ref, -1, #PB_UTF8)) +EndProcedure + +ProcedureCDLL.l BakaShrot_ResolveNodeW(*Ref) + If Not *Ref + ProcedureReturn -1 + EndIf + ProcedureReturn BakaShrot_ResolveString(#BakaShrot_NameKind_Node, PeekS(*Ref, -1, #PB_Unicode)) +EndProcedure + +; Asks the server for every topic (Kind #BakaShrot_NameKind_Topic, only +; those this client may push to or read, unless it may query) or node, and +; keeps them as JSON for BakaShrot_GetNamesList(): +; {"kind": "topic", "truncated": false, +; "items": [{"id": 1, "name": "logs", "origin": "config"}, ...]} +; by id, "name" "" if unnamed (those don't replicate), "origin" "config" or +; "id". "truncated" is true if they didn't all fit in one packet. +; Returns how many are listed, or -1 on failure (see BakaShrot_IsConnected()). +Procedure.l BakaShrot_ListNamesOf(Kind.i) + Protected Request.BakaShrot_ListNames + Protected *List.BakaShrot_NamesList + Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer + Protected *View.MsgPackData, IsRefusal.i, Count.l + Protected Json.i, Root.i, Items.i, Item.i + + BakaShrot_RefusalReason = "" + BakaShrot_NamesList = "" + + If Not BakaShrot_Outbound\ConnectionId Or BakaShrot_Outbound\Metadata\Status <> #BakaShrot_ConnectionStatus_Authenticated + ProcedureReturn -1 + EndIf + + Request\Kind = Kind + *Packet = BakaShrot_ListNamesPacket_Encode(@Request, @PacketSize) + If Not *Packet + ProcedureReturn -1 + EndIf + *Answer = BakaShrot_SendRequest(*Packet, PacketSize\i, @AnswerSize) + FreeMemory(*Packet) + If Not *Answer + ProcedureReturn -1 + EndIf + + If BakaShrot_GetPacketType(*Answer, AnswerSize\i) = #BakaShrot_PacketType_RequestRefused + IsRefusal = BakaShrot_ReadRefusal(*Answer, AnswerSize\i) + FreeMemory(*Answer) + If Not IsRefusal + BakaShrot_AbortConnection() + EndIf + ProcedureReturn -1 + EndIf + + *List = 0 + *View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i) + If *View + *List = BakaShrot_NamesListPacket_Decode(*View) + MsgPackFree(*View, #False) + EndIf + FreeMemory(*Answer) + If Not *List Or *List\Kind <> Kind + If *List + FreeStructure(*List) + EndIf + BakaShrot_AbortConnection() + ProcedureReturn -1 + EndIf + + Json = CreateJSON(#PB_Any) + If Not Json + FreeStructure(*List) + ProcedureReturn -1 + EndIf + Root = SetJSONObject(JSONValue(Json)) + If Kind = #BakaShrot_NameKind_Topic + SetJSONString(AddJSONMember(Root, "kind"), "topic") + Else + SetJSONString(AddJSONMember(Root, "kind"), "node") + EndIf + SetJSONBoolean(AddJSONMember(Root, "truncated"), *List\Truncated) + Items = SetJSONArray(AddJSONMember(Root, "items")) + ForEach *List\Entries() + Item = SetJSONObject(AddJSONElement(Items)) + SetJSONInteger(AddJSONMember(Item, "id"), *List\Entries()\Id) + SetJSONString(AddJSONMember(Item, "name"), *List\Entries()\Name) + SetJSONString(AddJSONMember(Item, "origin"), *List\Entries()\Origin) + Next + BakaShrot_NamesList = ComposeJSON(Json) + FreeJSON(Json) + + Count = ListSize(*List\Entries()) + FreeStructure(*List) + ProcedureReturn Count +EndProcedure + +ProcedureCDLL.l BakaShrot_ListTopics() + ProcedureReturn BakaShrot_ListNamesOf(#BakaShrot_NameKind_Topic) +EndProcedure + +ProcedureCDLL.l BakaShrot_ListNodes() + ProcedureReturn BakaShrot_ListNamesOf(#BakaShrot_NameKind_Node) +EndProcedure + +; JSON of the last successful BakaShrot_ListTopics/Nodes(). +ProcedureCDLL.i BakaShrot_GetNamesListA(*Buffer, BufferSize.i) + ProcedureReturn BakaShrot_CopyString(BakaShrot_NamesList, *Buffer, BufferSize, #PB_UTF8) +EndProcedure + +ProcedureCDLL.i BakaShrot_GetNamesListW(*Buffer, BufferSize.i) + ProcedureReturn BakaShrot_CopyString(BakaShrot_NamesList, *Buffer, BufferSize, #PB_Unicode) +EndProcedure + + +; Name found by the last successful BakaShrot_ResolveTopic/Node(), "" if it has none. +ProcedureCDLL.i BakaShrot_GetResolvedNameA(*Buffer, BufferSize.i) + ProcedureReturn BakaShrot_CopyString(BakaShrot_ResolvedName, *Buffer, BufferSize, #PB_UTF8) +EndProcedure + +ProcedureCDLL.i BakaShrot_GetResolvedNameW(*Buffer, BufferSize.i) + ProcedureReturn BakaShrot_CopyString(BakaShrot_ResolvedName, *Buffer, BufferSize, #PB_Unicode) +EndProcedure + +; Data (JSON or not) of the selected message of the last successful +; BakaShrot_GetLatestMessage() or BakaShrot_GetMessages(). +ProcedureCDLL.i BakaShrot_GetMessageDataA(*Buffer, BufferSize.i) + ProcedureReturn BakaShrot_CopyString(BakaShrot_MessageData, *Buffer, BufferSize, #PB_UTF8) +EndProcedure + +ProcedureCDLL.i BakaShrot_GetMessageDataW(*Buffer, BufferSize.i) + ProcedureReturn BakaShrot_CopyString(BakaShrot_MessageData, *Buffer, BufferSize, #PB_Unicode) +EndProcedure + + +; Why the server refused the last request, empty if it didn't. +ProcedureCDLL.i BakaShrot_GetRefusalReasonA(*Buffer, BufferSize.i) + ProcedureReturn BakaShrot_CopyString(BakaShrot_RefusalReason, *Buffer, BufferSize, #PB_UTF8) +EndProcedure + +ProcedureCDLL.i BakaShrot_GetRefusalReasonW(*Buffer, BufferSize.i) + ProcedureReturn BakaShrot_CopyString(BakaShrot_RefusalReason, *Buffer, BufferSize, #PB_Unicode) +EndProcedure + + +; Runs a raw SQL query on the server, read-only: a single SELECT (or WITH +; ... SELECT). The server refuses it if this client isn't allowed to query, +; if it fails, or if its result doesn't fit in one packet. +; On success, read the result with BakaShrot_GetQueryResult(), as JSON: +; {"columns": ["name", ...], "rows": [["value", ...], ...]} +; Every value is a string, or null for NULL. +; On failure, BakaShrot_IsConnected() tells if it was refused (see +; BakaShrot_GetRefusalReason()) or if the connection failed. +Procedure.i BakaShrot_QueryString(Sql.s) + Protected Request.BakaShrot_QueryRequest + Protected *Result.BakaShrot_QueryResult + Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer + Protected *View.MsgPackData, IsRefusal.i + + BakaShrot_RefusalReason = "" + BakaShrot_QueryResult = "" + + If Not BakaShrot_Outbound\ConnectionId Or BakaShrot_Outbound\Metadata\Status <> #BakaShrot_ConnectionStatus_Authenticated + ProcedureReturn #False + EndIf + + Request\Sql = Sql + *Packet = BakaShrot_QueryRequestPacket_Encode(@Request, @PacketSize) + If Not *Packet + ProcedureReturn #False + EndIf + *Answer = BakaShrot_SendRequest(*Packet, PacketSize\i, @AnswerSize) + FreeMemory(*Packet) + If Not *Answer + ProcedureReturn #False + EndIf + + If BakaShrot_GetPacketType(*Answer, AnswerSize\i) = #BakaShrot_PacketType_RequestRefused + IsRefusal = BakaShrot_ReadRefusal(*Answer, AnswerSize\i) + FreeMemory(*Answer) + If Not IsRefusal + BakaShrot_AbortConnection() + EndIf + ProcedureReturn #False + EndIf + + *Result = 0 + *View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i) + If *View + *Result = BakaShrot_QueryResultPacket_Decode(*View) + MsgPackFree(*View, #False) + EndIf + FreeMemory(*Answer) + If Not *Result + BakaShrot_AbortConnection() + ProcedureReturn #False + EndIf + + BakaShrot_QueryResult = *Result\JsonResult + FreeStructure(*Result) + ProcedureReturn #True +EndProcedure + +ProcedureCDLL.i BakaShrot_QueryA(*Sql) + If Not *Sql + ProcedureReturn #False + EndIf + ProcedureReturn BakaShrot_QueryString(PeekS(*Sql, -1, #PB_UTF8)) +EndProcedure + +ProcedureCDLL.i BakaShrot_QueryW(*Sql) + If Not *Sql + ProcedureReturn #False + EndIf + ProcedureReturn BakaShrot_QueryString(PeekS(*Sql, -1, #PB_Unicode)) +EndProcedure + + +; JSON result of the last successful BakaShrot_Query(). +ProcedureCDLL.i BakaShrot_GetQueryResultA(*Buffer, BufferSize.i) + ProcedureReturn BakaShrot_CopyString(BakaShrot_QueryResult, *Buffer, BufferSize, #PB_UTF8) +EndProcedure + +ProcedureCDLL.i BakaShrot_GetQueryResultW(*Buffer, BufferSize.i) + ProcedureReturn BakaShrot_CopyString(BakaShrot_QueryResult, *Buffer, BufferSize, #PB_Unicode) +EndProcedure diff --git a/Client/BakaShrot_Client.pbi.cfg b/Client/BakaShrot_Client.pbi.cfg new file mode 100644 index 0000000..e0cc554 --- /dev/null +++ b/Client/BakaShrot_Client.pbi.cfg @@ -0,0 +1,7 @@ +IDE Options = PureBasic 6.41 beta 2 (Windows - x64) +CursorPosition = 4 +EnableXP +DPIAware +CompileSourceDirectory +EnableCompileCount = 0 +EnableBuildCount = 0 diff --git a/Client/BakaShrot_Client_Prototypes.pbi b/Client/BakaShrot_Client_Prototypes.pbi new file mode 100644 index 0000000..eea6fa0 --- /dev/null +++ b/Client/BakaShrot_Client_Prototypes.pbi @@ -0,0 +1,335 @@ +; ============================================================================ +; 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. +; ============================================================================ + + +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_SetTopicId_Prototype(TopicId.l) +PrototypeC.i BakaShrot_SetNodeId_Prototype(NodeId.l) +PrototypeC.i BakaShrot_SetTopic_Prototype(Topic.p-unicode) +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.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.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() + + +Global BakaShrot_SetPrivateKey.BakaShrot_SetPrivateKey_Prototype +Global BakaShrot_SetPublicKey.BakaShrot_SetPublicKey_Prototype +Global BakaShrot_SetServerPublicKey.BakaShrot_SetServerPublicKey_Prototype +Global BakaShrot_SetTopicId.BakaShrot_SetTopicId_Prototype +Global BakaShrot_SetNodeId.BakaShrot_SetNodeId_Prototype +Global BakaShrot_SetTopic.BakaShrot_SetTopic_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_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_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_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_SetTopicId = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_SetTopicId") + BakaShrot_SetNodeId = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_SetNodeId") + BakaShrot_SetTopic = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_SetTopicW") + 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_GetMessageData = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetMessageDataW") + BakaShrot_GetRefusalReason = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetRefusalReasonW") + 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") + + If Not BakaShrot_SetPrivateKey Or Not BakaShrot_SetPublicKey Or Not BakaShrot_SetServerPublicKey Or Not BakaShrot_SetTopicId 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_GetMessageData Or Not BakaShrot_GetRefusalReason + BakaShrot_UnloadClient() + ProcedureReturn #False + EndIf + + If Not BakaShrot_Query Or Not BakaShrot_GetQueryResult + BakaShrot_UnloadClient() + ProcedureReturn #False + EndIf + + If Not BakaShrot_SetTopic Or 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 + + 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, Topic.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", "") + Topic = ReadPreferenceString("Topic", ReadPreferenceString("TopicId", "")) + 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_SetTopic(Topic) + PrintN("Failed to set the topic") + 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 diff --git a/Client/notes.txt b/Client/notes.txt new file mode 100644 index 0000000..8808b4b --- /dev/null +++ b/Client/notes.txt @@ -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. diff --git a/Commons/Cryptography/Cipher.pbi b/Commons/Cryptography/Cipher.pbi new file mode 100644 index 0000000..f9d7cf4 --- /dev/null +++ b/Commons/Cryptography/Cipher.pbi @@ -0,0 +1,238 @@ +; ============================================================================ +; 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 diff --git a/Commons/Cryptography/Libsodium.pbi b/Commons/Cryptography/Libsodium.pbi index efb51e4..398bbae 100644 --- a/Commons/Cryptography/Libsodium.pbi +++ b/Commons/Cryptography/Libsodium.pbi @@ -1,17 +1,18 @@ ; ============================================================================ ; BakaShrot Cryptography ; -; Authenticates packets using Ed25519 signatures (via libsodium - this does -; NOT reimplement any cryptographic primitive). +; 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.) ; -; This buys integrity + authenticity, NOT confidentiality: anyone who can see -; the packet can still read it, but they cannot forge one or tamper with one -; without the signature check failing. That matches BakaShrot's -; replication/broadcast model, where a message is meant to be read by every -; peer in the group - encrypting it for a single recipient would defeat that. +; 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. @@ -24,8 +25,9 @@ ; file - see EncodeKeyToString()/DecodeKeyFromString() below. ; ; Setup required to build/run this: -; - Windows: the official libsodium release's "libsodium.lib" (import -; library) and "libsodium.dll" alongside the executable. +; - Windows: the official libsodium MSVC release's dynamic build, extracted +; to Libs/libsodium// 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. @@ -38,9 +40,27 @@ #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 -CompilerIf #PB_Compiler_OS = #PB_OS_Windows - ImportC "libsodium.lib" +; 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 @@ -63,6 +83,58 @@ CompilerEndIf ; 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) + EndImport @@ -82,6 +154,14 @@ Procedure GenerateKeyPair(*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 diff --git a/Commons/Cryptography/Session.pbi b/Commons/Cryptography/Session.pbi new file mode 100644 index 0000000..da06d0b --- /dev/null +++ b/Commons/Cryptography/Session.pbi @@ -0,0 +1,186 @@ +; ============================================================================ +; 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 diff --git a/Commons/Networking/Connections.pbi b/Commons/Networking/Connections.pbi index 693202b..3a7957a 100644 --- a/Commons/Networking/Connections.pbi +++ b/Commons/Networking/Connections.pbi @@ -1,21 +1,424 @@ +; ============================================================================ +; 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 +; 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 +; +; +; 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" + + +; 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_Idk #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 + + ; Identity from the Hello, as the server's own ids (unused on the client + ; side), only trusted once Status is Authenticated. + TopicId.u + 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 + +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. +Procedure.i BakaShrot_SendPacket(ConnectionId.i, *Packet, PacketSize.i, *Cipher.BakaShrot_Cipher) + Protected *Frame, FrameSize.i, PayloadSize.i, Offset.i, Sent.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 + + While Offset < FrameSize + Sent = SendNetworkData(ConnectionId, *Frame + Offset, FrameSize - Offset) + If Sent <= 0 + FreeMemory(*Frame) + ProcedureReturn #False + EndIf + Offset + Sent + 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 diff --git a/Commons/Networking/Names.pbi b/Commons/Networking/Names.pbi new file mode 100644 index 0000000..c5177a1 --- /dev/null +++ b/Commons/Networking/Names.pbi @@ -0,0 +1,152 @@ +; ============================================================================ +; 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 diff --git a/Commons/Networking/Outbound.pbi b/Commons/Networking/Outbound.pbi new file mode 100644 index 0000000..60498ac --- /dev/null +++ b/Commons/Networking/Outbound.pbi @@ -0,0 +1,329 @@ +; ============================================================================ +; 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 + ; Each a name or an id in digits (Names.pbi), resolved by the server. + Topic.s + 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 +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 + + If *Outbound\ConnectionId Or Not *ServerPublicKey + ProcedureReturn #False + EndIf + + If Port < 1 Or Port > 65535 + ProcedureReturn #False + EndIf + + ; Only needed before PureBasic 6.00. + CompilerIf #PB_Compiler_Version < 600 + If Not InitNetwork() + ProcedureReturn #False + EndIf + CompilerEndIf + + If Not InitCryptography() + 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 + 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 + 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\ClientTopic = *Identity\Topic + Hello\ClientNode = *Identity\Node + Hello\ClientPubKeyB64 = *Identity\PublicKey + CopyMemory(@KeyPair\PublicKey[0], @Hello\ClientSessionKey[0], #BakaShrot_SessionKeySize) + + *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 + Sent = BakaShrot_SendPacket(*Outbound\ConnectionId, *Sealed, SealedSize\i, 0) + FreeMemory(*Sealed) + If Not Sent + Goto ConnectFailed + EndIf + + + ; 2. Challenge request, in plain text + *Packet = BakaShrot_Outbound_WaitPacket(*Outbound, @PacketSize, #BakaShrot_Outbound_Timeout) + If Not *Packet + Goto ConnectFailed + EndIf + + *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 + Goto ConnectFailed + EndIf + + ; Every packet is encrypted from now on. + 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 + Sent = BakaShrot_Outbound_Send(*Outbound, *Packet, PacketSize\i) + FreeMemory(*Packet) + If Not Sent + Goto ConnectFailed + EndIf + + + ; 4. Accepted + *Packet = BakaShrot_Outbound_WaitPacket(*Outbound, @PacketSize, #BakaShrot_Outbound_Timeout) + If Not *Packet + Goto ConnectFailed + EndIf + + *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 + 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 diff --git a/Commons/Networking/Packets.pbi b/Commons/Networking/Packets.pbi index 10df221..fba749e 100644 --- a/Commons/Networking/Packets.pbi +++ b/Commons/Networking/Packets.pbi @@ -1,4 +1,7 @@ +XIncludeFile "../../Includes/PB-MessagePack/Includes/MessagePack.pbi" +XIncludeFile "Names.pbi" + ; Represents the root of all BakaShrot packets. ; Any packets below this size MUST be thrown out. @@ -8,19 +11,146 @@ Structure BakaShrot_PacketBase 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" -#BakaShrot_ProtocolVersion = 1 +; 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). +#BakaShrot_ProtocolVersion = 3 + +; 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 + +; 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 - #BakaShrot_PacketType_AuthenticationRequest = 1 - #BakaShrot_PacketType_AuthenticationChallenge = 2 - #BakaShrot_PacketType_AuthenticationResult = 3 + ; 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 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 diff --git a/Commons/Networking/Packets/AuthAcceptedPacket.pbi b/Commons/Networking/Packets/AuthAcceptedPacket.pbi new file mode 100644 index 0000000..44714a4 --- /dev/null +++ b/Commons/Networking/Packets/AuthAcceptedPacket.pbi @@ -0,0 +1,65 @@ +; ============================================================================ +; ... +; ============================================================================ + + +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 diff --git a/Commons/Networking/Packets/AuthenticationPacket.pbi b/Commons/Networking/Packets/AuthenticationPacket.pbi deleted file mode 100644 index 1339d49..0000000 --- a/Commons/Networking/Packets/AuthenticationPacket.pbi +++ /dev/null @@ -1,303 +0,0 @@ - - -; ============================================================================ -; BakaShrot Authentication Packets -; -; The three packets exchanged during the auth handshake: -; C2S AuthRequest - client introduces itself and its public key. -; S2C AuthChallenge - server sends back something for the client to sign. -; C2S AuthResult - client replies with the signed challenge. -; -; Wire format: BakaShrot_PacketBase (Magic, Version, PacketType - see -; Packets.pbi) followed by each struct's own fields, in declaration order. -; Every string field is packed as {len}{str}: a 4-byte (Long) UTF-8 byte -; length, followed by exactly that many UTF-8 bytes - no null terminator. -; ============================================================================ - - -XIncludeFile "../Packets.pbi" - -; C2S auth request -Structure BakaShrot_AuthRequest Extends BakaShrot_PacketBase - ClientGroupId.l - ClientNodeId.l - ClientPubKeyB64.s -EndStructure - -; S2C Chalenge the client must sign it with their private key -Structure BakaShrot_AuthChallenge Extends BakaShrot_PacketBase - ClientPubKeyB64.s -EndStructure - -; C2S Response with the chalenge signed by their private key -Structure BakaShrot_AuthResult Extends BakaShrot_PacketBase - ChallengeResponseB64.s -EndStructure - - -DeclareModule BakaShrot_AuthenticationPacket - - ; Encodes *Request/*Challenge/*Result into a freshly allocated buffer. - ; *OutSize receives its size in bytes. Returns 0 (and leaves *OutSize - ; untouched) if the input is invalid (null) or the buffer could not be - ; allocated. Caller owns the returned buffer - free it with FreeMemory. - Declare.i EncodeRequest(*Request.BakaShrot_AuthRequest, *OutSize.l) - Declare.i EncodeChallenge(*Challenge.BakaShrot_AuthChallenge, *OutSize.l) - Declare.i EncodeResult(*Result.BakaShrot_AuthResult, *OutSize.l) - - ; Decodes *Buffer (BufferSize bytes) into a freshly allocated struct. - ; Returns 0 if the packet is too small, malformed, truncated, or not of - ; the expected kind. Caller owns the returned struct - free it with - ; FreeStructure. - Declare.i DecodeRequest(*Buffer, BufferSize.i) - Declare.i DecodeChallenge(*Buffer, BufferSize.i) - Declare.i DecodeResult(*Buffer, BufferSize.i) - -EndDeclareModule - - -Module BakaShrot_AuthenticationPacket - - ; ------------------------------------------------------------------------ - ; Wire helpers. Every string on the wire is {len}{str}: a 4-byte UTF-8 - ; byte length followed by exactly that many UTF-8 bytes. - ; ------------------------------------------------------------------------ - - ; Size, in bytes, Str will take once written as {len}{str}. - Procedure.i PackedStringSize(Str.s) - ProcedureReturn 4 + StringByteLength(Str, #PB_UTF8) - EndProcedure - - ; Writes Str at *Buffer + Offset as {len}{str}. *Buffer must have room - ; for at least PackedStringSize(Str) bytes from Offset onward. - Procedure WritePackedString(*Buffer, Offset.i, Str.s) - PokeL(*Buffer + Offset, StringByteLength(Str, #PB_UTF8)) - PokeS(*Buffer + Offset + 4, Str, -1, #PB_UTF8) - EndProcedure - - ; #True if a {len}{str} value starting at Offset is fully contained - ; within the first BufferSize bytes of *Buffer. Always check this before - ; calling ReadPackedString() - it does no bounds checking of its own. - Procedure.i PackedStringFits(*Buffer, BufferSize.i, Offset.i) - Protected ByteLen.l - - If Offset + 4 > BufferSize - ProcedureReturn #False - EndIf - - ByteLen = PeekL(*Buffer + Offset) - If ByteLen < 0 Or Offset + 4 + ByteLen > BufferSize - ProcedureReturn #False - EndIf - - ProcedureReturn #True - EndProcedure - - ; Reads the {len}{str} value at *Buffer + Offset. Caller MUST have - ; checked PackedStringFits() first. - Procedure.s ReadPackedString(*Buffer, Offset.i) - ProcedureReturn PeekS(*Buffer + Offset + 4, PeekL(*Buffer + Offset), #PB_UTF8 | #PB_ByteLength) - EndProcedure - - - ; ------------------------------------------------------------------------ - ; Header. All three packets share the same BakaShrot_PacketBase layout: - ; Magic.l, Version.l, PacketType.l. - ; ------------------------------------------------------------------------ - - ; Writes the packet header at the start of *Buffer. Returns the offset of - ; the first byte after the header. - Procedure.i WriteHeader(*Buffer, PacketType.l) - PokeL(*Buffer, #BakaShrot_ProtocolMagic) - PokeL(*Buffer + 4, #BakaShrot_ProtocolVersion) - PokeL(*Buffer + 8, PacketType) - - ProcedureReturn SizeOf(BakaShrot_PacketBase) - EndProcedure - - ; Validates the header at the start of *Buffer: big enough to hold one, - ; correct Magic/Version, and PacketType matching ExpectedPacketType. - ; Returns the offset of the first byte after the header on success, or - ; -1 if the packet must be thrown out. - Procedure.i ReadHeader(*Buffer, BufferSize.i, ExpectedPacketType.l) - If BufferSize < SizeOf(BakaShrot_PacketBase) - ProcedureReturn -1 - EndIf - - If PeekL(*Buffer) <> #BakaShrot_ProtocolMagic - ProcedureReturn -1 - EndIf - - If PeekL(*Buffer + 4) <> #BakaShrot_ProtocolVersion - ProcedureReturn -1 - EndIf - - If PeekL(*Buffer + 8) <> ExpectedPacketType - ProcedureReturn -1 - EndIf - - ProcedureReturn SizeOf(BakaShrot_PacketBase) - EndProcedure - - - ; ------------------------------------------------------------------------ - ; AuthRequest (C2S) - ; ------------------------------------------------------------------------ - - Procedure.i EncodeRequest(*Request.BakaShrot_AuthRequest, *OutSize.l) - Protected Size.i, *Buffer, Offset.i - - If Not *Request - ProcedureReturn 0 - EndIf - - Size = SizeOf(BakaShrot_PacketBase) + 4 + 4 + PackedStringSize(*Request\ClientPubKeyB64) - - *Buffer = AllocateMemory(Size) - If Not *Buffer - ProcedureReturn 0 - EndIf - - Offset = WriteHeader(*Buffer, #BakaShrot_PacketType_AuthenticationRequest) - - PokeL(*Buffer + Offset, *Request\ClientGroupId) - Offset = Offset + 4 - PokeL(*Buffer + Offset, *Request\ClientNodeId) - Offset = Offset + 4 - - WritePackedString(*Buffer, Offset, *Request\ClientPubKeyB64) - - *OutSize\l = Size - ProcedureReturn *Buffer - EndProcedure - - Procedure.i DecodeRequest(*Buffer, BufferSize.i) - Protected Offset.i, *Request.BakaShrot_AuthRequest - - Offset = ReadHeader(*Buffer, BufferSize, #BakaShrot_PacketType_AuthenticationRequest) - If Offset = -1 - ProcedureReturn 0 - EndIf - - If Offset + 4 + 4 > BufferSize - ProcedureReturn 0 - EndIf - - *Request = AllocateStructure(BakaShrot_AuthRequest) - - *Request\Magic = #BakaShrot_ProtocolMagic - *Request\Version = #BakaShrot_ProtocolVersion - *Request\PacketType = #BakaShrot_PacketType_AuthenticationRequest - - *Request\ClientGroupId = PeekL(*Buffer + Offset) - Offset = Offset + 4 - *Request\ClientNodeId = PeekL(*Buffer + Offset) - Offset = Offset + 4 - - If Not PackedStringFits(*Buffer, BufferSize, Offset) - FreeStructure(*Request) - ProcedureReturn 0 - EndIf - *Request\ClientPubKeyB64 = ReadPackedString(*Buffer, Offset) - - ProcedureReturn *Request - EndProcedure - - - ; ------------------------------------------------------------------------ - ; AuthChallenge (S2C) - ; ------------------------------------------------------------------------ - - Procedure.i EncodeChallenge(*Challenge.BakaShrot_AuthChallenge, *OutSize.l) - Protected Size.i, *Buffer, Offset.i - - If Not *Challenge - ProcedureReturn 0 - EndIf - - Size = SizeOf(BakaShrot_PacketBase) + PackedStringSize(*Challenge\ClientPubKeyB64) - - *Buffer = AllocateMemory(Size) - If Not *Buffer - ProcedureReturn 0 - EndIf - - Offset = WriteHeader(*Buffer, #BakaShrot_PacketType_AuthenticationChallenge) - WritePackedString(*Buffer, Offset, *Challenge\ClientPubKeyB64) - - *OutSize\l = Size - ProcedureReturn *Buffer - EndProcedure - - Procedure.i DecodeChallenge(*Buffer, BufferSize.i) - Protected Offset.i, *Challenge.BakaShrot_AuthChallenge - - Offset = ReadHeader(*Buffer, BufferSize, #BakaShrot_PacketType_AuthenticationChallenge) - If Offset = -1 - ProcedureReturn 0 - EndIf - - If Not PackedStringFits(*Buffer, BufferSize, Offset) - ProcedureReturn 0 - EndIf - - *Challenge = AllocateStructure(BakaShrot_AuthChallenge) - - *Challenge\Magic = #BakaShrot_ProtocolMagic - *Challenge\Version = #BakaShrot_ProtocolVersion - *Challenge\PacketType = #BakaShrot_PacketType_AuthenticationChallenge - *Challenge\ClientPubKeyB64 = ReadPackedString(*Buffer, Offset) - - ProcedureReturn *Challenge - EndProcedure - - - ; ------------------------------------------------------------------------ - ; AuthResult (C2S) - ; ------------------------------------------------------------------------ - - Procedure.i EncodeResult(*Result.BakaShrot_AuthResult, *OutSize.l) - Protected Size.i, *Buffer, Offset.i - - If Not *Result - ProcedureReturn 0 - EndIf - - Size = SizeOf(BakaShrot_PacketBase) + PackedStringSize(*Result\ChallengeResponseB64) - - *Buffer = AllocateMemory(Size) - If Not *Buffer - ProcedureReturn 0 - EndIf - - Offset = WriteHeader(*Buffer, #BakaShrot_PacketType_AuthenticationResult) - WritePackedString(*Buffer, Offset, *Result\ChallengeResponseB64) - - *OutSize\l = Size - ProcedureReturn *Buffer - EndProcedure - - Procedure.i DecodeResult(*Buffer, BufferSize.i) - Protected Offset.i, *Result.BakaShrot_AuthResult - - Offset = ReadHeader(*Buffer, BufferSize, #BakaShrot_PacketType_AuthenticationResult) - If Offset = -1 - ProcedureReturn 0 - EndIf - - If Not PackedStringFits(*Buffer, BufferSize, Offset) - ProcedureReturn 0 - EndIf - - *Result = AllocateStructure(BakaShrot_AuthResult) - - *Result\Magic = #BakaShrot_ProtocolMagic - *Result\Version = #BakaShrot_ProtocolVersion - *Result\PacketType = #BakaShrot_PacketType_AuthenticationResult - *Result\ChallengeResponseB64 = ReadPackedString(*Buffer, Offset) - - ProcedureReturn *Result - EndProcedure - -EndModule - diff --git a/Commons/Networking/Packets/ChallengeRequestPacket.pbi b/Commons/Networking/Packets/ChallengeRequestPacket.pbi new file mode 100644 index 0000000..06fa71a --- /dev/null +++ b/Commons/Networking/Packets/ChallengeRequestPacket.pbi @@ -0,0 +1,131 @@ +; ============================================================================ +; ... +; ============================================================================ + + +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 diff --git a/Commons/Networking/Packets/ChallengeResponsePacket.pbi b/Commons/Networking/Packets/ChallengeResponsePacket.pbi new file mode 100644 index 0000000..70d0e88 --- /dev/null +++ b/Commons/Networking/Packets/ChallengeResponsePacket.pbi @@ -0,0 +1,101 @@ +; ============================================================================ +; ... +; ============================================================================ + + +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 diff --git a/Commons/Networking/Packets/GetLatestMessagePacket.pbi b/Commons/Networking/Packets/GetLatestMessagePacket.pbi new file mode 100644 index 0000000..07bdf62 --- /dev/null +++ b/Commons/Networking/Packets/GetLatestMessagePacket.pbi @@ -0,0 +1,99 @@ +; ============================================================================ +; ... +; ============================================================================ + + +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.] 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 diff --git a/Commons/Networking/Packets/GetMessagesPacket.pbi b/Commons/Networking/Packets/GetMessagesPacket.pbi new file mode 100644 index 0000000..b910232 --- /dev/null +++ b/Commons/Networking/Packets/GetMessagesPacket.pbi @@ -0,0 +1,138 @@ +; ============================================================================ +; ... +; ============================================================================ + + +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.] 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 diff --git a/Commons/Networking/Packets/HelloPacket.pbi b/Commons/Networking/Packets/HelloPacket.pbi new file mode 100644 index 0000000..e8ba060 --- /dev/null +++ b/Commons/Networking/Packets/HelloPacket.pbi @@ -0,0 +1,130 @@ +; ============================================================================ +; ... +; ============================================================================ + + +XIncludeFile "../Packets.pbi" + +; C2S auth request, sent sealed for the server's public key (Connections.pbi). +; ClientTopic, ClientNode: who the client is, each a name or an id in digits +; (Commons/Networking/Names.pbi), resolved by the server in its own names. +; ClientSessionKey: the public half of the client's key pair for this +; connection (Commons/Cryptography/Session.pbi). +Structure BakaShrot_AuthHello Extends BakaShrot_PacketBase + ClientTopic.s + 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\ClientTopic) <> #MsgPack_Error_Success + 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 + + ; ClientTopic + If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String + Goto DecodeFailed + EndIf + *Hello\ClientTopic = MsgPackReadString(*MsgPackData) + If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success + 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 diff --git a/Commons/Networking/Packets/LatestMessagePacket.pbi b/Commons/Networking/Packets/LatestMessagePacket.pbi new file mode 100644 index 0000000..3232016 --- /dev/null +++ b/Commons/Networking/Packets/LatestMessagePacket.pbi @@ -0,0 +1,157 @@ +; ============================================================================ +; ... +; ============================================================================ + + +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. +Structure BakaShrot_LatestMessage Extends BakaShrot_PacketBase + TopicId.l + NodeId.l + TopicName.s + NodeName.s + MessageId.q + JsonData.s +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 MsgPackWriteString(*MsgPackData, *Latest\JsonData) <> #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 + + ; JsonData + If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String + Goto DecodeFailed + EndIf + *Latest\JsonData = MsgPackReadString(*MsgPackData) + If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success + Goto DecodeFailed + EndIf + + ProcedureReturn *Latest + + ; Everything read so far is tainted, drop it. + DecodeFailed: + FreeStructure(*Latest) + ProcedureReturn 0 +EndProcedure diff --git a/Commons/Networking/Packets/ListNamesPacket.pbi b/Commons/Networking/Packets/ListNamesPacket.pbi new file mode 100644 index 0000000..d224fff --- /dev/null +++ b/Commons/Networking/Packets/ListNamesPacket.pbi @@ -0,0 +1,87 @@ +; ============================================================================ +; ... +; ============================================================================ + + +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 diff --git a/Commons/Networking/Packets/MessagePushedPacket.pbi b/Commons/Networking/Packets/MessagePushedPacket.pbi new file mode 100644 index 0000000..2a3b90f --- /dev/null +++ b/Commons/Networking/Packets/MessagePushedPacket.pbi @@ -0,0 +1,82 @@ +; ============================================================================ +; ... +; ============================================================================ + + +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 diff --git a/Commons/Networking/Packets/MessagesPacket.pbi b/Commons/Networking/Packets/MessagesPacket.pbi new file mode 100644 index 0000000..376224b --- /dev/null +++ b/Commons/Networking/Packets/MessagesPacket.pbi @@ -0,0 +1,219 @@ +; ============================================================================ +; ... +; ============================================================================ + + +XIncludeFile "../Packets.pbi" +XIncludeFile "GetMessagesPacket.pbi" + +; One message of a Messages answer. +Structure BakaShrot_MessagesEntry + MessageId.q + 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 = 16 + +; 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 MsgPackWriteString(*MsgPackData, *Answer\Messages()\JsonData) <> #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 + + ; 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 + Next + + ProcedureReturn *Answer + + ; Everything read so far is tainted, drop it. + DecodeFailed: + FreeStructure(*Answer) + ProcedureReturn 0 +EndProcedure diff --git a/Commons/Networking/Packets/NameResolvedPacket.pbi b/Commons/Networking/Packets/NameResolvedPacket.pbi new file mode 100644 index 0000000..59c9dc9 --- /dev/null +++ b/Commons/Networking/Packets/NameResolvedPacket.pbi @@ -0,0 +1,116 @@ +; ============================================================================ +; ... +; ============================================================================ + + +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 diff --git a/Commons/Networking/Packets/NamesListPacket.pbi b/Commons/Networking/Packets/NamesListPacket.pbi new file mode 100644 index 0000000..21219cf --- /dev/null +++ b/Commons/Networking/Packets/NamesListPacket.pbi @@ -0,0 +1,177 @@ +; ============================================================================ +; ... +; ============================================================================ + + +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 diff --git a/Commons/Networking/Packets/PushMessagePacket.pbi b/Commons/Networking/Packets/PushMessagePacket.pbi new file mode 100644 index 0000000..71e9128 --- /dev/null +++ b/Commons/Networking/Packets/PushMessagePacket.pbi @@ -0,0 +1,101 @@ +; ============================================================================ +; ... +; ============================================================================ + + +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.] PushTopics must allow it. +; The node is always the client's authenticated one, the client can't pick it. +; Answered with a MessagePushed or a RequestRefused. +Structure BakaShrot_PushMessage Extends BakaShrot_PacketBase + Topic.s + JsonData.s +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 + + ; 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 + + ProcedureReturn *Push + + ; Everything read so far is tainted, drop it. + DecodeFailed: + FreeStructure(*Push) + ProcedureReturn 0 +EndProcedure diff --git a/Commons/Networking/Packets/QueryRequestPacket.pbi b/Commons/Networking/Packets/QueryRequestPacket.pbi new file mode 100644 index 0000000..b612500 --- /dev/null +++ b/Commons/Networking/Packets/QueryRequestPacket.pbi @@ -0,0 +1,84 @@ +; ============================================================================ +; ... +; ============================================================================ + + +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 diff --git a/Commons/Networking/Packets/QueryResultPacket.pbi b/Commons/Networking/Packets/QueryResultPacket.pbi new file mode 100644 index 0000000..c49ecf9 --- /dev/null +++ b/Commons/Networking/Packets/QueryResultPacket.pbi @@ -0,0 +1,84 @@ +; ============================================================================ +; ... +; ============================================================================ + + +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 diff --git a/Commons/Networking/Packets/ReplicateMessagesPacket.pbi b/Commons/Networking/Packets/ReplicateMessagesPacket.pbi new file mode 100644 index 0000000..fe8c19e --- /dev/null +++ b/Commons/Networking/Packets/ReplicateMessagesPacket.pbi @@ -0,0 +1,177 @@ +; ============================================================================ +; ... +; ============================================================================ + + +XIncludeFile "../Packets.pbi" + +; One message of a ReplicateMessages batch. +Structure BakaShrot_ReplicatedMessage + MessageId.q + JsonData.s +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 = 16 + +; 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 and JSON. +; 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 MsgPackWriteString(*MsgPackData, *Batch\Messages()\JsonData) <> #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 + + *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 + + ; 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 + Next + + ProcedureReturn *Batch + + ; Everything read so far is tainted, drop it. + DecodeFailed: + FreeStructure(*Batch) + ProcedureReturn 0 +EndProcedure diff --git a/Commons/Networking/Packets/RequestRefusedPacket.pbi b/Commons/Networking/Packets/RequestRefusedPacket.pbi new file mode 100644 index 0000000..2fa4311 --- /dev/null +++ b/Commons/Networking/Packets/RequestRefusedPacket.pbi @@ -0,0 +1,83 @@ +; ============================================================================ +; ... +; ============================================================================ + + +XIncludeFile "../Packets.pbi" + +; S2C, answers a request the server won't fulfill, the connection stays open. +; Reason is only meant for logs and humans. +Structure BakaShrot_RequestRefused Extends BakaShrot_PacketBase + 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 + + *MsgPackData = MsgPackCreate(64) + If Not *MsgPackData + ProcedureReturn 0 + EndIf + + If Not BakaShrot_WritePacketBase(*Refused, *MsgPackData) + 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 + + *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 + + ; 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 diff --git a/Commons/Networking/Packets/ResolveNamePacket.pbi b/Commons/Networking/Packets/ResolveNamePacket.pbi new file mode 100644 index 0000000..fc9d84d --- /dev/null +++ b/Commons/Networking/Packets/ResolveNamePacket.pbi @@ -0,0 +1,107 @@ +; ============================================================================ +; ... +; ============================================================================ + + +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 diff --git a/Commons/Networking/Packets/SyncStatePacket.pbi b/Commons/Networking/Packets/SyncStatePacket.pbi new file mode 100644 index 0000000..af4a182 --- /dev/null +++ b/Commons/Networking/Packets/SyncStatePacket.pbi @@ -0,0 +1,279 @@ +; ============================================================================ +; ... +; ============================================================================ + + +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 diff --git a/Commons/Networking/Packets/SyncStateRequestPacket.pbi b/Commons/Networking/Packets/SyncStateRequestPacket.pbi new file mode 100644 index 0000000..a502ee6 --- /dev/null +++ b/Commons/Networking/Packets/SyncStateRequestPacket.pbi @@ -0,0 +1,65 @@ +; ============================================================================ +; ... +; ============================================================================ + + +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 diff --git a/Commons/Networking/SocketWait.pbi b/Commons/Networking/SocketWait.pbi new file mode 100644 index 0000000..8c2e44b --- /dev/null +++ b/Commons/Networking/SocketWait.pbi @@ -0,0 +1,124 @@ +; ============================================================================ +; 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 diff --git a/Commons/Threading/Signal.pbi b/Commons/Threading/Signal.pbi new file mode 100644 index 0000000..427031e --- /dev/null +++ b/Commons/Threading/Signal.pbi @@ -0,0 +1,69 @@ +; ============================================================================ +; 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 diff --git a/Core/Config/Config.pbi b/Core/Config/Config.pbi deleted file mode 100644 index 4220ca8..0000000 --- a/Core/Config/Config.pbi +++ /dev/null @@ -1,260 +0,0 @@ -; ============================================================================ -; BakaShrot Config -; -; Loads and saves the node's configuration from/to an ini file via -; PureBasic's native Preferences library. -; -; Section layout: -; [BakaShrot] -> BakaShrot_CoreConfig -; [BakaShrot.Server] -> BakaShrot_CoreConfig\Server -; [BakaShrot.Client] -> BakaShrot_CoreConfig\Client -; [BakaShrot.Peer.] -> one BakaShrot_CoreConfig\Peers() entry per -; section; is only a key for this file, -; it is never sent on the wire. -; ============================================================================ - - -; Ini Section: [BakaShrot.Peer.] (one section per known peer) -Structure BakaShrot_PeerConfig - - ; Remote adress of the peer - ; Can be a domain name, IPV4, IPV6 - Host.s - - ; Remote port of the peer - ; 0-65535 - Port.u - - ; Remote node's GID - ; The connection will be aborted if it differs. - GroupId.u - - ; Remote node's node id - ; The connection will be aborted if it differs. - NodeId.u - - ; This peer's Ed25519 public key (Base64), used to verify the signature - ; on every packet it sends. See Networking/Cryptography.pbi. - PublicKey.s - -EndStructure - - -; Ini Section: [BakaShrot.Server] -Structure BakaShrot_ServerConfig - - ; IPV4 that it will be bound to - Host.s - - ; Used port - Port.u - - ; List of groups from which the server will attempt to replicate from. - ; Format: 0;1;100-150;200;... - List ReplicatingGroupIds.i() - -EndStructure - - -; Ini Section: [BakaShrot.Client] -Structure BakaShrot_ClientConfig - - ; No idea, feel free to suggest ideas - -EndStructure - - -; Ini Section: [BakaShrot] -Structure BakaShrot_CoreConfig - - ; This node's Ed25519 private key (Base64), used to sign every packet it - ; sends. Its matching public key must be handed to peers, who store it - ; as PublicKey in the relevant [BakaShrot.Peer.] section of THEIR - ; own config. See Networking/Cryptography.pbi. - PrivateKey.s - - ; Replication Group ID to which the node belongs. - ; Will be used during the connection phase to identify itself. - ; Will be used to set the messages' GID - ; Will be used by itself and other nodes to know which messages to replicate and which to ignore. - GroupId.u - - ; Node ID that uniquely represents the node within a replication group. - ; Will be used during the connection phase to identify itself. - ; Will be used to set the messages' NID - NodeId.u - - ; [BakaShrot.Server] - Server.BakaShrot_ServerConfig - - ; [BakaShrot.Client] - Client.BakaShrot_ClientConfig - - ; One [BakaShrot.Peer.] entry per map key. - Map Peers.BakaShrot_PeerConfig() - -EndStructure - - -Macro Ptr_BakaShrot_CoreConfig : i : EndMacro - - -; Parses a "0;1;100-150;200" style range list into a flat list of ids. -Procedure ParseGroupIdRanges(RangesString.s, List Ids.i()) - Protected i, Part.s, DashPos, FromId, ToId, Id - - ClearList(Ids()) - - For i = 1 To CountString(RangesString, ";") + 1 - Part = Trim(StringField(RangesString, i, ";")) - If Part = "" - Continue - EndIf - - DashPos = FindString(Part, "-") - If DashPos - FromId = Val(Left(Part, DashPos - 1)) - ToId = Val(Mid(Part, DashPos + 1)) - For Id = FromId To ToId - AddElement(Ids()) - Ids() = Id - Next - Else - AddElement(Ids()) - Ids() = Val(Part) - EndIf - Next - -EndProcedure - - -; Serializes a flat list of ids back into "id;id;id" form. -; (Ranges are not reconstructed on save; each id is written out individually.) -Procedure.s FormatGroupIdList(List Ids.i()) - Protected Result.s - - ForEach Ids() - If Result <> "" - Result + ";" - EndIf - Result + Str(Ids()) - Next - - ProcedureReturn Result -EndProcedure - - -Procedure.Ptr_BakaShrot_CoreConfig LoadConfig(IniFilePath.s) - Protected *Config.BakaShrot_CoreConfig - Protected GroupName.s, PeerName.s - - If Not OpenPreferences(IniFilePath) - ProcedureReturn 0 - EndIf - - *Config = AllocateStructure(BakaShrot_CoreConfig) - - PreferenceGroup("BakaShrot") - *Config\PrivateKey = ReadPreferenceString("PrivateKey", "") - *Config\GroupId = ReadPreferenceLong("GroupId", 0) - *Config\NodeId = ReadPreferenceLong("NodeId", 0) - - PreferenceGroup("BakaShrot.Server") - *Config\Server\Host = ReadPreferenceString("Host", "") - *Config\Server\Port = ReadPreferenceLong("Port", 0) - ParseGroupIdRanges(ReadPreferenceString("ReplicatingGroupIds", ""), *Config\Server\ReplicatingGroupIds()) - - ; [BakaShrot.Client] has no fields yet. - - ; Discover every [BakaShrot.Peer.] section dynamically, so adding a - ; peer never needs a second "list of peer names" kept in sync by hand. - ExaminePreferenceGroups() - While NextPreferenceGroup() - GroupName = PreferenceGroupName() - - If Left(GroupName, Len("BakaShrot.Peer.")) = "BakaShrot.Peer." - PeerName = Mid(GroupName, Len("BakaShrot.Peer.") + 1) - If PeerName <> "" - AddMapElement(*Config\Peers(), PeerName) - *Config\Peers()\Host = ReadPreferenceString("Host", "") - *Config\Peers()\Port = ReadPreferenceLong("Port", 0) - *Config\Peers()\GroupId = ReadPreferenceLong("GroupId", 0) - *Config\Peers()\NodeId = ReadPreferenceLong("NodeId", 0) - *Config\Peers()\PublicKey = ReadPreferenceString("PublicKey", "") - EndIf - EndIf - Wend - - ClosePreferences() - - ProcedureReturn *Config -EndProcedure - - -Procedure.i SaveConfig(IniFilePath.s, *Config.BakaShrot_CoreConfig) - - If Not CreatePreferences(IniFilePath) - ProcedureReturn #False - EndIf - - PreferenceGroup("BakaShrot") - WritePreferenceString("PrivateKey", *Config\PrivateKey) - WritePreferenceLong("GroupId", *Config\GroupId) - WritePreferenceLong("NodeId", *Config\NodeId) - - PreferenceGroup("BakaShrot.Server") - WritePreferenceString("Host", *Config\Server\Host) - WritePreferenceLong("Port", *Config\Server\Port) - WritePreferenceString("ReplicatingGroupIds", FormatGroupIdList(*Config\Server\ReplicatingGroupIds())) - - PreferenceGroup("BakaShrot.Client") - ; No fields yet. - - ForEach *Config\Peers() - PreferenceGroup("BakaShrot.Peer." + MapKey(*Config\Peers())) - WritePreferenceString("Host", *Config\Peers()\Host) - WritePreferenceLong("Port", *Config\Peers()\Port) - WritePreferenceLong("GroupId", *Config\Peers()\GroupId) - WritePreferenceLong("NodeId", *Config\Peers()\NodeId) - WritePreferenceString("PublicKey", *Config\Peers()\PublicKey) - Next - - ClosePreferences() - - ProcedureReturn #True -EndProcedure - - -Procedure FreeConfig(*Config.BakaShrot_CoreConfig) - FreeStructure(*Config) -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 - - Define *Config.BakaShrot_CoreConfig = LoadConfig("schema.ini") - - If *Config - Debug "PrivateKey: " + *Config\PrivateKey - Debug "GroupId: " + Str(*Config\GroupId) - Debug "NodeId: " + Str(*Config\NodeId) - - Debug "Server: " + *Config\Server\Host + ":" + Str(*Config\Server\Port) - ForEach *Config\Server\ReplicatingGroupIds() - Debug " Replicating group: " + Str(*Config\Server\ReplicatingGroupIds()) - Next - - ForEach *Config\Peers() - Debug "Peer '" + MapKey(*Config\Peers()) + "': " + *Config\Peers()\Host + ":" + Str(*Config\Peers()\Port) + " PublicKey=" + *Config\Peers()\PublicKey - Next - - SaveConfig("schema_out.ini", *Config) - - FreeConfig(*Config) - Else - Debug "Failed to load schema.ini" - EndIf - -CompilerEndIf diff --git a/Core/Config/schema.ini b/Core/Config/schema.ini deleted file mode 100644 index b86cfcb..0000000 --- a/Core/Config/schema.ini +++ /dev/null @@ -1,56 +0,0 @@ -; BakaShrot 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. - -[BakaShrot] -; Config shared by every type of config. - -; This node's Ed25519 private key (Base64), used to sign every packet it -; sends. Its matching public key must be handed to peers, who store it as -; PublicKey below in THEIR own config. See Networking/Cryptography.pbi. -PrivateKey = - -; Replication Group ID to which this node belongs. -GroupId = - -; Node ID that uniquely represents this node within its replication group. -NodeId = - - -[BakaShrot.Server] -; IPV4 that the server will be bound to. -Host = - -; Used port. -Port = - -; List of groups from which the server will attempt to replicate. -; Format: 0;1;100-150;200;... -ReplicatingGroupIds = - -; Amount of threads used for networking-related tasks -NetThreadPoolSize = 4 - - -[BakaShrot.Client] -; No fields yet. - - -; One [BakaShrot.Peer.] section per peer this node talks to. -; 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 = - -; Remote node's GID. The connection is aborted if it differs. -GroupId = - -; Remote node's node id. The connection is aborted if it differs. -NodeId = - -; This peer's Ed25519 public key (Base64), used to verify the signature on -; every packet it sends. See Networking/Cryptography.pbi. -PublicKey = diff --git a/Core/Storage/Storage.pbi b/Core/Storage/Storage.pbi deleted file mode 100644 index 0a6ee56..0000000 --- a/Core/Storage/Storage.pbi +++ /dev/null @@ -1,203 +0,0 @@ -; ============================================================================ -; 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_v1.dbml in this same folder. -; ============================================================================ - - -UseSQLiteDatabase() - - -; One row of the "data" table (see db_schema_v1.dbml). -Structure BakaShrot_Message - MessageId.i - JsonData.s -EndStructure - - -; Opens (and creates, if missing) the SQLite database at DatabasePath. -; Returns the PureBasic database number, or 0 if the file could not be opened. -Procedure.i OpenStorageDatabase(DatabasePath.s) - ProcedureReturn OpenDatabase(#PB_Any, DatabasePath, "", "") -EndProcedure - - -; Creates the tables and indexes described by db_schema_v1.dbml, if they -; don't exist yet. Plain "CREATE IF NOT EXISTS" for now - a real versioned -; upgrade mechanism (DbUpdater) will replace this later. -Procedure.i SetupStorageDatabase(DbId.i) - - If Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS archives (" + - "delete_by INTEGER NOT NULL, " + - "message_data TEXT NOT NULL)") - ProcedureReturn #False - EndIf - - If Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS data (" + - "group_id INTEGER NOT NULL, " + - "node_id INTEGER NOT NULL, " + - "message_id INTEGER NOT NULL, " + - "message_data TEXT NOT NULL)") - ProcedureReturn #False - EndIf - If Not DatabaseUpdate(DbId, "CREATE INDEX IF NOT EXISTS idx_data_group_node ON data (group_id, node_id)") - ProcedureReturn #False - EndIf - If Not DatabaseUpdate(DbId, "CREATE INDEX IF NOT EXISTS idx_data_message_id ON data (message_id)") - ProcedureReturn #False - EndIf - - ; Not used yet, but created now so the on-disk schema already matches - ; db_schema_v1.dbml. - If Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS attachements (" + - "group_id INTEGER NOT NULL, " + - "node_id INTEGER NOT NULL, " + - "message_id INTEGER NOT NULL, " + - "attachement_data BLOB NOT NULL)") - ProcedureReturn #False - EndIf - If Not DatabaseUpdate(DbId, "CREATE INDEX IF NOT EXISTS idx_attachements_group_node ON attachements (group_id, node_id)") - ProcedureReturn #False - EndIf - If Not DatabaseUpdate(DbId, "CREATE INDEX IF NOT EXISTS idx_attachements_message_id ON attachements (message_id)") - ProcedureReturn #False - EndIf - - ProcedureReturn #True -EndProcedure - - -; Inserts one JSON message into the "data" table. -Procedure.i Insert(DbId.i, GroupId.i, NodeId.i, MessageId.i, JsonData.s) - SetDatabaseLong(DbId, 0, GroupId) - SetDatabaseLong(DbId, 1, NodeId) - SetDatabaseLong(DbId, 2, MessageId) - SetDatabaseString(DbId, 3, JsonData) - - ProcedureReturn DatabaseUpdate(DbId, "INSERT INTO data (group_id, node_id, message_id, message_data) VALUES (?, ?, ?, ?)") -EndProcedure - - -; Gets every message stored for a given group_id/node_id pair - the -; "(group_id, node_id)" index - ordered by message_id. -Procedure.i GetMessagesByGroupAndNode(DbId.i, GroupId.i, NodeId.i, List Messages.BakaShrot_Message()) - ClearList(Messages()) - - SetDatabaseLong(DbId, 0, GroupId) - SetDatabaseLong(DbId, 1, NodeId) - - If Not DatabaseQuery(DbId, "SELECT message_id, message_data FROM data WHERE group_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 -; group/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. Kept basic on purpose - no paging, no group/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 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 group_id/node_id pair, -; or -1 if there's none yet. Will likely grow into a cached counter later. -Procedure.i GetLatestMessageId(DbId.i, GroupId.i, NodeId.i) - Protected MessageId.i = -1 - - SetDatabaseLong(DbId, 0, GroupId) - SetDatabaseLong(DbId, 1, NodeId) - - If DatabaseQuery(DbId, "SELECT COALESCE(MAX(message_id), -1) FROM data WHERE group_id = ? AND node_id = ?") - If NextDatabaseRow(DbId) - MessageId = GetDatabaseLong(DbId, 0) - EndIf - FinishDatabaseQuery(DbId) - EndIf - - ProcedureReturn MessageId -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 - - 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() - GetMessagesByGroupAndNode(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 diff --git a/Design/Cryptography.md b/Design/Cryptography.md new file mode 100644 index 0000000..0673bcb --- /dev/null +++ b/Design/Cryptography.md @@ -0,0 +1,225 @@ +# 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/KeyGen`. | +| `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. | + +- **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.] PublicKeys` and + `[BakaShrot.Peer.] 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/KeyGen`, which `Build.ps1` runs on every build. +- **Wiping:** + - Wiped from memory after use: KeyGen; 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 + identity (topic, node), 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.]` lists both this key and this + identity. +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. diff --git a/Design/Packets.md b/Design/Packets.md new file mode 100644 index 0000000..a90b298 --- /dev/null +++ b/Design/Packets.md @@ -0,0 +1,313 @@ +# 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 | `Server/Networking/Peers.pbi` | +| 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` | +| 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` | + +## 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` (3: the + Hello sealed, a key per connection, everything after the + ChallengeRequest encrypted; 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 the + config can name them (`[BakaShrot.Topics]`, `[BakaShrot.Nodes]`). 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.*`) 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 | `ClientTopic` str (ref), `ClientNode` str (ref), `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 | 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, `JsonData` str | | +| 12 | RequestRefused | S→C | `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) and `JsonData` str | 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`) and `JsonData` str | | + +## 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. + - **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 identity (topic and node refs) + 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 refs must + resolve to its ids, the key must decode to 32 bytes, and one + [BakaShrot.Client.] must list both this key and this identity +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: the topics of its `Identities`). + - Whether it's a **peer**: its key and identity match a + `[BakaShrot.Peer.]`, and then its `AcceptTopics`. + +### Client requests + +``` +PushMessage(t, json) AllowWrite, t in PushTopics ("" = own topic), 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 -> 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.]`, +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: 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 +``` + +- **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. + +## Code conventions + +- **Encode:** `BakaShrot_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_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/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 `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. diff --git a/Design/Release.md b/Design/Release.md new file mode 100644 index 0000000..73a6c9d --- /dev/null +++ b/Design/Release.md @@ -0,0 +1,235 @@ +# 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\\` and zips it. `` is `-Version`, or +`-`, 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 `KeyGen.exe`, writes a server and a client config; +- pushes two messages, reads the latest back by name, reads both with + `GetMessages.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 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), but against `Build\` (PB 5.73) +and `BenchServer.exe`, not the release. + +## 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, even with `synchronous = + NORMAL` (only a power loss or an OS crash can). **Not tested against + the release yet**, `Names-Test.ps1` restarts a server but doesn't check + these. +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. +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**: `ListNames`, `GetMessages --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 (3) 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, + decide if that's fine (`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-12407 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. diff --git a/Design/ReplicationIssues.md b/Design/ReplicationIssues.md new file mode 100644 index 0000000..73efc46 --- /dev/null +++ b/Design/ReplicationIssues.md @@ -0,0 +1,168 @@ +# 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 (accepted for now) + +**When:** the same topic/node id is written to on two servers, for example +when a client identity is registered on both and pushes to each while they +can't reach each other. This is a configuration issue that """shouldn't""" +happen in real use. + +**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.]` 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`. diff --git a/Design/StorageConcurrency.md b/Design/StorageConcurrency.md new file mode 100644 index 0000000..09b64c1 --- /dev/null +++ b/Design/StorageConcurrency.md @@ -0,0 +1,148 @@ +# 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 + `synchronous = NORMAL` on every connection (`#BakaShrot_Storage_Synchronous` + in `Storage.pbi`). 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. +- **The tradeoff of NORMAL:** commits are only synced at checkpoints. The + file can't get corrupted, but the last 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). Set it to `FULL` to sync every commit again. +- **`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** in thread-safe + mode. If it's shared by the whole program, an error message could show up + in the wrong thread's log or refusal. The data isn't affected. + `RunReadOnlyQuery()` only checks it after reading the rows on Linux, where + it could refuse a valid query because of another thread's error. On + Windows it asks SQLite instead (`sqlite3_errcode()` on its own + connection), 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. diff --git a/Design/Suggestions.md b/Design/Suggestions.md new file mode 100644 index 0000000..d474471 --- /dev/null +++ b/Design/Suggestions.md @@ -0,0 +1,125 @@ +# 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`** (`#BakaShrot_Storage_Synchronous`): + the last commits before a power loss or an OS crash can be lost, and their + ids handed out again (drift). With group commit, `FULL` costs one sync per + transaction, not per push, so it may cost much less than it used to: worth + one benchmark run before deciding. +- **`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. diff --git a/Interactors/Python/bakashrot.py b/Interactors/Python/bakashrot.py new file mode 100644 index 0000000..2bfaf7d --- /dev/null +++ b/Interactors/Python/bakashrot.py @@ -0,0 +1,451 @@ +"""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()) + +Topics and nodes are "refs": a name ("logs") or an id (12, or "12"), ids +being the server's own. + +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. + +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. +""" + +from __future__ import annotations + +import configparser +import ctypes +import json +import os +import threading +import time +from dataclasses import dataclass, field +from typing import Any, Iterator, Optional, Union + +__all__ = [ + "Client", "Message", "MessagesPage", "NameEntry", "NamesList", + "BakaShrotError", "RefusedError", "ConnectionLostError", + "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 BakaShrotError(Exception): + """Something failed: the DLL couldn't be loaded, a bad argument, ...""" + + +class RefusedError(BakaShrotError): + """The server refused the request, the connection is still open.""" + + def __init__(self, reason: str): + super().__init__(reason or "Refused") + self.reason = reason + + +class ConnectionLostError(BakaShrotError): + """The connection failed or was closed, connect() again to go on.""" + + +@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).""" + + id: int + topic: str + node: str + topic_id: int + node_id: int + data: str + + def json(self) -> Any: + """The data parsed as JSON, raises ValueError if it isn't.""" + return json.loads(self.data) + + +@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_SetPrivateKeyA": (I, [P]), + "BakaShrot_SetPublicKeyA": (I, [P]), + "BakaShrot_SetServerPublicKeyA": (I, [P]), + "BakaShrot_SetTopicA": (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_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?") 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 (KeyGen.exe). + server_public_key: the server's Ed25519 public key in Base64, it must + prove it holds the matching private key. + topic, node: who the client is, names or ids, as the server's + [BakaShrot.Client.] Identities lists them. + """ + + _connected_client: Optional["Client"] = None + + def __init__(self, private_key: str, public_key: str, server_public_key: str, topic: Ref, 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.topic = topic + 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, Topic, Node, ServerHost, ServerPort.""" + parser = configparser.ConfigParser(interpolation=None) + if not parser.read(path, encoding="utf-8-sig"): + raise BakaShrotError(f"Failed to open '{path}'") + 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}") + return value.strip() + + return cls(get("PrivateKey"), get("PublicKey"), get("ServerPublicKey"), + get("Topic", section.get("TopicId")), get("Node", section.get("NodeId")), + get("ServerHost"), int(get("ServerPort")), dll_path) + + # --- Connection -------------------------------------------------------- + + def connect(self) -> "Client": + """Connects and authenticates, raises BakaShrotError on failure.""" + 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") + if self.connected: + return self + dll = self._dll + if not dll.SetPrivateKeyA(self.private_key.encode("ascii")): + raise BakaShrotError("Invalid private key") + if not dll.SetPublicKeyA(self.public_key.encode("ascii")): + raise BakaShrotError("Invalid public key") + if not dll.SetServerPublicKeyA(self.server_public_key.encode("ascii")): + raise BakaShrotError("Invalid server public key") + if not dll.SetTopicA(_ref(self.topic)): + raise BakaShrotError(f"Invalid topic {self.topic!r}") + if not dll.SetNodeA(_ref(self.node)): + raise BakaShrotError(f"Invalid node {self.node!r}") + if not dll.ConnectA(self.host.encode("utf-8"), self.port): + raise ConnectionLostError(f"Failed to connect and authenticate 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") + + def _failed(self, what: str) -> BakaShrotError: + """The error for a failed request: refused, or the connection is gone.""" + if self._dll.IsConnected(): + reason = self._dll.string(self._dll.GetRefusalReasonA) + return RefusedError(reason) if reason else BakaShrotError(f"{what} failed") + if Client._connected_client is self: + Client._connected_client = None + return ConnectionLostError(f"{what}: the connection to the server failed") + + # --- Requests ---------------------------------------------------------- + + def push(self, data: Any, topic: Optional[Ref] = None) -> int: + """Pushes a message into topic (default: the client's own), 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.""" + 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}") + with self._lock: + self._check_connected() + message_id = self._dll.PushMessageToA(b"" if topic is None else _ref(topic), encoded) + if message_id < 1: + raise self._failed("Push") + return message_id + + 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)) + + 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.reason.startswith("No message for"): + 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.""" + 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"]] diff --git a/Interactors/Python/check_bakashrot.py b/Interactors/Python/check_bakashrot.py new file mode 100644 index 0000000..c2d2759 --- /dev/null +++ b/Interactors/Python/check_bakashrot.py @@ -0,0 +1,168 @@ +"""Checks bakashrot.py against a running server, run by Tests/Python-Test.ps1. + +Usage: python check_bakashrot.py + 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 sys +import threading +import time + +import bakashrot +from bakashrot import BakaShrotError, Client, ConnectionLostError, 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=""): + try: + function() + except error_type as error: + return contains in str(error), f"{type(error).__name__}: {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) + + 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) + + 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) + + # --- 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'") + check("Unknown node: RefusedError", 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") + check("Push to an unknown topic: RefusedError", 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") + 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}") + +check("close(): disconnected", not kitchen.connected) +ok, detail = raises(lambda: kitchen.push("x"), ConnectionLostError) +check("A request once closed: ConnectionLostError", 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'") + check("A topic not in its ReadTopics: RefusedError", ok, detail) + ok, detail = raises(lambda: lounge.query("SELECT 1"), RefusedError, "Not allowed to query") + check("Not allowed to query: RefusedError", ok, detail) + +print() +print("All checks passed" if fails == 0 else f"{fails} check(s) failed") +sys.exit(1 if fails else 0) diff --git a/Interactors/Python/example.py b/Interactors/Python/example.py new file mode 100644 index 0000000..89cbb9d --- /dev/null +++ b/Interactors/Python/example.py @@ -0,0 +1,42 @@ +"""Example app: catches up on a topic/node's messages, then follows new ones. + +Usage: python example.py [--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: + .\\PushMessage.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 {client.topic}:{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) diff --git a/Interactors/Python/notes.txt b/Interactors/Python/notes.txt new file mode 100644 index 0000000..f5a77dc --- /dev/null +++ b/Interactors/Python/notes.txt @@ -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. diff --git a/Libs/redist/README.md b/Libs/redist/README.md new file mode 100644 index 0000000..8fed8d8 --- /dev/null +++ b/Libs/redist/README.md @@ -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" ` +- x86 isn't built, so there's no `x86/`. diff --git a/Libs/redist/x64/vcruntime140.dll b/Libs/redist/x64/vcruntime140.dll new file mode 100644 index 0000000000000000000000000000000000000000..410f3a7d12c196719c0a52d68fc885ecb4ce36d1 GIT binary patch literal 178616 zcmdSCd3;pW-S|J*V1VEqlxR?pQG-TNjK(Dx&>5J4J2+8Xz_XTzka?X z_ug~Q_F2wnJD+o>?y{AhB9F&Y%)fNn<5|m9{tKwT-~MMWuMZmeW`VzH{*719|K9cf#_!#5!;LZjm9zcx<2U%PxxpVg|04hOH(oV+%;3QTE8MPc z+IPj^(;qx_X69dXMD?sQc^>!f&u5;k%ByD{>b^gX>r;oFF>92%o;m9TbvcGuCI`?eQG#A5?hIsh)oncs$LzwBbqa zed@l2JAGg1@$}<%Aphj5{_CU=Bwqb+5%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000000..7376d72 --- /dev/null +++ b/Notes.md @@ -0,0 +1,368 @@ +# BakaShrot - working notes + +Where things stand and what's next, as of 2026-11-08. The detailed docs are in +`Design/`: + +| Doc | About | +|---|---| +| `Design/Packets.md` | The protocol: framing, every packet, flows, conventions, how to add a packet. | +| `Design/Cryptography.md` | What libsodium is used for: the handshake proving both ends, the connections' encryption. What isn't done, and ideas for abstracting it. | +| `Design/ReplicationIssues.md` | Known replication problems, with benchmarks. | +| `Design/StorageConcurrency.md` | One connection per thread, WAL, the write mutex and the writer (done), and what's left. | +| `Design/Suggestions.md` | Improvements not done yet: pipelined pushes, faster replication, smaller ones. | +| `Design/Release.md` | The release smoke test, what's missing for 1.0.0, the (fixed) silent query failure, notes for CI/CD. | + +## Where things stand + +- **Build:** `powershell -ExecutionPolicy Bypass -File Build.ps1` + - Extracts libsodium and SQLite from `Libs/`, builds everything with + PureBasic 5.73 (`-Compiler` for another) into `Build/`, and generates + keys and configs for two servers (same names, different ids) and a + client. + - Then runs the first server. Its console takes `quit`, `restart`, + `vacuum`, `names` and `help`. +- **Server:** + - Every connection is encrypted, and both ends prove who they are: the + client with an Ed25519 challenge, the server by signing the handshake + with the key its clients know (protocol 3, `Design/Cryptography.md`). + - Clients can push messages (usually JSON, anything is stored, flagged + in `is_json`), read the latest one of a topic/node pair or a run of + them after an id, resolve names, and run raw read-only SQL, each depending on + per-client `AllowRead`, `AllowWrite`, `AllowQuery`, `PushTopics` and + `ReadTopics`. Topics and nodes by name or id, see below. + - Links to its peers, retries when that fails, and replicates the missing + messages in batches (`PeerBatchSize`). + - One thread per client and per peer, each with its own SQLite connection. + - The root thread can stop every worker (restart, vacuum). +- **Client:** a DLL with A/W string exports, PureBasic prototypes in + `Client/BakaShrot_Client_Prototypes.pbi`, and tools in `Tools/`: + `PushMessage`, `GetLatestMessage`, `GetMessages` (with `--follow`), + `Resolve`, `ListNames`, `Query`, `KeyGen`. +- **Python:** `Interactors/Python/bakashrot.py`, over the DLL with ctypes, + no dependencies, and `example.py`. +- **Release:** `Release.ps1` builds with PB 6.40's C backend into + `Release\-\` with a zip, and smoke-tests it. + +## Renamed: group id -> topic id (2026-11-07) + +- Everywhere: code (`TopicId`, `ReplicatingTopicIds`, `IsReplicatingTopic`, + ...), config keys (`TopicId =`, `ReplicatingTopicIds =`), the DLL export + (`BakaShrot_SetTopicId`), the columns (`topic_id`), docs, bench + placeholders (`{TOPIC}`). Not "group commit", `PreferenceGroup*` or SQL + `GROUP BY`. The wire format is unchanged (fields are positional). +- **Old configs need their keys renamed** by hand, `GroupId` is no longer + read. Build.ps1 writes the new ones. +- **Old databases are migrated on start** (`MigrateStorageTopicIds()` in + `Storage.pbi`, schema `db_schema_v4.dbml`). Tested on a v2 and a v3 + database, and two servers replicating after both were migrated. + +## Done: topic and node names, filters (2026-11-07) + +- **Names are the shared identity, ids are per server.** `[BakaShrot.Topics]` + and `[BakaShrot.Nodes]` (`logs = 1`): "logs" can be 1 here and 200 on a + peer. Replication sends names, the receiver stores under its own ids. + Kept on purpose even though using the same ids everywhere would be + simpler: hand-written configs drift, names keep them matching anyway. + Rules for a "ref" (name or id): `Commons/Networking/Names.pbi`. +- **Only what's named on both servers replicates.** Unnamed topics and + nodes, and names the other side doesn't have, are dropped. The sync + state of every check-in lists every name the receiver takes from that + peer, and its wildcards, and the sender only sends those: no refusal at + every check-in. Unnamed ones still work locally, by id. +- **Wildcards (2026-11-07),** like file names: `*` any characters, `?` one, + no case, only names (`Commons/Networking/Names.pbi`). In every topic list + (`ReplicatingTopics`, `SendTopics`, `AcceptTopics`, `PushTopics`, + `ReadTopics`) and in the peers' new node lists `SendNodes` (default `*`) + and `AcceptNodes` (default: the nodes named here). In `AcceptTopics` / + `AcceptNodes`, `*` and wildcards also take names this server doesn't have + (`BakaShrot_Names_Ingest()`): highest free id counting down from 65535, + origin "peer". So `AcceptNodes = kitchen-*` saves listing every kitchen + node on every server. Clients still can't create topics by name. +- **A peer authenticates by name:** its own topic and node must be named the + same on the servers it links to (it sends its name when it has one). +- **Everywhere a topic or node goes, a name or an id:** config, the Hello, + requests, tools, client.ini. Keys: `Topic`, `Node`, `ReplicatingTopics` + (`TopicId`, `NodeId`, `ReplicatingTopicIds` still read when the new ones + are missing, in server configs and client.ini). +- **Filters:** per client `PushTopics` / `ReadTopics` (default: its + identities' topics, as before), per peer `SendTopics` / `AcceptTopics` + (default: `ReplicatingTopics`). `*` = every topic. A push picks its topic + (`PushMessage -t sensors`), never its node. +- **The config wins at start,** except when it would move a name to another + id than the one its messages are under: the server then refuses to start + and says which id to use (`Server/Storage/Names.pbi`). +- **Seeing the names:** the server's `names` console command, the + `ListNames` tool (`BakaShrot_ListTopics/Nodes()` + `BakaShrot_GetNamesList()` + as JSON, request `ListNames`), `Resolve` for one. +- **Clients:** `BakaShrot_ResolveTopic/Node()`, `BakaShrot_PushMessageTo()`, + `BakaShrot_GetLatestMessageOf()`, the answer's names and ids. Raw + queries: `SELECT * FROM messages WHERE topic = 'logs' AND node = + 'kitchen'` (a view over `data` with `topics` and `nodes`, uses the + indexes). No foreign keys from `data`, see the evaluation below. +- **Protocol version 2:** v1 servers and clients can't talk to v2 ones. +- **Tested:** `Tests/Names-Test.ps1`, 44 checks: two servers with different + ids for the same names, old and new keys, filters, resolving, listing, + translation both ways, a node and a topic named on one side only, an + unnamed node, wildcards taking a topic and a node, a `SendNodes` filter, + no refusals in the logs, the start-up conflict. + Bench: `-Names Wildcard` (each server names only its own nodes, the + others come by `AcceptNodes = n*`), results in + `Tests/Bench/Results-2026-11-07.md`. + Release.ps1 on PB 6.40. Bench (every node named on every server): ~37,000 + msg/s flat out for 4 servers, p99 0.9 ms at 10 x 50. +- **For later:** + - **Warn about dropped names.** `BakaShrot_Names_NoteDropped()` is called + wherever something isn't replicated because one side doesn't know it + (unnamed here, not taken by the peer, unknown to the peer, refused + on arrival), but does nothing: it runs at every check-in, so a plain + log line would spam. Make it warn once per peer and name, and again + only when that changes. + - **Two conventions for "unnamed":** `NameResolved` and `NamesList` give + "" (with origin "id"), `LatestMessage` gives the id in digits. Still + the case: both work, but pick one if more answers carry names. + - Names stay in the database once given: removing one from the config + keeps it (origin stays "config") until renamed. + - The sync state lists every named node the receiver takes from that + peer, every check-in (all of them by default): fine for thousands, a + lot for tens of thousands (65536 at most, and the whole list every + check-in). Wildcards help, + since a node taken by `AcceptNodes = kitchen-*` needn't be named first, + but once taken it has a name and is listed too. + - Names a wildcard added (origin "peer") are never removed, even if the + peer stops sending them or the wildcard goes away. + +Evaluation that led to it: enforced foreign keys from `data` cost ~1 % per +insert, but an unknown id would fail a whole replicated batch +(`INSERT OR IGNORE` doesn't skip FK violations), and adding them to an +existing `data` means rebuilding the table. So: name tables, joined, no FKs. + +## Done: big messages (2026-11-08) + +- **Packets up to 16 MB once authenticated** (`#BakaShrot_MaxPacketSize`), + 4 KB before (`#BakaShrot_MaxHandshakePacketSize`): a frame announcing more + is cut as soon as its size arrived, so anyone can connect but only those + with a key get to make the other end hold big frames. The server lifts + the limit (`BakaShrot_Inbox_Lift()`) before sending AuthAccepted, the + client once it got it. Same protocol version: only the limit changed. +- **Pushes are capped at `#BakaShrot_MaxMessageSize`** (16 MB - 4 KB) of + UTF-8, refused above (the DLL refuses it before sending), so a + stored message fits in every packet that carries it: LatestMessage, a + replicated batch of one. The "too big to replicate" stop can't happen + anymore. +- **The inbox** grows by doubling, keeps a read offset instead of moving + what's left after every packet (pipelined small packets in a 32 MB inbox + would have moved megabytes each, under the server's mutex), and frees + its buffer once emptied if it's 256 KB or more. +- **Replication batches stay ~64 KB** (`#BakaShrot_ReplicateBatchBytes`), as + before, a bigger message goes alone, and reading rows stops at that much. +- **Pushes aren't checked to be JSON anymore:** stored as they are, and + SQLite flags them in `is_json` (`json_valid()` on insert), like replicated + ones always were. PureBasic's `ParseJSON()` was the only thing that looked + inside messages, and took 23 s for 16 MB. Queries using `->>` on messages + that may not be JSON need `WHERE is_json = 1` (the bench queries, the + release test and `GetValuesAtJsonPath()` have it): SQLite's JSON functions + fail the whole query on a malformed row. That failure used to be silent + (no rows, or only the first ones), it's refused with SQLite's message now: + see open item 5 and `Design/Release.md`. `ReadString()` with + `#PB_File_IgnoreEOL` too (6 s), the tools read files in one go now + (`ToolClient_ReadTextFile()`). +- **Tested:** `Tests/BigMessages-Test.ps1`, 38 checks: frames over 4 KB cut + before authenticating, pushes of 100 KB / 1 MB / just under the cap (0.7 + s), over it refused, non-JSON stored with is_json = 0 (10 edge cases), replicated intact to the + other server, a 16 MB read back from it (0.5 s), small ones still + batched. `Names-Test.ps1` and the handshake test still pass. +- **Left:** attachments for real files (the unused `attachements` table: + the message references a blob sent in chunks, only when wanted), if more + than 16 MB is ever needed. Memory: an authenticated connection can hold + up to ~32 MB of inbox (64 MB in the worst case of the growth), plus the + packet being handled. + +## Done: reading runs of messages, Python client (2026-11-08) + +- **GetMessages / Messages** (packet types 22, 23, `Design/Packets.md`): the + messages of a topic/node after an id, in id order, at most `Limit` + (1-10000), stopped at ~1 MB (`#BakaShrot_MessagesBatchBytes`, a bigger + one alone), with `More` when others follow. Same permissions as + GetLatestMessage. No messages isn't a refusal. Same protocol version: an + older server aborts the connection on it (unexpected packet). +- **Server:** `BakaShrot_NetClient_HandleGetMessages()`. `GetMessagesAfter()` + (`Storage.pbi`) asks for one row more than the limit and tells whether + more follow (`*More`, optional, the peers don't use it). +- **DLL:** `BakaShrot_GetMessagesA/W(Topic, Node, AfterMessageId, Limit)` + returns how many came (-1 on failure), the first one selected; + `BakaShrot_SelectMessage(Index)` selects the others for the existing + `BakaShrot_GetMessage*()` getters, `BakaShrot_GetMessageCount()`, + `BakaShrot_HasMoreMessages()`. GetLatestMessage fills the same list (one + message). The DLL checks the answer is about what it asked, no more than + asked, after the asked id. +- **Tool:** `GetMessages [--after ] [--limit ] + [--follow] [--interval ] [ClientIni]`: one line per message, id, tab, + data as stored. `--follow` polls every 500 ms once caught up, exits 1 when + the connection fails. Polling, not pushed by the server: fine for a few + followers, a subscription would be the next step if many follow. +- **Python** (`Interactors/Python/bakashrot.py`): `Client(...)` or + `Client.from_ini()`, `push()` (a str as is, anything else as JSON), + `latest()` (None if none), `get_messages()` -> page with `.more`, + `iter_messages()`, `follow()`, `resolve_topic/node()`, `list_topics/nodes()`, + `query()` / `query_raw()`. `RefusedError` (still connected) vs + `ConnectionLostError`. Uses the DLL's UTF-8 exports, a lock serializes + calls. **One connection per process** (the DLL's globals): a second + Client can't connect while one is. ~9,600 pushes/s on one connection, + against ~75/s launching `PushMessage.exe` each time. +- **Released:** `GetMessages.exe` and `python\` (bakashrot.py, example.py), + the smoke test reads both messages back with the tool and with Python + (if `python` is on the PATH). +- **Tested:** `Tests/GetMessages-Test.ps1` (27 checks: limits, after an id / + latest, by ids, refusals, non-JSON and multi-line data, 600 KB / 3 MB + ones split over answers, `--follow` picking up new pushes and failing + when the server stops), `Tests/Python-Test.ps1` (32 checks, through + `check_bakashrot.py`: pages and `more`, iteration, Unicode, empty and + non-JSON data, is_json, 700 KB ones one per answer, refusals keep the + connection, follow() from another thread, one connection per process). + `BigMessages-Test.ps1`'s raw-frame check now accepts "too much data" as + well as "invalid frame" (which one is down to timing, both cut it right + away), from unauthenticated clients only. +- **Left:** a reconnect in `--follow` and `follow()`; server-pushed + subscriptions instead of polling; several connections per process (a + handle-based DLL API); reading back a range in reverse (the last N). + +## Done: encrypted connections, the server proves itself (2026-11-08) + +- **Protocol version 3:** the Hello is sealed for the server's public key, + each connection gets its own keys from an exchange both ends sign, and + everything after the ChallengeRequest is encrypted. v2 clients and + servers can't talk to v3 ones. Details: `Design/Cryptography.md`. +- **Every client needs the server's public key:** `client.ini`'s + `ServerPublicKey` (`Build.ps1` and `Release.ps1` already wrote it), + `BakaShrot_SetServerPublicKey()` in the DLL, `server_public_key` in + `bakashrot.py` (third argument of `Client()`). The server logs it when it + starts. A peer section's `PublicKey` is now required: it's who the link + must reach. +- **Code:** `Commons/Cryptography/Session.pbi` (sealed Hello, key exchange), + `Cipher.pbi` (unchanged but for `_EncryptTo()`), the handshake in + `Connections.pbi`, `Outbound.pbi` and `Networking.pbi`. Encrypting is in + the framing (`BakaShrot_SendPacket()` takes the cipher, + `BakaShrot_OpenFrame()`), the request handlers didn't change. +- **Tested:** `Tests/CipherTest.pb` 56 checks, `Tests/wire_check.py` (in + `Python-Test.ps1`) through a recording proxy, every other test and the + release's smoke test over encrypted connections, peer links included. +- **Left:** see `Design/Cryptography.md`'s "What's NOT done": per-message + signatures for replication, keys in plain-text inis, rotation. + +## Threat model (2026-11-08) + +BakaShrot is an **internal tool, on trusted machines and a trusted +network**, not exposed to the internet. So: + +- The encryption and the server proving itself are defence in depth: they + stop a misconfigured client from talking to the wrong server and keep + data off the wire in clear, they aren't holding off attackers. +- What's left on the security side is low priority (below), unless the + deployment changes. If it ever faces an untrusted network, start with + per-message signatures, rate limiting the handshake, and keys out of + plain-text inis. +- Correctness, durability and operations matter more: losing or mixing up + data, or a server that can't be run unattended, hurts on day one. + +## Open items, by importance (for that internal tool) + +### Operations and correctness + +1. **The server needs a console, and can't be stopped cleanly without + one.** It reads its commands from the console window (`quit`, ...), and + stops at once without console input. So no service, no scheduled task, + no clean stop from a script (tests force-kill it). Fix: a stop file like + `BenchServer.exe`'s, and/or a local admin connection, then a way to run + it as a service. (`Design/Release.md` smoke test #4) +2. **The 1.0.0 smoke test isn't done:** a run from the extracted zip on a + clean Windows (the shipped runtime has never been checked there), + replication between two release servers, restart catch-up (designed to + work, never tested: kill a server, check ids continue and peers catch + up). (`Design/Release.md`, items 1-3) +3. **`synchronous = NORMAL`:** the last commits can be lost on a power loss + or OS crash (not on a killed process). Decide, or switch to `FULL`. + (`Design/StorageConcurrency.md`) +4. **Drift between servers** when one topic/node pair is written to on two + servers: only partially resynced. Accepted while each pair has a single + writer; document that as the rule. (`Design/ReplicationIssues.md` #1) +5. **Gaps in a pair's ids aren't detected** on replication. + (`Design/ReplicationIssues.md` #5) +6. **No single test runner**, and fixed ports (12399, 12401-12407): every + `Tests/*.ps1` and the two `.pb` tests are run by hand. Needed for CI. + (`Design/Release.md`, "For CI/CD") +7. **Is `DatabaseError()` per thread?** Messages could land in the wrong + thread's log or refusal; Windows queries no longer depend on it. + (`Design/StorageConcurrency.md`) +8. **Limits:** the sync state must fit in one packet (65536 topic/node + pairs); `ReplicatingTopicIds` ranges are expanded to every id they cover. + (`Design/ReplicationIssues.md` #7) + +### Client side + +9. **One connection per process** (the DLL's globals): a handle-based API + for several. No reconnect in `GetMessages --follow` / `follow()`, polling + rather than server-pushed subscriptions. +10. **Breaking with protocol 3:** every client config needs + `ServerPublicKey`; older clients can't connect. Fine while it's all + built from this repo, worth a line in the release notes of the first + real release. + +### Security, low priority under the threat model + +11. **Peers are trusted completely:** messages aren't signed by the node + that first wrote them, a peer can replicate anything in what we accept + from it. (`Design/ReplicationIssues.md` #3) +12. **Private keys sit in plain-text ini files**, readable by whoever can + read the config. On trusted machines: file permissions are enough. +13. **No key rotation or revocation**, other than editing configs and + restarting; a server can't announce a new key, clients pin one. +14. **The handshake costs the server work before the client proved + anything** (a sealed box, a key pair, a signature): no rate limit, only + the 4 KB handshake limit and the 10 s timeout. +15. **Small ones:** the DLL doesn't wipe its private key; one identity key + both signs and opens sealed boxes; `EncodeData`/`DecodeData` are + misnamed (they sign/verify). (`Design/Cryptography.md`) + +### Housekeeping + +16. **Review.md rules** not checked against the newer code (`.i` in + networking structures, explicit enumeration values), see below. The + file itself says to ignore it for now. +17. **Linux is untested** (libsodium via `-lsodium`, the query error check + falls back to `DatabaseError()`). +18. **Console commands can't be scripted** (see 1). + +### Done recently (details in the sections above and `Design/`) + +- Protocol 3: encrypted connections, the server proves itself (2026-11-08). +- The release ships the Visual C++ runtime, from `Libs/redist/` (2026-11-08). +- A JSON query over non-JSON rows is refused with SQLite's error instead of + answering nothing (2026-11-08, Windows). +- GetMessages, `--follow`, the Python client; big messages (16 MB) and + `is_json`; names, filters and wildcards; speed: ~34,300 msg/s for 4 + servers (2026-11-07/08). + +## To check against Review.md + +`Review.md` has two rules the newer code hasn't been reviewed against: + +- **No `.i` in networking structures.** The wire packets use `.l`/`.q`, but + `BakaShrot_ConnectionMetadata\Status`, `BakaShrot_Inbox\Size` and the + server/link structures use `.i`. Decide whether the rule covers in-memory + connection state, or only what goes on the wire. +- **Networking enumerations must declare their values explicitly.** + `BakaShrot_PacketTypes` does. `BakaShrot_ConnectionStatuses` (already + implicit before) and `BakaShrot_InboxResults` don't. + +## Testing tips + +- **Run exes from `Build/`.** Exes in the session's temp/scratchpad folder are + blocked by the antivirus. +- **Test the server's console commands** with a small driver that includes + `Server/Root.pbi` and calls `BakaShrot_Root_*` directly. Piping commands + into the server doesn't work. +- **With no console input,** `Input()` returns `Chr(4)` on every call, and the + server stops on it. +- **Don't trust timestamps** from PowerShell's `Register-ObjectEvent`: lines + queue up during `Start-Sleep`. PureBasic's console output into a pipe is + also buffered until exit. Trust the order, not the times. diff --git a/Release.ps1 b/Release.ps1 new file mode 100644 index 0000000..00f3028 --- /dev/null +++ b/Release.ps1 @@ -0,0 +1,336 @@ +# ============================================================================ +# BakaShrot release build +# +# Builds everything with PureBasic 6.40's C backend and its optimizer into +# Release\\, 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 +# PushMessage.exe, GetLatestMessage.exe, GetMessages.exe, Query.exe, +# Resolve.exe, ListNames.exe, KeyGen.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 +# config.example.ini the server's config, documented +# VERSION.txt commit, date, compiler, libraries +# and Release\BakaShrot-.zip of it, unless -NoZip. +# +# No keys and no configs with keys in it: generate them with KeyGen.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 - +# ... -Force replaces Release\\ if it exists +# ... -Compiler -NoOptimizer -SqliteDll -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 +# 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\PushMessage\PushMessage.pb", "PushMessage.exe", @("/CONSOLE")), + @("Tools\GetLatestMessage\GetLatestMessage.pb", "GetLatestMessage.exe", @("/CONSOLE")), + @("Tools\GetMessages\GetMessages.pb", "GetMessages.exe", @("/CONSOLE")), + @("Tools\Query\Query.pb", "Query.exe", @("/CONSOLE")), + @("Tools\Resolve\Resolve.pb", "Resolve.exe", @("/CONSOLE")), + @("Tools\ListNames\ListNames.pb", "ListNames.exe", @("/CONSOLE")), + @("Tools\KeyGen\KeyGen.pb", "KeyGen.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 +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 +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") +} +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. + +Run the server: BakaShrot_Server.exe config.ini + Its config: config.example.ini. Keys: KeyGen.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. +Tools, next to BakaShrot_Client.dll, with a client.ini: + PushMessage [-t ] [ClientIni] + GetLatestMessage [ClientIni] + GetMessages [--after ] [--limit ] [--follow] [--interval ] [ClientIni] + Resolve [ClientIni] + ListNames [topics|nodes|all] [ClientIni] [--json] + Query [ClientIni] e.g. SELECT * FROM messages WHERE topic = 'logs' + client.ini: [BakaShrot] PrivateKey, PublicKey, Topic, Node (names or + ids), ServerHost, ServerPort, ServerPublicKey. +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 . +"@ +Set-Content -Path (Join-Path $OutDir "VERSION.txt") -Value $VersionText -Encoding UTF8 + + +# --- Test ------------------------------------------------------------------- + +function New-KeyPair { + $Lines = & (Join-Path $OutDir "KeyGen.exe") + if ($LASTEXITCODE -ne 0) { throw "KeyGen 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) +Topic = releasetest +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) +Identities = releasetest:tester +AllowRead = 1 +AllowWrite = 1 +AllowQuery = 1 +"@ + Set-Content -Path (Join-Path $TestDir "client.ini") -Encoding Ascii -Value @" +[BakaShrot] +PrivateKey = $($ClientKeys.PrivateKey) +PublicKey = $($ClientKeys.PublicKey) +Topic = releasetest +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 "PushMessage.exe" @("@$(Join-Path $TestDir 'message.json')", $ClientIni) + if ($Pushed -notmatch "message #1") { throw "Unexpected push answer: $Pushed" } + + $Latest = Invoke-Tool "GetLatestMessage.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 "PushMessage.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 "GetMessages.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 "Resolve.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 "Query.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" + + $PythonExe = Get-Command python -ErrorAction SilentlyContinue + 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" + } + else { + Write-Host " No python on the PATH, the Python client wasn't checked" + } + } + 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 diff --git a/Server/BakaShrot_Server.pb b/Server/BakaShrot_Server.pb new file mode 100644 index 0000000..9afaef7 --- /dev/null +++ b/Server/BakaShrot_Server.pb @@ -0,0 +1,108 @@ +; ============================================================================ +; 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.]. 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. +; +; Compile as a thread-safe console program. +; ============================================================================ + +EnableExplicit + +XIncludeFile "Root.pbi" + + +#BakaShrot_Server_DefaultConfigPath = "config.ini" + + +Procedure PrintCommands() + PrintN("Commands: quit (or an empty line), restart, vacuum, names, help") +EndProcedure + + +Define Root.BakaShrot_Root +Define Command.s, ExitCode.i + +OpenConsole("BakaShrot Server") + +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(Input())) + + ; Once there's no more input (no console, closed standard input), every + ; Input() returns Chr(4) right away. Without this, it would loop forever. + If FindString(Command, Chr(4)) + PrintN("No more input, stopping") + Break + 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 diff --git a/Server/BakaShrot_Server.pb.cfg b/Server/BakaShrot_Server.pb.cfg new file mode 100644 index 0000000..1308c0a --- /dev/null +++ b/Server/BakaShrot_Server.pb.cfg @@ -0,0 +1,8 @@ +IDE Options = PureBasic 6.41 beta 2 (Windows - x64) +CursorPosition = 15 +FirstLine = 23 +EnableXP +DPIAware +CompileSourceDirectory +EnableCompileCount = 1 +EnableBuildCount = 0 diff --git a/Server/Config/Config.pbi b/Server/Config/Config.pbi new file mode 100644 index 0000000..db428db --- /dev/null +++ b/Server/Config/Config.pbi @@ -0,0 +1,893 @@ +; ============================================================================ +; BakaShrot Server Config +; +; Loads and saves the server node's configuration from/to an ini file via +; PureBasic's native Preferences library. +; +; Section layout: +; [BakaShrot] -> BakaShrot_CoreConfig +; [BakaShrot.Server] -> BakaShrot_CoreConfig\Server +; [BakaShrot.Topics] -> topic names, "name = id" lines +; [BakaShrot.Nodes] -> node names, "name = id" lines +; [BakaShrot.Peer.] -> one BakaShrot_CoreConfig\Peers() entry per +; section. +; [BakaShrot.Client.] -> one BakaShrot_CoreConfig\Clients() entry per +; section. +; +; of a peer or client section is only a key for this file, it is never +; sent on the wire. Topic and node names are: they're what other servers know +; them by, see Commons/Networking/Names.pbi. +; +; Everywhere else, a topic or node is a "ref": a name from those sections, +; or an id in digits. Topic and node lists ("0;logs;100-150;sensors.*") also +; take ranges of ids, patterns like file names ("sensors.*", "kitchen-??", +; see Commons/Networking/Names.pbi), and "*" for every one. In a peer's +; AcceptTopics / AcceptNodes, "*" and patterns also take names this server +; doesn't have: they're added with an id of their own, see +; Server/Storage/Names.pbi. +; +; LoadConfig() returns 0 on any mistake, with the reason in +; BakaShrot_ConfigError. +; ============================================================================ + +XIncludeFile "../../Commons/Networking/Names.pbi" + + +; Some topics or nodes, or all of them: what a topic list (or node list) +; in the config holds, see the top of this file. +Structure BakaShrot_NameSet + ; Every one, named or not, known or not ("*"). + All.i + + ; Every one that has a name on this server: the default of AcceptNodes. + Known.i + + ; Str(Id) -> #True, from ids, ranges and names in the list. + Map Ids.i() + + ; Patterns ("sensors.*"), matched against names, known here or not: + ; a peer's topics and nodes it doesn't name are taken if they match. + List Patterns.s() +EndStructure + + +; Ini Section: [BakaShrot.Peer.] (one section per known peer) +; The server links to every peer on start, see Server/Networking/Peers.pbi. +; The peer must register this server in one of its [BakaShrot.Client.]. +; PublicKey is the peer's: a link to it only goes through if the peer +; proves it holds the matching private key (Commons/Networking/Connections.pbi). +; Topic and Node are only checked when the peer links to here. +Structure BakaShrot_PeerConfig + + ; Remote address of the peer + ; Can be a domain name, IPV4, IPV6 + Host.s + + ; Remote port of the peer + ; 0-65535 + Port.u + + ; Topic, Node: the remote node's topic and node, refs, resolved to this + ; server's ids. The peer authenticates with them when it links to here. + TopicId.u + NodeId.u + + ; This peer's Ed25519 public key (Base64): the Hello of a link to it is + ; sealed for it, and the peer must sign the handshake with the matching + ; private key. It also authenticates with it when it links to here. + PublicKey.s + + ; SendTopics: the topics this server sends to the peer (if the peer + ; takes them). AcceptTopics: the topics it takes from the peer. + ; Both default to [BakaShrot.Server] ReplicatingTopics. + SendTopics.BakaShrot_NameSet + AcceptTopics.BakaShrot_NameSet + + ; SendNodes: the nodes whose messages this server sends to the peer. + ; Default: every one (*). AcceptNodes: the nodes whose messages it takes + ; from the peer. Default: every one named here, no other. + SendNodes.BakaShrot_NameSet + AcceptNodes.BakaShrot_NameSet + + ; As written in the ini, for SaveConfig(). Chr(1) when missing. + SendTopicsText.s + AcceptTopicsText.s + SendNodesText.s + AcceptNodesText.s + TopicText.s + NodeText.s + +EndStructure + + +; One "Topic:Node" entry of BakaShrot_ClientConfig\Identities(). +Structure BakaShrot_ClientIdentity + TopicId.u + NodeId.u +EndStructure + + +; What a client is allowed to do once authenticated. +; Ini keys of [BakaShrot.Client.], 1 to allow, 0 to deny. +Structure BakaShrot_ClientPermissions + + ; AllowRead: GetLatestMessage. Defaults to 1. + Read.i + + ; AllowWrite: PushMessage. Defaults to 1. + Write.i + + ; AllowQuery: raw read-only SQL queries. Defaults to 0, they can read + ; every topic's data. + Query.i + +EndStructure + +#BakaShrot_Config_DefaultAllowRead = 1 +#BakaShrot_Config_DefaultAllowWrite = 1 +#BakaShrot_Config_DefaultAllowQuery = 0 + + +; Ini Section: [BakaShrot.Client.] (one section per registered client) +Structure BakaShrot_ClientConfig + + ; Ed25519 public keys (Base64) the client is allowed to authenticate with. + ; Format: Key;Key;... + List PublicKeys.s() + + ; Topic and node pairs the client is allowed to authenticate as, once it + ; has authenticated with one of its PublicKeys. + ; Format: Topic:Node;Topic:Node;... each a name or an id. + List Identities.BakaShrot_ClientIdentity() + + ; AllowRead, AllowWrite, AllowQuery + Permissions.BakaShrot_ClientPermissions + + ; PushTopics: the topics it may push to, under its own node. + ; ReadTopics: the topics it may read the latest messages of. + ; Both default to the topics of its Identities. + PushTopics.BakaShrot_NameSet + ReadTopics.BakaShrot_NameSet + + ; As written in the ini, for SaveConfig(). Chr(1) when missing. + IdentitiesText.s + PushTopicsText.s + ReadTopicsText.s + +EndStructure + + +; Ini Section: [BakaShrot.Server] +Structure BakaShrot_ServerConfig + + ; IPV4 that it will be bound to + Host.s + + ; Used port + Port.u + + ; ReplicatingTopics: the topics replicated with every peer that doesn't + ; say otherwise (SendTopics, AcceptTopics). + ; Format: 0;logs;100-150;200;... or * for every topic. + ReplicatingTopics.BakaShrot_NameSet + ReplicatingTopicsText.s + + ; Amount of threads used for networking-related tasks + NetThreadPoolSize.i + + ; SQLite database file holding the messages. + DatabasePath.s + + ; Seconds to wait before connecting to a peer again, after failing to + ; connect or losing the connection. + PeerRetryDelay.i + + ; Seconds between two check-ins with a linked peer, where it's sent the + ; messages it's missing. + PeerSyncInterval.i + + ; Most messages sent to a peer per packet when it's missing some, 1-10000. + ; A batch is also cut short to fit in one packet (64 KB). + PeerBatchSize.i + +EndStructure + + +; Ini Section: [BakaShrot] +Structure BakaShrot_CoreConfig + + ; This node's Ed25519 private key (Base64), used to sign every packet it + ; sends. Its matching public key must be handed to peers, who store it + ; as PublicKey in the relevant [BakaShrot.Peer.] section of THEIR + ; own config. See Commons/Cryptography/Libsodium.pbi. + PrivateKey.s + + ; Topic, Node: the topic and node this server authenticates as when it + ; links to its peers, refs. Peers must know them by the same names. + TopicId.u + NodeId.u + TopicText.s + NodeText.s + + ; [BakaShrot.Server] + Server.BakaShrot_ServerConfig + + ; [BakaShrot.Topics] and [BakaShrot.Nodes]: + ; LCase(name) -> id, and Str(id) -> name as written. + Map TopicIds.i() + Map TopicNames.s() + Map NodeIds.i() + Map NodeNames.s() + + ; Str(id) -> #True for every id the config mentions, named or not, so + ; the database knows them all (Server/Storage/Names.pbi). + Map UsedTopicIds.i() + Map UsedNodeIds.i() + + ; One [BakaShrot.Peer.] entry per map key. + Map Peers.BakaShrot_PeerConfig() + + ; One [BakaShrot.Client.] entry per map key. + Map Clients.BakaShrot_ClientConfig() + +EndStructure + + +Macro Ptr_BakaShrot_CoreConfig : i : EndMacro + + +#BakaShrot_Config_DefaultNetThreadPoolSize = 4 +#BakaShrot_Config_DefaultDatabasePath = "./test.sqlite" +#BakaShrot_Config_DefaultPeerRetryDelay = 10 +#BakaShrot_Config_DefaultPeerSyncInterval = 5 +#BakaShrot_Config_DefaultPeerBatchSize = 100 + +; What ReadPreferenceString() returns for a missing key, to tell it from an +; empty one: an empty PushTopics allows nothing, a missing one the default. +#BakaShrot_Config_Missing = Chr(1) + + +; Why the last LoadConfig() failed. +Global BakaShrot_ConfigError.s = "" + + +; Reads Key, or OldKey if Key is missing: Topic, Node and ReplicatingTopics +; were TopicId, NodeId and ReplicatingTopicIds before they took names, and +; configs written then still work. +Procedure.s ReadConfigKey(Key.s, OldKey.s, DefaultValue.s) + Protected Value.s = ReadPreferenceString(Key, #BakaShrot_Config_Missing) + If Value = #BakaShrot_Config_Missing + Value = ReadPreferenceString(OldKey, DefaultValue) + EndIf + ProcedureReturn Value +EndProcedure + + +; #True if *Set holds the topic or node Id named Name: Name is its name +; ("" if it has none), Id is -1 for a name this server doesn't know. +; Not thread-safe, it moves the set's current map and list elements: give +; each thread its own copy (CopyStructure()). +Procedure.i NameSetHas(*Set.BakaShrot_NameSet, Id.i, Name.s) + If *Set\All + ProcedureReturn #True + EndIf + If Id >= 0 And FindMapElement(*Set\Ids(), Str(Id)) + ProcedureReturn #True + EndIf + If Name <> "" + If *Set\Known And Id >= 0 + ProcedureReturn #True + EndIf + ForEach *Set\Patterns() + If BakaShrot_GlobMatch(*Set\Patterns(), Name) + ProcedureReturn #True + EndIf + Next + EndIf + ProcedureReturn #False +EndProcedure + +; #True if *Set has anything that can take names this server doesn't know +; ("*" or a pattern). +Procedure.i NameSetTakesUnknown(*Set.BakaShrot_NameSet) + ProcedureReturn Bool(*Set\All Or ListSize(*Set\Patterns()) > 0) +EndProcedure + + +; The id a topic ref stands for in *Config, -1 if it's neither an id nor one +; of its [BakaShrot.Topics]. +; An empty ref is 0, like an empty key always was. +Procedure.i ResolveConfigTopic(*Config.BakaShrot_CoreConfig, Ref.s) + Protected Id.i + + If Ref = "" + Ref = "0" + EndIf + Id = BakaShrot_RefToId(Ref) + + If Id >= 0 + ProcedureReturn Id + EndIf + If BakaShrot_IsValidName(Ref) And FindMapElement(*Config\TopicIds(), LCase(Ref)) + ProcedureReturn *Config\TopicIds() + EndIf + ProcedureReturn -1 +EndProcedure + +; Same for a node ref and [BakaShrot.Nodes]. +Procedure.i ResolveConfigNode(*Config.BakaShrot_CoreConfig, Ref.s) + Protected Id.i + + If Ref = "" + Ref = "0" + EndIf + Id = BakaShrot_RefToId(Ref) + + If Id >= 0 + ProcedureReturn Id + EndIf + If BakaShrot_IsValidName(Ref) And FindMapElement(*Config\NodeIds(), LCase(Ref)) + ProcedureReturn *Config\NodeIds() + EndIf + ProcedureReturn -1 +EndProcedure + + +; Reads a "name = id" section into Ids() (LCase(name) -> id) and Names() +; (Str(id) -> name). Kind is "topic" or "node", for the errors. +; Returns #False on an invalid name or id, or one given twice. +Procedure.i ParseNameSection(Section.s, Kind.s, Map Ids.i(), Map Names.s()) + Protected Name.s, Value.s, Id.i + + If Not PreferenceGroup(Section) + ProcedureReturn #True + EndIf + + If ExaminePreferenceKeys() + While NextPreferenceKey() + Name = Trim(PreferenceKeyName()) + Value = Trim(PreferenceKeyValue()) + If Not BakaShrot_IsValidName(Name) + BakaShrot_ConfigError = "[" + Section + "] '" + Name + "' isn't a valid " + Kind + " name: 1-" + Str(#BakaShrot_MaxNameLength) + " of A-Z a-z 0-9 _ . -, not only digits" + ProcedureReturn #False + EndIf + Id = BakaShrot_RefToId(Value) + If Id < 0 + BakaShrot_ConfigError = "[" + Section + "] " + Name + " = '" + Value + "' isn't an id, 0-" + Str(#BakaShrot_MaxId) + ProcedureReturn #False + EndIf + If FindMapElement(Ids(), LCase(Name)) + BakaShrot_ConfigError = "[" + Section + "] " + Kind + " '" + Name + "' is given twice" + ProcedureReturn #False + EndIf + If FindMapElement(Names(), Str(Id)) + BakaShrot_ConfigError = "[" + Section + "] " + Kind + " id " + Str(Id) + " is given to both '" + Names() + "' and '" + Name + "'" + ProcedureReturn #False + EndIf + Ids(LCase(Name)) = Id + Names(Str(Id)) = Name + Wend + EndIf + + ProcedureReturn #True +EndProcedure + + +; Parses a topic list (IsNodes #False) or node list into *Set: refs, +; patterns and ranges of ids separated by ";", "*" for every one, see the +; top of this file. Where is for the errors. +; Returns #False on an unknown name, an invalid pattern or range. +Procedure.i ParseNameSet(*Config.BakaShrot_CoreConfig, Text.s, *Set.BakaShrot_NameSet, IsNodes.i, Where.s) + Protected i.i, Part.s, DashPos.i, FromId.i, ToId.i, Id.i, Kind.s, Section.s + + Kind = "topic" : Section = "[BakaShrot.Topics]" + If IsNodes + Kind = "node" : Section = "[BakaShrot.Nodes]" + EndIf + + ClearMap(*Set\Ids()) + ClearList(*Set\Patterns()) + *Set\All = #False + *Set\Known = #False + + For i = 1 To CountString(Text, ";") + 1 + Part = Trim(StringField(Text, i, ";")) + If Part = "" + Continue + EndIf + + If Part = "*" + *Set\All = #True + Continue + EndIf + + If FindString(Part, "*") Or FindString(Part, "?") + If Not BakaShrot_IsValidPattern(Part) + BakaShrot_ConfigError = Where + ": '" + Part + "' isn't a valid pattern, * and ? among A-Z a-z 0-9 _ . -" + ProcedureReturn #False + EndIf + AddElement(*Set\Patterns()) + *Set\Patterns() = Part + Continue + EndIf + + ; Names can have dashes too, only digits on both sides make a range. + DashPos = FindString(Part, "-") + If DashPos And BakaShrot_IsDigits(Trim(Left(Part, DashPos - 1))) And BakaShrot_IsDigits(Trim(Mid(Part, DashPos + 1))) + FromId = BakaShrot_RefToId(Trim(Left(Part, DashPos - 1))) + ToId = BakaShrot_RefToId(Trim(Mid(Part, DashPos + 1))) + If FromId < 0 Or ToId < 0 Or FromId > ToId + BakaShrot_ConfigError = Where + ": '" + Part + "' isn't a valid range of ids" + ProcedureReturn #False + EndIf + For Id = FromId To ToId + *Set\Ids(Str(Id)) = #True + If IsNodes + *Config\UsedNodeIds(Str(Id)) = #True + Else + *Config\UsedTopicIds(Str(Id)) = #True + EndIf + Next + Else + If IsNodes + Id = ResolveConfigNode(*Config, Part) + Else + Id = ResolveConfigTopic(*Config, Part) + EndIf + If Id < 0 + BakaShrot_ConfigError = Where + ": unknown " + Kind + " '" + Part + "', not an id, a pattern, nor in " + Section + ProcedureReturn #False + EndIf + *Set\Ids(Str(Id)) = #True + If IsNodes + *Config\UsedNodeIds(Str(Id)) = #True + Else + *Config\UsedTopicIds(Str(Id)) = #True + EndIf + EndIf + Next + + ProcedureReturn #True +EndProcedure + +; A topic list, see ParseNameSet(). +Procedure.i ParseTopicSet(*Config.BakaShrot_CoreConfig, Text.s, *Set.BakaShrot_NameSet, Where.s) + ProcedureReturn ParseNameSet(*Config, Text, *Set, #False, Where) +EndProcedure + + +; Parses a "Key;Key;..." list into a list of Base64 public keys. +Procedure ParsePublicKeyList(KeysString.s, List Keys.s()) + Protected i, Part.s + + ClearList(Keys()) + + For i = 1 To CountString(KeysString, ";") + 1 + Part = Trim(StringField(KeysString, i, ";")) + If Part = "" + Continue + EndIf + + AddElement(Keys()) + Keys() = Part + Next + +EndProcedure + + +; Serializes a list of Base64 public keys back into "Key;Key;..." form. +Procedure.s FormatPublicKeyList(List Keys.s()) + Protected Result.s + + ForEach Keys() + If Result <> "" + Result + ";" + EndIf + Result + Keys() + Next + + ProcedureReturn Result +EndProcedure + + +; Parses a "Topic:Node;Topic:Node;..." list into a list of identities. +; Returns #False if an entry isn't exactly "Topic:Node" with known refs, +; since silently turning a typo into a 0:0 identity would grant an identity +; nobody asked for. +Procedure.i ParseIdentityList(*Config.BakaShrot_CoreConfig, IdentitiesString.s, List Identities.BakaShrot_ClientIdentity(), Where.s) + Protected i, Part.s, TopicPart.s, NodePart.s, TopicId.i, NodeId.i + + ClearList(Identities()) + + For i = 1 To CountString(IdentitiesString, ";") + 1 + Part = Trim(StringField(IdentitiesString, i, ";")) + If Part = "" + Continue + EndIf + + If CountString(Part, ":") <> 1 + BakaShrot_ConfigError = Where + ": '" + Part + "' isn't Topic:Node" + ProcedureReturn #False + EndIf + + TopicPart = Trim(StringField(Part, 1, ":")) + NodePart = Trim(StringField(Part, 2, ":")) + If TopicPart = "" Or NodePart = "" + BakaShrot_ConfigError = Where + ": '" + Part + "' isn't Topic:Node" + ProcedureReturn #False + EndIf + TopicId = ResolveConfigTopic(*Config, TopicPart) + NodeId = ResolveConfigNode(*Config, NodePart) + If TopicId < 0 + BakaShrot_ConfigError = Where + ": unknown topic '" + TopicPart + "', not an id nor in [BakaShrot.Topics]" + ProcedureReturn #False + EndIf + If NodeId < 0 + BakaShrot_ConfigError = Where + ": unknown node '" + NodePart + "', not an id nor in [BakaShrot.Nodes]" + ProcedureReturn #False + EndIf + + AddElement(Identities()) + Identities()\TopicId = TopicId + Identities()\NodeId = NodeId + *Config\UsedTopicIds(Str(TopicId)) = #True + *Config\UsedNodeIds(Str(NodeId)) = #True + Next + + ProcedureReturn #True +EndProcedure + + +; Returns the name of the [BakaShrot.Client.] section allowing both +; PublicKey and the TopicId:NodeId identity, or "" if none does. +; Not thread-safe, it moves *Config\Clients()' current element. +Procedure.s FindClientName(*Config.BakaShrot_CoreConfig, PublicKey.s, TopicId.i, NodeId.i) + Protected KeyAllowed.i, IdentityAllowed.i + + ForEach *Config\Clients() + KeyAllowed = #False + ForEach *Config\Clients()\PublicKeys() + If *Config\Clients()\PublicKeys() = PublicKey + KeyAllowed = #True + Break + EndIf + Next + + IdentityAllowed = #False + ForEach *Config\Clients()\Identities() + If *Config\Clients()\Identities()\TopicId = TopicId And *Config\Clients()\Identities()\NodeId = NodeId + IdentityAllowed = #True + Break + EndIf + Next + + If KeyAllowed And IdentityAllowed + ProcedureReturn MapKey(*Config\Clients()) + EndIf + Next + + ProcedureReturn "" +EndProcedure + + +; Returns the name of the [BakaShrot.Peer.] section with exactly this +; public key and TopicId:NodeId identity, or "" if none has. +; Not thread-safe, it moves *Config\Peers()' current element. +Procedure.s FindPeerName(*Config.BakaShrot_CoreConfig, PublicKey.s, TopicId.i, NodeId.i) + ForEach *Config\Peers() + If *Config\Peers()\PublicKey = PublicKey And *Config\Peers()\TopicId = TopicId And *Config\Peers()\NodeId = NodeId + ProcedureReturn MapKey(*Config\Peers()) + EndIf + Next + + ProcedureReturn "" +EndProcedure + + +Procedure FreeConfig(*Config.BakaShrot_CoreConfig) + FreeStructure(*Config) +EndProcedure + + +; Loads IniFilePath. Returns 0 on failure, with the reason in BakaShrot_ConfigError. +Procedure.Ptr_BakaShrot_CoreConfig LoadConfig(IniFilePath.s) + Protected *Config.BakaShrot_CoreConfig + Protected GroupName.s, PeerName.s, ClientName.s, Text.s, Id.i + Protected NewList PeerNames.s(), NewList ClientNames.s() + Protected Failed.i = #False + + BakaShrot_ConfigError = "" + + If Not OpenPreferences(IniFilePath) + BakaShrot_ConfigError = "can't open '" + IniFilePath + "'" + ProcedureReturn 0 + EndIf + + *Config = AllocateStructure(BakaShrot_CoreConfig) + If Not *Config + ClosePreferences() + BakaShrot_ConfigError = "out of memory" + ProcedureReturn 0 + EndIf + + ; Names first, everything else can refer to them. + If Not ParseNameSection("BakaShrot.Topics", "topic", *Config\TopicIds(), *Config\TopicNames()) Or + Not ParseNameSection("BakaShrot.Nodes", "node", *Config\NodeIds(), *Config\NodeNames()) + Goto LoadFailed + EndIf + ForEach *Config\TopicNames() + *Config\UsedTopicIds(MapKey(*Config\TopicNames())) = #True + Next + ForEach *Config\NodeNames() + *Config\UsedNodeIds(MapKey(*Config\NodeNames())) = #True + Next + + PreferenceGroup("BakaShrot") + *Config\PrivateKey = ReadPreferenceString("PrivateKey", "") + *Config\TopicText = Trim(ReadConfigKey("Topic", "TopicId", "0")) + *Config\NodeText = Trim(ReadConfigKey("Node", "NodeId", "0")) + Id = ResolveConfigTopic(*Config, *Config\TopicText) + If Id < 0 + BakaShrot_ConfigError = "[BakaShrot] Topic: unknown topic '" + *Config\TopicText + "'" + Goto LoadFailed + EndIf + *Config\TopicId = Id + Id = ResolveConfigNode(*Config, *Config\NodeText) + If Id < 0 + BakaShrot_ConfigError = "[BakaShrot] Node: unknown node '" + *Config\NodeText + "'" + Goto LoadFailed + EndIf + *Config\NodeId = Id + *Config\UsedTopicIds(Str(*Config\TopicId)) = #True + *Config\UsedNodeIds(Str(*Config\NodeId)) = #True + + PreferenceGroup("BakaShrot.Server") + *Config\Server\Host = ReadPreferenceString("Host", "") + *Config\Server\Port = ReadPreferenceLong("Port", 0) + *Config\Server\NetThreadPoolSize = ReadPreferenceLong("NetThreadPoolSize", #BakaShrot_Config_DefaultNetThreadPoolSize) + *Config\Server\DatabasePath = ReadPreferenceString("DatabasePath", #BakaShrot_Config_DefaultDatabasePath) + *Config\Server\PeerRetryDelay = ReadPreferenceLong("PeerRetryDelay", #BakaShrot_Config_DefaultPeerRetryDelay) + *Config\Server\PeerSyncInterval = ReadPreferenceLong("PeerSyncInterval", #BakaShrot_Config_DefaultPeerSyncInterval) + *Config\Server\PeerBatchSize = ReadPreferenceLong("PeerBatchSize", #BakaShrot_Config_DefaultPeerBatchSize) + *Config\Server\ReplicatingTopicsText = ReadConfigKey("ReplicatingTopics", "ReplicatingTopicIds", "") + If Not ParseTopicSet(*Config, *Config\Server\ReplicatingTopicsText, @*Config\Server\ReplicatingTopics, "[BakaShrot.Server] ReplicatingTopics") + Goto LoadFailed + EndIf + + ; Every [BakaShrot.Peer.] and [BakaShrot.Client.], found + ; dynamically so adding one never needs a second "list of names" kept in + ; sync by hand. Read once the walk is done: PreferenceGroup() inside it + ; would lose the walk's place. + If ExaminePreferenceGroups() + While NextPreferenceGroup() + GroupName = PreferenceGroupName() + If Left(GroupName, Len("BakaShrot.Peer.")) = "BakaShrot.Peer." And Len(GroupName) > Len("BakaShrot.Peer.") + AddElement(PeerNames()) + PeerNames() = Mid(GroupName, Len("BakaShrot.Peer.") + 1) + EndIf + If Left(GroupName, Len("BakaShrot.Client.")) = "BakaShrot.Client." And Len(GroupName) > Len("BakaShrot.Client.") + AddElement(ClientNames()) + ClientNames() = Mid(GroupName, Len("BakaShrot.Client.") + 1) + EndIf + Wend + EndIf + + ForEach PeerNames() + PeerName = PeerNames() + PreferenceGroup("BakaShrot.Peer." + PeerName) + AddMapElement(*Config\Peers(), PeerName) + With *Config\Peers() + \Host = ReadPreferenceString("Host", "") + \Port = ReadPreferenceLong("Port", 0) + \PublicKey = ReadPreferenceString("PublicKey", "") + \TopicText = Trim(ReadConfigKey("Topic", "TopicId", "0")) + \NodeText = Trim(ReadConfigKey("Node", "NodeId", "0")) + Id = ResolveConfigTopic(*Config, \TopicText) + If Id < 0 + BakaShrot_ConfigError = "[BakaShrot.Peer." + PeerName + "] Topic: unknown topic '" + \TopicText + "'" + Failed = #True : Break + EndIf + \TopicId = Id + Id = ResolveConfigNode(*Config, \NodeText) + If Id < 0 + BakaShrot_ConfigError = "[BakaShrot.Peer." + PeerName + "] Node: unknown node '" + \NodeText + "'" + Failed = #True : Break + EndIf + \NodeId = Id + *Config\UsedTopicIds(Str(\TopicId)) = #True + *Config\UsedNodeIds(Str(\NodeId)) = #True + + \SendTopicsText = ReadPreferenceString("SendTopics", #BakaShrot_Config_Missing) + If \SendTopicsText = #BakaShrot_Config_Missing + CopyStructure(@*Config\Server\ReplicatingTopics, @\SendTopics, BakaShrot_NameSet) + ElseIf Not ParseTopicSet(*Config, \SendTopicsText, @\SendTopics, "[BakaShrot.Peer." + PeerName + "] SendTopics") + Failed = #True : Break + EndIf + + \AcceptTopicsText = ReadPreferenceString("AcceptTopics", #BakaShrot_Config_Missing) + If \AcceptTopicsText = #BakaShrot_Config_Missing + CopyStructure(@*Config\Server\ReplicatingTopics, @\AcceptTopics, BakaShrot_NameSet) + ElseIf Not ParseTopicSet(*Config, \AcceptTopicsText, @\AcceptTopics, "[BakaShrot.Peer." + PeerName + "] AcceptTopics") + Failed = #True : Break + EndIf + + \SendNodesText = ReadPreferenceString("SendNodes", #BakaShrot_Config_Missing) + If \SendNodesText = #BakaShrot_Config_Missing + \SendNodes\All = #True + ElseIf Not ParseNameSet(*Config, \SendNodesText, @\SendNodes, #True, "[BakaShrot.Peer." + PeerName + "] SendNodes") + Failed = #True : Break + EndIf + + \AcceptNodesText = ReadPreferenceString("AcceptNodes", #BakaShrot_Config_Missing) + If \AcceptNodesText = #BakaShrot_Config_Missing + \AcceptNodes\Known = #True + ElseIf Not ParseNameSet(*Config, \AcceptNodesText, @\AcceptNodes, #True, "[BakaShrot.Peer." + PeerName + "] AcceptNodes") + Failed = #True : Break + EndIf + EndWith + Next + If Failed + Goto LoadFailed + EndIf + + ForEach ClientNames() + ClientName = ClientNames() + PreferenceGroup("BakaShrot.Client." + ClientName) + AddMapElement(*Config\Clients(), ClientName) + With *Config\Clients() + ParsePublicKeyList(ReadPreferenceString("PublicKeys", ""), \PublicKeys()) + \IdentitiesText = ReadPreferenceString("Identities", "") + If Not ParseIdentityList(*Config, \IdentitiesText, \Identities(), "[BakaShrot.Client." + ClientName + "] Identities") + Failed = #True : Break + EndIf + \Permissions\Read = Bool(ReadPreferenceLong("AllowRead", #BakaShrot_Config_DefaultAllowRead) <> 0) + \Permissions\Write = Bool(ReadPreferenceLong("AllowWrite", #BakaShrot_Config_DefaultAllowWrite) <> 0) + \Permissions\Query = Bool(ReadPreferenceLong("AllowQuery", #BakaShrot_Config_DefaultAllowQuery) <> 0) + + ; By default, only the topics it authenticates in, like before. + \PushTopicsText = ReadPreferenceString("PushTopics", #BakaShrot_Config_Missing) + \ReadTopicsText = ReadPreferenceString("ReadTopics", #BakaShrot_Config_Missing) + If \PushTopicsText = #BakaShrot_Config_Missing + ForEach \Identities() + \PushTopics\Ids(Str(\Identities()\TopicId)) = #True + Next + ElseIf Not ParseTopicSet(*Config, \PushTopicsText, @\PushTopics, "[BakaShrot.Client." + ClientName + "] PushTopics") + Failed = #True : Break + EndIf + If \ReadTopicsText = #BakaShrot_Config_Missing + ForEach \Identities() + \ReadTopics\Ids(Str(\Identities()\TopicId)) = #True + Next + ElseIf Not ParseTopicSet(*Config, \ReadTopicsText, @\ReadTopics, "[BakaShrot.Client." + ClientName + "] ReadTopics") + Failed = #True : Break + EndIf + EndWith + Next + If Failed + Goto LoadFailed + EndIf + + ClosePreferences() + ProcedureReturn *Config + + LoadFailed: + ClosePreferences() + FreeConfig(*Config) + ProcedureReturn 0 +EndProcedure + + +; Writes a key, unless its text is #BakaShrot_Config_Missing. +Procedure WriteConfigText(Key.s, Text.s) + If Text <> #BakaShrot_Config_Missing + WritePreferenceString(Key, Text) + EndIf +EndProcedure + + +; Saves *Config back, lists and refs as they were written in the ini. +Procedure.i SaveConfig(IniFilePath.s, *Config.BakaShrot_CoreConfig) + + If Not CreatePreferences(IniFilePath) + ProcedureReturn #False + EndIf + + PreferenceGroup("BakaShrot") + WritePreferenceString("PrivateKey", *Config\PrivateKey) + WritePreferenceString("Topic", *Config\TopicText) + WritePreferenceString("Node", *Config\NodeText) + + PreferenceGroup("BakaShrot.Server") + WritePreferenceString("Host", *Config\Server\Host) + WritePreferenceLong("Port", *Config\Server\Port) + WritePreferenceString("ReplicatingTopics", *Config\Server\ReplicatingTopicsText) + WritePreferenceLong("NetThreadPoolSize", *Config\Server\NetThreadPoolSize) + WritePreferenceString("DatabasePath", *Config\Server\DatabasePath) + WritePreferenceLong("PeerRetryDelay", *Config\Server\PeerRetryDelay) + WritePreferenceLong("PeerSyncInterval", *Config\Server\PeerSyncInterval) + WritePreferenceLong("PeerBatchSize", *Config\Server\PeerBatchSize) + + PreferenceGroup("BakaShrot.Topics") + ForEach *Config\TopicNames() + WritePreferenceString(*Config\TopicNames(), MapKey(*Config\TopicNames())) + Next + + PreferenceGroup("BakaShrot.Nodes") + ForEach *Config\NodeNames() + WritePreferenceString(*Config\NodeNames(), MapKey(*Config\NodeNames())) + Next + + ForEach *Config\Peers() + PreferenceGroup("BakaShrot.Peer." + MapKey(*Config\Peers())) + WritePreferenceString("Host", *Config\Peers()\Host) + WritePreferenceLong("Port", *Config\Peers()\Port) + WritePreferenceString("Topic", *Config\Peers()\TopicText) + WritePreferenceString("Node", *Config\Peers()\NodeText) + WritePreferenceString("PublicKey", *Config\Peers()\PublicKey) + WriteConfigText("SendTopics", *Config\Peers()\SendTopicsText) + WriteConfigText("AcceptTopics", *Config\Peers()\AcceptTopicsText) + WriteConfigText("SendNodes", *Config\Peers()\SendNodesText) + WriteConfigText("AcceptNodes", *Config\Peers()\AcceptNodesText) + Next + + ForEach *Config\Clients() + PreferenceGroup("BakaShrot.Client." + MapKey(*Config\Clients())) + WritePreferenceString("PublicKeys", FormatPublicKeyList(*Config\Clients()\PublicKeys())) + WritePreferenceString("Identities", *Config\Clients()\IdentitiesText) + WritePreferenceLong("AllowRead", *Config\Clients()\Permissions\Read) + WritePreferenceLong("AllowWrite", *Config\Clients()\Permissions\Write) + WritePreferenceLong("AllowQuery", *Config\Clients()\Permissions\Query) + WriteConfigText("PushTopics", *Config\Clients()\PushTopicsText) + WriteConfigText("ReadTopics", *Config\Clients()\ReadTopicsText) + Next + + ClosePreferences() + + ProcedureReturn #True +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 + + Define *Config.BakaShrot_CoreConfig = LoadConfig("schema.ini") + + If *Config + Debug "PrivateKey: " + *Config\PrivateKey + Debug "TopicId: " + Str(*Config\TopicId) + Debug "NodeId: " + Str(*Config\NodeId) + + Debug "Server: " + *Config\Server\Host + ":" + Str(*Config\Server\Port) + Debug " NetThreadPoolSize: " + Str(*Config\Server\NetThreadPoolSize) + Debug " Replicating: " + *Config\Server\ReplicatingTopicsText + + ForEach *Config\TopicNames() + Debug "Topic " + *Config\TopicNames() + " = " + MapKey(*Config\TopicNames()) + Next + ForEach *Config\NodeNames() + Debug "Node " + *Config\NodeNames() + " = " + MapKey(*Config\NodeNames()) + Next + + ForEach *Config\Peers() + Debug "Peer '" + MapKey(*Config\Peers()) + "': " + *Config\Peers()\Host + ":" + Str(*Config\Peers()\Port) + " PublicKey=" + *Config\Peers()\PublicKey + Next + + ForEach *Config\Clients() + Debug "Client '" + MapKey(*Config\Clients()) + "':" + ForEach *Config\Clients()\PublicKeys() + Debug " PublicKey: " + *Config\Clients()\PublicKeys() + Next + ForEach *Config\Clients()\Identities() + Debug " Identity: " + Str(*Config\Clients()\Identities()\TopicId) + ":" + Str(*Config\Clients()\Identities()\NodeId) + Next + Next + + SaveConfig("schema_out.ini", *Config) + + FreeConfig(*Config) + Else + Debug "Failed to load schema.ini: " + BakaShrot_ConfigError + EndIf + +CompilerEndIf diff --git a/Core/Config/Config.pbi.cfg b/Server/Config/Config.pbi.cfg similarity index 100% rename from Core/Config/Config.pbi.cfg rename to Server/Config/Config.pbi.cfg diff --git a/Server/Config/schema.ini b/Server/Config/schema.ini new file mode 100644 index 0000000..16f041f --- /dev/null +++ b/Server/Config/schema.ini @@ -0,0 +1,149 @@ +; 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, in [BakaShrot.Topics] and [BakaShrot.Nodes]. 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 ListNames 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 KeyGen.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 topic and node this server authenticates as when it links to its +; peers, a name or an id. Its peers must register it under the same names. +Topic = +Node = + + +[BakaShrot.Topics] +; One line per named topic: name = this server's id for it. +; logs = 1 +; sensors = 2 + + +[BakaShrot.Nodes] +; One line per named node (a client's or a server's), same as topics. Every +; server that should get a node's messages must name it too. +; Once a name has messages, keep its id: the server refuses to start if the +; config moves it to another one, and says which id to use. +; kitchen = 2 + + +[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 + + +; One [BakaShrot.Peer.] section per peer this node talks to. +; 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.]. +; The link only goes through if the peer proves it holds the private key +; of PublicKey below, and it's encrypted. + +; Remote node's topic and node, names or ids. The peer authenticates with +; them when it links to here. +Topic = +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: the ones named in +; [BakaShrot.Nodes], no other). AcceptNodes = kitchen-* takes every +; kitchen-something the peer sends, 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.] section per client allowed to connect. +; 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 = + +; Topic and node pairs this client is allowed to authenticate as, names or ids. +; Format: Topic:Node;Topic:Node;... +Identities = + +; The topics it may push to (always under its own node), and the topics it +; may read the latest messages of. Both default to the topics of its +; Identities, 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 diff --git a/Core/Config/schema_out.ini b/Server/Config/schema_out.ini similarity index 73% rename from Core/Config/schema_out.ini rename to Server/Config/schema_out.ini index 2c829a2..ed0d33c 100644 --- a/Core/Config/schema_out.ini +++ b/Server/Config/schema_out.ini @@ -1,14 +1,14 @@  [BakaShrot] PrivateKey = -GroupId = 0 +TopicId = 0 NodeId = 0 [BakaShrot.Server] Host = Port = 0 -ReplicatingGroupIds = +ReplicatingTopicIds = [BakaShrot.Peer.example] Host = Port = 0 -GroupId = 0 +TopicId = 0 NodeId = 0 diff --git a/Server/Networking/Networking.pbi b/Server/Networking/Networking.pbi new file mode 100644 index 0000000..804e2e6 --- /dev/null +++ b/Server/Networking/Networking.pbi @@ -0,0 +1,1318 @@ +; ============================================================================ +; BakaShrot Server Networking +; +; Threaded TCP server, one thread per client: +; - The listener thread is the only one calling NetworkServerEvent(). +; On connect it starts a thread for the client, on data it adds what it +; received to that client's inbox, on disconnect it flags the client. +; Either way it then sets the client's Signal to wake its thread up. +; With nothing to do, it sleeps in select() on every socket (see +; Commons/Networking/SocketWait.pbi). +; - Each client thread runs the handshake (see Connections.pbi) by taking +; packets out of its inbox, sleeping on its Signal while it's empty. +; Anything out of order or unexpected aborts the connection. +; It opens the client's sealed Hello with this server's key, proves it +; holds it, and sets up the connection's cipher: every packet after the +; ChallengeRequest is encrypted, and decrypted by the client's thread. +; +; Once authenticated, a client's thread answers its requests one at a time +; until it disconnects: PushMessage, GetLatestMessage, GetMessages, +; QueryRequest, ResolveName and ListNames, each one only if its +; [BakaShrot.Client.] allows it (AllowWrite and PushTopics, AllowRead +; and ReadTopics, AllowQuery), and for +; peers, SyncStateRequest and ReplicateMessages, refused for regular clients, +; within the peer's AcceptTopics and AcceptNodes. Any other packet aborts it. +; +; Topics and nodes come by name or id (Commons/Networking/Names.pbi), and +; are resolved to this server's ids by Storage/Names.pbi. +; +; Each client thread opens its own database connection once its client is +; authenticated, and closes it when it ends. See the top of Storage/Storage.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 "Networking.pbi needs the thread-safe option (Compiler Options > Create threadsafe executable)." +CompilerEndIf + +XIncludeFile "../../Commons/Networking/Connections.pbi" +XIncludeFile "../../Commons/Networking/SocketWait.pbi" +XIncludeFile "../../Commons/Threading/Signal.pbi" +XIncludeFile "../Config/Config.pbi" +XIncludeFile "../Storage/Storage.pbi" +XIncludeFile "../Storage/Names.pbi" + + +#BakaShrot_Net_ReceiveBufferSize = 65536 + +; How long a client gets to send each handshake packet. +#BakaShrot_Net_HandshakeTimeout = 10000 + +; Logs every push, read and query. Off: PrintN() costs ~0.4 ms per line and +; serializes every thread behind it, which capped a server at ~2400 pushes/s +; (12000/s without it, see Design/StorageConcurrency.md). The storage logs a +; summary every 10 s instead. +#BakaShrot_Net_LogRequests = #False + + +Structure BakaShrot_NetServer + ServerId.i + ThreadId.i + *Config.BakaShrot_CoreConfig + + ; Every client thread opens its own connection to it, and so does every + ; raw query, read-only. + DatabasePath.s + + ; This server's identity, from [BakaShrot] PrivateKey: signs the + ; handshake, and opens the Hellos sealed for it. Read-only once started, + ; every client thread uses them. Wiped when it stops. + PrivateKey.a[#BakaShrot_Ed25519_PrivateKeySize] + PublicKey.a[#BakaShrot_Ed25519_PublicKeySize] + HelloKeys.BakaShrot_HelloKeys + + ; Set by BakaShrot_NetServer_Stop(), makes every thread return. + StopRequested.i + + ; Guards Clients(), every client's Inbox, Disconnected and Overflowed, + ; ActiveClientThreads and the use of *Config\Clients(). + Mutex.i + + ; Client threads that haven't finished yet. + ActiveClientThreads.i + + ; *BakaShrot_NetClient by Str(ClientId), for the listener to find them. + ; A client is removed when it disconnects or its thread closes it. + Map Clients.i() +EndStructure + + +Structure BakaShrot_NetClient + *Server.BakaShrot_NetServer + ClientId.i + + ; Filled by the listener thread, read by the client's thread. + Inbox.BakaShrot_Inbox + + ; Set by the listener thread. + Disconnected.i + Overflowed.i + + ; Set by the listener thread whenever it changed the above, or the + ; inbox. The client's thread sleeps on it while waiting for a packet. + ; Freed by the client's thread, once it's out of Clients(). + Signal.i + + ; Only used by the client's thread. + Metadata.BakaShrot_ConnectionMetadata + + ; Name of the [BakaShrot.Peer.] the client authenticated as, "" + ; for a regular client. Only peers may replicate. + PeerName.s + + ; From the [BakaShrot.Client.] the client authenticated as, copied + ; so this thread can look them up without the server's mutex. + Permissions.BakaShrot_ClientPermissions + PushTopics.BakaShrot_NameSet + ReadTopics.BakaShrot_NameSet + + ; From the [BakaShrot.Peer.], for peers only. + AcceptTopics.BakaShrot_NameSet + AcceptNodes.BakaShrot_NameSet + + ; This thread's own database connection, opened once authenticated. + DbId.i +EndStructure + + +; Waits for the next packet from *Client, for up to TimeoutMs, 0 waits forever. +; Decrypted once the connection's cipher is set up, outside the server's +; mutex. +; Returns the packet (free it with FreeMemory) with its size in *OutSize\i, +; or 0 if the client disconnected, sent an invalid frame, one that doesn't +; decrypt or too much data, timed out, or the server is stopping. The +; reason is logged. +Procedure.i BakaShrot_NetClient_WaitPacket(*Client.BakaShrot_NetClient, *OutSize.Integer, TimeoutMs.i) + Protected *Packet = 0, Result.i, Disconnected.i, Overflowed.i, StartTime.i + + StartTime = ElapsedMilliseconds() + + Repeat + LockMutex(*Client\Server\Mutex) + Disconnected = *Client\Disconnected + Overflowed = *Client\Overflowed + Result = BakaShrot_Inbox_TakePacket(@*Client\Inbox, @*Packet, *OutSize) + UnlockMutex(*Client\Server\Mutex) + + If Result = #BakaShrot_Inbox_Packet + *Packet = BakaShrot_OpenFrame(@*Client\Metadata\Cipher, *Packet, *OutSize\i, *OutSize) + If Not *Packet + PrintN("[Net] Client " + Str(*Client\ClientId) + " sent a packet that doesn't decrypt") + EndIf + ProcedureReturn *Packet + EndIf + + If Result = #BakaShrot_Inbox_Invalid + PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an invalid frame") + ProcedureReturn 0 + EndIf + + If Overflowed + PrintN("[Net] Client " + Str(*Client\ClientId) + " sent too much data") + ProcedureReturn 0 + EndIf + + If Disconnected + PrintN("[Net] Client " + Str(*Client\ClientId) + " disconnected") + ProcedureReturn 0 + EndIf + + If *Client\Server\StopRequested + PrintN("[Net] Client " + Str(*Client\ClientId) + " dropped, the server is stopping") + ProcedureReturn 0 + EndIf + + If TimeoutMs > 0 And ElapsedMilliseconds() - StartTime > TimeoutMs + PrintN("[Net] Client " + Str(*Client\ClientId) + " timed out") + ProcedureReturn 0 + EndIf + + ; Sleeps until the listener got something for it, waking up at least + ; every 50 ms to check the timeout and StopRequested. + BakaShrot_Signal_Wait(*Client\Signal, 50) + ForEver +EndProcedure + + +; Runs the server's side of the handshake, see Connections.pbi. +; Returns #True once the client is authenticated, #False if it must be aborted. +Procedure.i BakaShrot_NetClient_Authenticate(*Client.BakaShrot_NetClient) + Protected *Server.BakaShrot_NetServer = *Client\Server + Protected *Packet, PacketSize.Integer, *View.MsgPackData, *Sealed + 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 TopicId.i, NodeId.i, PublicKey.s, ClientName.s, TopicRef.s, NodeRef.s + Protected NonceMatches.i, SignatureDecoded.i, Sent.i, CipherReady.i + + *Client\Metadata\Status = #BakaShrot_ConnectionStatus_New + CopyMemory(@*Server\PublicKey[0], @*Client\Metadata\ServerPublicKey[0], #BakaShrot_Ed25519_PublicKeySize) + + + ; 1. Hello, sealed for this server + *Sealed = BakaShrot_NetClient_WaitPacket(*Client, @PacketSize, #BakaShrot_Net_HandshakeTimeout) + If Not *Sealed + ProcedureReturn #False + EndIf + *Packet = BakaShrot_Session_OpenHello(@*Server\HelloKeys, *Sealed, PacketSize\i, @PacketSize) + FreeMemory(*Sealed) + If Not *Packet + PrintN("[Net] Client " + Str(*Client\ClientId) + " sent a hello that isn't sealed for this server (wrong ServerPublicKey?)") + ProcedureReturn #False + EndIf + + *Hello = 0 + *View = MsgPackWrapMsgBuffer(*Packet, PacketSize\i) + If *View + *Hello = BakaShrot_HelloPacket_Decode(*View) + MsgPackFree(*View, #False) + EndIf + FreeMemory(*Packet) + If Not *Hello + PrintN("[Net] Client " + Str(*Client\ClientId) + " didn't send a valid hello") + ProcedureReturn #False + EndIf + + TopicRef = *Hello\ClientTopic + NodeRef = *Hello\ClientNode + PublicKey = *Hello\ClientPubKeyB64 + CopyMemory(@*Hello\ClientSessionKey[0], @*Client\Metadata\ClientSessionKey[0], #BakaShrot_SessionKeySize) + FreeStructure(*Hello) + + TopicId = BakaShrot_Names_ResolveTopic(TopicRef) + NodeId = BakaShrot_Names_ResolveNode(NodeRef) + If TopicId < 0 Or NodeId < 0 + PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an unknown identity '" + Left(TopicRef, 80) + "':'" + Left(NodeRef, 80) + "'") + ProcedureReturn #False + EndIf + + If Not DecodeKeyFromString(PublicKey, @*Client\Metadata\PublicKey[0], #BakaShrot_Ed25519_PublicKeySize) + PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an invalid public key") + ProcedureReturn #False + EndIf + + LockMutex(*Server\Mutex) + ClientName = FindClientName(*Server\Config, PublicKey, TopicId, NodeId) + *Client\PeerName = FindPeerName(*Server\Config, PublicKey, TopicId, NodeId) + If ClientName <> "" And FindMapElement(*Server\Config\Clients(), ClientName) + *Client\Permissions\Read = *Server\Config\Clients()\Permissions\Read + *Client\Permissions\Write = *Server\Config\Clients()\Permissions\Write + *Client\Permissions\Query = *Server\Config\Clients()\Permissions\Query + CopyStructure(@*Server\Config\Clients()\PushTopics, @*Client\PushTopics, BakaShrot_NameSet) + CopyStructure(@*Server\Config\Clients()\ReadTopics, @*Client\ReadTopics, BakaShrot_NameSet) + EndIf + If *Client\PeerName <> "" And FindMapElement(*Server\Config\Peers(), *Client\PeerName) + CopyStructure(@*Server\Config\Peers()\AcceptTopics, @*Client\AcceptTopics, BakaShrot_NameSet) + CopyStructure(@*Server\Config\Peers()\AcceptNodes, @*Client\AcceptNodes, BakaShrot_NameSet) + EndIf + UnlockMutex(*Server\Mutex) + If ClientName = "" + PrintN("[Net] Client " + Str(*Client\ClientId) + " isn't allowed to use " + BakaShrot_Names_TopicRef(TopicId) + ":" + BakaShrot_Names_NodeRef(NodeId) + " with its public key") + ProcedureReturn #False + EndIf + + *Client\Metadata\TopicId = TopicId + *Client\Metadata\NodeId = NodeId + + + ; 2. Challenge request, in plain text, signed by this server + If Not CryptRandomData(@*Client\Metadata\Challenge[0], #BakaShrot_ChallengeSize) + PrintN("[Net] Failed to generate a challenge for client " + Str(*Client\ClientId)) + ProcedureReturn #False + EndIf + If Not CryptRandomData(@*Client\Metadata\Nonce[0], #BakaShrot_NonceSize) + PrintN("[Net] Failed to generate a nonce for client " + Str(*Client\ClientId)) + ProcedureReturn #False + EndIf + + BakaShrot_Session_NewKeyPair(@KeyPair) + CopyMemory(@KeyPair\PublicKey[0], @*Client\Metadata\ServerSessionKey[0], #BakaShrot_SessionKeySize) + + BakaShrot_MakeHandshakeTranscript(@*Client\Metadata, #BakaShrot_TranscriptServerLabel, @Proof) + If Not BakaShrot_SignHandshake(@Proof, @*Server\PrivateKey[0]) + BakaShrot_Session_ClearKeyPair(@KeyPair) + PrintN("[Net] Failed to sign the handshake for client " + Str(*Client\ClientId)) + ProcedureReturn #False + EndIf + + ; This connection's keys, before anything else arrives: the client + ; encrypts everything after this. + CipherReady = BakaShrot_Session_StartServer(@*Client\Metadata\Cipher, @KeyPair, @*Client\Metadata\ClientSessionKey[0]) + If Not CipherReady + PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an unusable session key") + ProcedureReturn #False + EndIf + + Request\ChallengeB64 = EncodeKeyToString(@*Client\Metadata\Challenge[0], #BakaShrot_ChallengeSize) + CopyMemory(@*Client\Metadata\Nonce[0], @Request\Nonce[0], #BakaShrot_NonceSize) + CopyMemory(@*Client\Metadata\ServerSessionKey[0], @Request\ServerSessionKey[0], #BakaShrot_SessionKeySize) + CopyMemory(@Proof\Signature[0], @Request\ServerSignature[0], #BakaShrot_HandshakeSignatureSize) + + *Packet = BakaShrot_ChallengeRequestPacket_Encode(@Request, @PacketSize) + If Not *Packet + PrintN("[Net] Failed to encode the challenge request for client " + Str(*Client\ClientId)) + ProcedureReturn #False + EndIf + Sent = BakaShrot_SendPacket(*Client\ClientId, *Packet, PacketSize\i, 0) + FreeMemory(*Packet) + If Not Sent + PrintN("[Net] Failed to send the challenge request to client " + Str(*Client\ClientId)) + ProcedureReturn #False + EndIf + + *Client\Metadata\Status = #BakaShrot_ConnectionStatus_Challenged + + + ; 3. Challenge response, encrypted as everything from now on + *Packet = BakaShrot_NetClient_WaitPacket(*Client, @PacketSize, #BakaShrot_Net_HandshakeTimeout) + If Not *Packet + ProcedureReturn #False + EndIf + + *Response = 0 + *View = MsgPackWrapMsgBuffer(*Packet, PacketSize\i) + If *View + *Response = BakaShrot_ChallengeResponsePacket_Decode(*View) + MsgPackFree(*View, #False) + EndIf + FreeMemory(*Packet) + If Not *Response + PrintN("[Net] Client " + Str(*Client\ClientId) + " didn't send a valid challenge response") + ProcedureReturn #False + EndIf + + NonceMatches = CompareMemory(@*Response\Nonce[0], @*Client\Metadata\Nonce[0], #BakaShrot_NonceSize) + SignatureDecoded = DecodeKeyFromString(*Response\ChallengeResponseB64, @Proof\Signature[0], #BakaShrot_Ed25519_SignatureSize) + FreeStructure(*Response) + + If Not NonceMatches + PrintN("[Net] Client " + Str(*Client\ClientId) + " answered with the wrong nonce") + ProcedureReturn #False + EndIf + + If Not SignatureDecoded + PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an invalid signature") + ProcedureReturn #False + EndIf + + BakaShrot_MakeHandshakeTranscript(@*Client\Metadata, #BakaShrot_TranscriptClientLabel, @Proof) + If Not BakaShrot_VerifyHandshake(@Proof, @*Client\Metadata\PublicKey[0]) + PrintN("[Net] Client " + Str(*Client\ClientId) + " failed the challenge") + ProcedureReturn #False + EndIf + + + ; 4. Accepted + ; Big packets from now on, set before it hears it's accepted: the listener + ; may get its first request right after. + LockMutex(*Server\Mutex) + BakaShrot_Inbox_Lift(@*Client\Inbox) + UnlockMutex(*Server\Mutex) + + *Packet = BakaShrot_AuthAcceptedPacket_Encode(@Accepted, @PacketSize) + If Not *Packet + PrintN("[Net] Failed to encode the acceptance for client " + Str(*Client\ClientId)) + ProcedureReturn #False + EndIf + Sent = BakaShrot_SendPacket(*Client\ClientId, *Packet, PacketSize\i, @*Client\Metadata\Cipher) + FreeMemory(*Packet) + If Not Sent + PrintN("[Net] Failed to send the acceptance to client " + Str(*Client\ClientId)) + ProcedureReturn #False + EndIf + + *Client\Metadata\Status = #BakaShrot_ConnectionStatus_Authenticated + If *Client\PeerName = "" + PrintN("[Net] Client " + Str(*Client\ClientId) + " authenticated as '" + ClientName + "' " + BakaShrot_Names_TopicRef(TopicId) + ":" + BakaShrot_Names_NodeRef(NodeId)) + Else + PrintN("[Net] Client " + Str(*Client\ClientId) + " authenticated as '" + ClientName + "' " + BakaShrot_Names_TopicRef(TopicId) + ":" + BakaShrot_Names_NodeRef(NodeId) + ", peer '" + *Client\PeerName + "'") + EndIf + + ProcedureReturn #True +EndProcedure + + +; Encodes and sends a RequestRefused. +; Returns #False if it couldn't be sent, the client must then be aborted. +Procedure.i BakaShrot_NetClient_Refuse(*Client.BakaShrot_NetClient, Reason.s) + Protected Refused.BakaShrot_RequestRefused + Protected *Packet, PacketSize.Integer, Sent.i + + PrintN("[Net] Refused a request from client " + Str(*Client\ClientId) + ": " + Reason) + + Refused\Reason = Reason + *Packet = BakaShrot_RequestRefusedPacket_Encode(@Refused, @PacketSize) + If Not *Packet + ProcedureReturn #False + EndIf + Sent = BakaShrot_SendPacket(*Client\ClientId, *Packet, PacketSize\i, @*Client\Metadata\Cipher) + FreeMemory(*Packet) + + ProcedureReturn Sent +EndProcedure + + +; Stores the pushed message in the asked topic (its authenticated one if +; none) under the client's authenticated node, with the next message id for +; them, and answers with that id. JSON or not: SQLite flags it in is_json, +; nothing here looks inside it. +; Returns #False if the client must be aborted. +Procedure.i BakaShrot_NetClient_HandlePushMessage(*Client.BakaShrot_NetClient, *Packet, PacketSize.i) + Protected *View.MsgPackData, *Push.BakaShrot_PushMessage + Protected Pushed.BakaShrot_MessagePushed + Protected JsonData.s, TopicRef.s, TopicId.i, JsonSize.i, MessageId.q, StoreError.String + Protected *Answer, AnswerSize.Integer, Sent.i + + *Push = 0 + *View = MsgPackWrapMsgBuffer(*Packet, PacketSize) + If *View + *Push = BakaShrot_PushMessagePacket_Decode(*View) + MsgPackFree(*View, #False) + EndIf + If Not *Push + PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an invalid push") + ProcedureReturn #False + EndIf + JsonData = *Push\JsonData + TopicRef = *Push\Topic + FreeStructure(*Push) + + ; The node is the authenticated one, the client never sends it here. + If *Client\Metadata\Status <> #BakaShrot_ConnectionStatus_Authenticated + PrintN("[Net] Client " + Str(*Client\ClientId) + " pushed without being authenticated") + ProcedureReturn #False + EndIf + + If Not *Client\Permissions\Write + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to write") + EndIf + + If TopicRef = "" + TopicId = *Client\Metadata\TopicId + Else + TopicId = BakaShrot_Names_ResolveTopic(TopicRef) + If TopicId < 0 + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown topic '" + Left(TopicRef, 80) + "'") + EndIf + EndIf + If Not NameSetHas(@*Client\PushTopics, TopicId, BakaShrot_Names_TopicName(TopicId)) + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to push to topic '" + BakaShrot_Names_TopicRef(TopicId) + "'") + EndIf + + ; So it fits in every packet that carries it later, see Packets.pbi. + JsonSize = StringByteLength(JsonData, #PB_UTF8) + If JsonSize > #BakaShrot_MaxMessageSize + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The message is too big: " + Str(JsonSize) + " bytes, at most " + Str(#BakaShrot_MaxMessageSize)) + EndIf + + ; A topic allowed by "*" may be new here, it needs its row for the + ; "messages" view. + If Not BakaShrot_Names_EnsureTopicId(TopicId, @StoreError) + PrintN("[Net] Failed to register topic " + Str(TopicId) + ": " + StoreError\s) + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The message couldn't be stored") + EndIf + + MessageId = InsertNextMessage(TopicId, *Client\Metadata\NodeId, JsonData, @StoreError) + If MessageId < 1 + PrintN("[Net] Failed to store a message from client " + Str(*Client\ClientId) + ": " + StoreError\s) + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The message couldn't be stored") + EndIf + + Pushed\MessageId = MessageId + *Answer = BakaShrot_MessagePushedPacket_Encode(@Pushed, @AnswerSize) + If Not *Answer + ProcedureReturn #False + EndIf + Sent = BakaShrot_SendPacket(*Client\ClientId, *Answer, AnswerSize\i, @*Client\Metadata\Cipher) + FreeMemory(*Answer) + + CompilerIf #BakaShrot_Net_LogRequests + PrintN("[Net] Client " + Str(*Client\ClientId) + " pushed message " + Str(TopicId) + ":" + Str(*Client\Metadata\NodeId) + "#" + Str(MessageId)) + CompilerEndIf + ProcedureReturn Sent +EndProcedure + + +; Answers with the latest message of the asked topic/node. +; Refuses if the client may not read that topic, if either is unknown, or if +; there's no message. +; Returns #False if the client must be aborted. +Procedure.i BakaShrot_NetClient_HandleGetLatestMessage(*Client.BakaShrot_NetClient, *Packet, PacketSize.i) + Protected *View.MsgPackData, *Request.BakaShrot_GetLatestMessage + Protected Latest.BakaShrot_LatestMessage + Protected Message.BakaShrot_Message + Protected TopicId.i, NodeId.i, TopicRef.s, NodeRef.s + Protected *Answer, AnswerSize.Integer, Sent.i + + *Request = 0 + *View = MsgPackWrapMsgBuffer(*Packet, PacketSize) + If *View + *Request = BakaShrot_GetLatestMessagePacket_Decode(*View) + MsgPackFree(*View, #False) + EndIf + If Not *Request + PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an invalid latest message request") + ProcedureReturn #False + EndIf + TopicRef = *Request\Topic + NodeRef = *Request\Node + FreeStructure(*Request) + + If *Client\Metadata\Status <> #BakaShrot_ConnectionStatus_Authenticated + PrintN("[Net] Client " + Str(*Client\ClientId) + " asked for a message without being authenticated") + ProcedureReturn #False + EndIf + + If Not *Client\Permissions\Read + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to read") + EndIf + + TopicId = BakaShrot_Names_ResolveTopic(TopicRef) + If TopicId < 0 + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown topic '" + Left(TopicRef, 80) + "'") + EndIf + If Not NameSetHas(@*Client\ReadTopics, TopicId, BakaShrot_Names_TopicName(TopicId)) + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to read topic '" + BakaShrot_Names_TopicRef(TopicId) + "'") + EndIf + NodeId = BakaShrot_Names_ResolveNode(NodeRef) + If NodeId < 0 + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown node '" + Left(NodeRef, 80) + "'") + EndIf + + If Not GetLatestMessage(*Client\DbId, TopicId, NodeId, @Message) + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "No message for " + BakaShrot_Names_TopicRef(TopicId) + ":" + BakaShrot_Names_NodeRef(NodeId)) + EndIf + + Latest\TopicId = TopicId + Latest\NodeId = NodeId + Latest\TopicName = BakaShrot_Names_TopicRef(TopicId) + Latest\NodeName = BakaShrot_Names_NodeRef(NodeId) + Latest\MessageId = Message\MessageId + Latest\JsonData = Message\JsonData + *Answer = BakaShrot_LatestMessagePacket_Encode(@Latest, @AnswerSize) + If Not *Answer + ProcedureReturn #False + EndIf + Sent = BakaShrot_SendPacket(*Client\ClientId, *Answer, AnswerSize\i, @*Client\Metadata\Cipher) + FreeMemory(*Answer) + + CompilerIf #BakaShrot_Net_LogRequests + PrintN("[Net] Client " + Str(*Client\ClientId) + " got message " + Str(TopicId) + ":" + Str(NodeId) + "#" + Str(Message\MessageId)) + CompilerEndIf + ProcedureReturn Sent +EndProcedure + + +; Answers with the messages of the asked topic/node after the asked id: as +; many as asked for that fit in about #BakaShrot_MessagesBatchBytes, a +; bigger one alone. None if there are no more, that isn't refused. +; Refuses if the client may not read that topic, or if either is unknown. +; Returns #False if the client must be aborted. +Procedure.i BakaShrot_NetClient_HandleGetMessages(*Client.BakaShrot_NetClient, *Packet, PacketSize.i) + Protected *View.MsgPackData, *Request.BakaShrot_GetMessages + Protected Answer.BakaShrot_Messages + Protected NewList Messages.BakaShrot_Message() + Protected TopicId.i, NodeId.i, TopicRef.s, NodeRef.s, AfterMessageId.q, Limit.i + Protected More.Integer, BatchSize.i, MessageSize.i + Protected *Answer, AnswerSize.Integer, Sent.i + + *Request = 0 + *View = MsgPackWrapMsgBuffer(*Packet, PacketSize) + If *View + *Request = BakaShrot_GetMessagesPacket_Decode(*View) + MsgPackFree(*View, #False) + EndIf + If Not *Request + PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an invalid messages request") + ProcedureReturn #False + EndIf + TopicRef = *Request\Topic + NodeRef = *Request\Node + AfterMessageId = *Request\AfterMessageId + Limit = *Request\Limit + FreeStructure(*Request) + + If *Client\Metadata\Status <> #BakaShrot_ConnectionStatus_Authenticated + PrintN("[Net] Client " + Str(*Client\ClientId) + " asked for messages without being authenticated") + ProcedureReturn #False + EndIf + + If Not *Client\Permissions\Read + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to read") + EndIf + + TopicId = BakaShrot_Names_ResolveTopic(TopicRef) + If TopicId < 0 + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown topic '" + Left(TopicRef, 80) + "'") + EndIf + If Not NameSetHas(@*Client\ReadTopics, TopicId, BakaShrot_Names_TopicName(TopicId)) + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to read topic '" + BakaShrot_Names_TopicRef(TopicId) + "'") + EndIf + NodeId = BakaShrot_Names_ResolveNode(NodeRef) + If NodeId < 0 + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown node '" + Left(NodeRef, 80) + "'") + EndIf + + ; In characters, the bytes are counted below: never less than that. + If Not GetMessagesAfter(*Client\DbId, TopicId, NodeId, AfterMessageId, Limit, #BakaShrot_MessagesBatchBytes, Messages(), @More) + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The messages couldn't be read") + EndIf + + ; As many as fit in #BakaShrot_MessagesBatchBytes, the rest is for the + ; next request. A bigger message goes alone, it always fits in a packet. + Answer\More = More\i + BatchSize = #BakaShrot_MessagesOverhead + ForEach Messages() + MessageSize = #BakaShrot_MessagesMessageOverhead + StringByteLength(Messages()\JsonData, #PB_UTF8) + If ListSize(Answer\Messages()) > 0 And (BatchSize + MessageSize > #BakaShrot_MessagesBatchBytes Or BatchSize + MessageSize > #BakaShrot_MaxPacketSize) + Answer\More = #True + Break + EndIf + BatchSize + MessageSize + + AddElement(Answer\Messages()) + Answer\Messages()\MessageId = Messages()\MessageId + Answer\Messages()\JsonData = Messages()\JsonData + Next + ClearList(Messages()) + + Answer\TopicId = TopicId + Answer\NodeId = NodeId + Answer\TopicName = BakaShrot_Names_TopicRef(TopicId) + Answer\NodeName = BakaShrot_Names_NodeRef(NodeId) + *Answer = BakaShrot_MessagesPacket_Encode(@Answer, @AnswerSize) + If Not *Answer + ProcedureReturn #False + EndIf + Sent = BakaShrot_SendPacket(*Client\ClientId, *Answer, AnswerSize\i, @*Client\Metadata\Cipher) + FreeMemory(*Answer) + + CompilerIf #BakaShrot_Net_LogRequests + PrintN("[Net] Client " + Str(*Client\ClientId) + " got " + Str(ListSize(Answer\Messages())) + " messages of " + Str(TopicId) + ":" + Str(NodeId) + " after #" + Str(AfterMessageId)) + CompilerEndIf + ProcedureReturn Sent +EndProcedure + + +; Runs a raw read-only SQL query and answers with its rows as JSON, see +; RunReadOnlyQuery() in Storage/Storage.pbi. +; Refuses clients not allowed to query, and results too big for one packet. +; Returns #False if the client must be aborted. +Procedure.i BakaShrot_NetClient_HandleQuery(*Client.BakaShrot_NetClient, *Packet, PacketSize.i) + Protected *View.MsgPackData, *Request.BakaShrot_QueryRequest + Protected Result.BakaShrot_QueryResult + Protected Sql.s, JsonResult.String, QueryError.String + Protected *Answer, AnswerSize.Integer, Sent.i + + *Request = 0 + *View = MsgPackWrapMsgBuffer(*Packet, PacketSize) + If *View + *Request = BakaShrot_QueryRequestPacket_Decode(*View) + MsgPackFree(*View, #False) + EndIf + If Not *Request + PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an invalid query") + ProcedureReturn #False + EndIf + Sql = *Request\Sql + FreeStructure(*Request) + + If Not *Client\Permissions\Query + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to query") + EndIf + + If Not RunReadOnlyQuery(*Client\Server\DatabasePath, Sql, @JsonResult, @QueryError) + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Query failed: " + QueryError\s) + EndIf + + ; Leaves room for the packet's own fields. + If StringByteLength(JsonResult\s, #PB_UTF8) > #BakaShrot_MaxPacketSize - 64 + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The result is too big for one packet, add a LIMIT") + EndIf + + Result\JsonResult = JsonResult\s + *Answer = BakaShrot_QueryResultPacket_Encode(@Result, @AnswerSize) + If Not *Answer + ProcedureReturn #False + EndIf + Sent = BakaShrot_SendPacket(*Client\ClientId, *Answer, AnswerSize\i, @*Client\Metadata\Cipher) + FreeMemory(*Answer) + + CompilerIf #BakaShrot_Net_LogRequests + PrintN("[Net] Client " + Str(*Client\ClientId) + " ran a query, " + Str(AnswerSize\i) + " bytes of results") + CompilerEndIf + ProcedureReturn Sent +EndProcedure + + +; Answers with this server's id and name of a topic or node. +; Topics: only those the client may push to or read, unless it may query. +; Returns #False if the client must be aborted. +Procedure.i BakaShrot_NetClient_HandleResolveName(*Client.BakaShrot_NetClient, *Packet, PacketSize.i) + Protected *View.MsgPackData, *Request.BakaShrot_ResolveName + Protected Resolved.BakaShrot_NameResolved + Protected Kind.i, Ref.s, Id.i + Protected *Answer, AnswerSize.Integer, Sent.i + + *Request = 0 + *View = MsgPackWrapMsgBuffer(*Packet, PacketSize) + If *View + *Request = BakaShrot_ResolveNamePacket_Decode(*View) + MsgPackFree(*View, #False) + EndIf + If Not *Request + PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an invalid name request") + ProcedureReturn #False + EndIf + Kind = *Request\Kind + Ref = *Request\Ref + FreeStructure(*Request) + + If Kind = #BakaShrot_NameKind_Topic + Id = BakaShrot_Names_ResolveTopic(Ref) + If Id < 0 + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown topic '" + Left(Ref, 80) + "'") + EndIf + If Not *Client\Permissions\Query And Not NameSetHas(@*Client\PushTopics, Id, BakaShrot_Names_TopicName(Id)) And Not NameSetHas(@*Client\ReadTopics, Id, BakaShrot_Names_TopicName(Id)) + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown topic '" + Left(Ref, 80) + "'") + EndIf + Resolved\Name = BakaShrot_Names_TopicName(Id) + Else + Id = BakaShrot_Names_ResolveNode(Ref) + If Id < 0 + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown node '" + Left(Ref, 80) + "'") + EndIf + Resolved\Name = BakaShrot_Names_NodeName(Id) + EndIf + + Resolved\Kind = Kind + Resolved\Id = Id + *Answer = BakaShrot_NameResolvedPacket_Encode(@Resolved, @AnswerSize) + If Not *Answer + ProcedureReturn #False + EndIf + Sent = BakaShrot_SendPacket(*Client\ClientId, *Answer, AnswerSize\i, @*Client\Metadata\Cipher) + FreeMemory(*Answer) + + ProcedureReturn Sent +EndProcedure + + +; Lists every topic (those the client may push to or read, unless it may +; query) or node, with its id, name and origin, as many as fit in one packet. +; Returns #False if the client must be aborted. +Procedure.i BakaShrot_NetClient_HandleListNames(*Client.BakaShrot_NetClient, *Packet, PacketSize.i) + Protected *View.MsgPackData, *Request.BakaShrot_ListNames + Protected Answer.BakaShrot_NamesList, Visible.BakaShrot_NameSet + Protected NewList All.BakaShrot_NameEntry() + Protected Kind.i, Size.i, EntrySize.i + Protected *Answer, AnswerSize.Integer, Sent.i + + *Request = 0 + *View = MsgPackWrapMsgBuffer(*Packet, PacketSize) + If *View + *Request = BakaShrot_ListNamesPacket_Decode(*View) + MsgPackFree(*View, #False) + EndIf + If Not *Request + PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an invalid names list request") + ProcedureReturn #False + EndIf + Kind = *Request\Kind + FreeStructure(*Request) + + If Kind = #BakaShrot_NameKind_Topic And Not *Client\Permissions\Query + ; The topics it may push to or read. + Visible\All = Bool(*Client\PushTopics\All Or *Client\ReadTopics\All) + Visible\Known = Bool(*Client\PushTopics\Known Or *Client\ReadTopics\Known) + ForEach *Client\PushTopics\Ids() + Visible\Ids(MapKey(*Client\PushTopics\Ids())) = #True + Next + ForEach *Client\ReadTopics\Ids() + Visible\Ids(MapKey(*Client\ReadTopics\Ids())) = #True + Next + ForEach *Client\PushTopics\Patterns() + AddElement(Visible\Patterns()) : Visible\Patterns() = *Client\PushTopics\Patterns() + Next + ForEach *Client\ReadTopics\Patterns() + AddElement(Visible\Patterns()) : Visible\Patterns() = *Client\ReadTopics\Patterns() + Next + BakaShrot_Names_GetAll(Kind, All(), @Visible) + Else + BakaShrot_Names_GetAll(Kind, All()) + EndIf + + Answer\Kind = Kind + Size = #BakaShrot_NamesListOverhead + ForEach All() + EntrySize = #BakaShrot_NamesListEntryOverhead + StringByteLength(All()\Name, #PB_UTF8) + StringByteLength(All()\Origin, #PB_UTF8) + If Size + EntrySize > #BakaShrot_MaxPacketSize + Answer\Truncated = #True + Break + EndIf + Size + EntrySize + AddElement(Answer\Entries()) + Answer\Entries()\Id = All()\Id + Answer\Entries()\Name = All()\Name + Answer\Entries()\Origin = All()\Origin + Next + + *Answer = BakaShrot_NamesListPacket_Encode(@Answer, @AnswerSize) + If Not *Answer + ProcedureReturn #False + EndIf + Sent = BakaShrot_SendPacket(*Client\ClientId, *Answer, AnswerSize\i, @*Client\Metadata\Cipher) + FreeMemory(*Answer) + + ProcedureReturn Sent +EndProcedure + + +; Answers a peer with this server's sync state, see SyncStatePacket.pbi: +; every name it knows and takes from that peer (its AcceptTopics and +; AcceptNodes), their wildcards, and the highest message id it has for each +; topic/node of those. Unnamed ones don't replicate. +; Refuses regular clients. +; Returns #False if the client must be aborted. +Procedure.i BakaShrot_NetClient_HandleSyncStateRequest(*Client.BakaShrot_NetClient, *Packet, PacketSize.i) + Protected *View.MsgPackData, *Request.BakaShrot_SyncStateRequest + Protected State.BakaShrot_SyncState + Protected NewList AllPairs.BakaShrot_SyncPair() + Protected NewMap Topics.i(), NewMap Nodes.i() + Protected *Answer, AnswerSize.Integer, Sent.i + + *Request = 0 + *View = MsgPackWrapMsgBuffer(*Packet, PacketSize) + If *View + *Request = BakaShrot_SyncStateRequestPacket_Decode(*View) + MsgPackFree(*View, #False) + EndIf + If Not *Request + PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an invalid sync state request") + ProcedureReturn #False + EndIf + FreeStructure(*Request) + + If *Client\PeerName = "" + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Only peers can replicate") + EndIf + + If Not GetSyncState(*Client\DbId, AllPairs()) + PrintN("[Net] Failed to read the sync state for peer '" + *Client\PeerName + "': " + DatabaseError()) + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The sync state couldn't be read") + EndIf + + ; Every name this server knows, the peer only sends those. + BakaShrot_Names_GetNamed(#BakaShrot_NameKind_Topic, State\Topics(), @*Client\AcceptTopics) + BakaShrot_Names_GetNamed(#BakaShrot_NameKind_Node, State\Nodes(), @*Client\AcceptNodes) + If *Client\AcceptTopics\All + AddElement(State\TopicPatterns()) : State\TopicPatterns() = "*" + EndIf + ForEach *Client\AcceptTopics\Patterns() + AddElement(State\TopicPatterns()) : State\TopicPatterns() = *Client\AcceptTopics\Patterns() + Next + If *Client\AcceptNodes\All + AddElement(State\NodePatterns()) : State\NodePatterns() = "*" + EndIf + ForEach *Client\AcceptNodes\Patterns() + AddElement(State\NodePatterns()) : State\NodePatterns() = *Client\AcceptNodes\Patterns() + Next + ForEach State\Topics() + Topics(Str(State\Topics()\Id)) = #True + Next + ForEach State\Nodes() + Nodes(Str(State\Nodes()\Id)) = #True + Next + ForEach AllPairs() + If FindMapElement(Topics(), Str(AllPairs()\TopicId)) And FindMapElement(Nodes(), Str(AllPairs()\NodeId)) + AddElement(State\Pairs()) + State\Pairs()\TopicId = AllPairs()\TopicId + State\Pairs()\NodeId = AllPairs()\NodeId + State\Pairs()\MessageId = AllPairs()\MessageId + EndIf + Next + + *Answer = BakaShrot_SyncStatePacket_Encode(@State, @AnswerSize) + If Not *Answer + PrintN("[Net] Failed to encode the sync state for peer '" + *Client\PeerName + "', is it too big?") + ProcedureReturn #False + EndIf + Sent = BakaShrot_SendPacket(*Client\ClientId, *Answer, AnswerSize\i, @*Client\Metadata\Cipher) + FreeMemory(*Answer) + + ProcedureReturn Sent +EndProcedure + + +; Stores a batch of messages a peer replicated, under this server's ids for +; their topic and node names and their original message ids, in one +; transaction, and answers with the last one's message id. +; Refuses regular clients, and topics or nodes this server doesn't take from +; that peer (AcceptTopics, AcceptNodes): only what's named on both servers +; replicates, unless a wildcard there takes a name this server doesn't have, +; which is then added, see Storage/Names.pbi. The sync state tells the peer +; what's taken here, so it doesn't send the rest in the first place. +; Returns #False if the client must be aborted. +Procedure.i BakaShrot_NetClient_HandleReplicateMessages(*Client.BakaShrot_NetClient, *Packet, PacketSize.i) + Protected *View.MsgPackData, *Batch.BakaShrot_ReplicateMessages + Protected Pushed.BakaShrot_MessagePushed + Protected TopicId.i, NodeId.i, TopicRef.s, NodeRef.s, LastMessageId.q, IsStored.i, StoreError.String + Protected *Answer, AnswerSize.Integer, Sent.i + + *Batch = 0 + *View = MsgPackWrapMsgBuffer(*Packet, PacketSize) + If *View + *Batch = BakaShrot_ReplicateMessagesPacket_Decode(*View) + MsgPackFree(*View, #False) + EndIf + If Not *Batch + PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an invalid batch of replicated messages") + ProcedureReturn #False + EndIf + TopicRef = *Batch\Topic + NodeRef = *Batch\Node + LastElement(*Batch\Messages()) + LastMessageId = *Batch\Messages()\MessageId + + If *Client\PeerName = "" + FreeStructure(*Batch) + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Only peers can replicate") + EndIf + + TopicId = BakaShrot_Names_TopicByName(TopicRef) + If Not NameSetHas(@*Client\AcceptTopics, TopicId, TopicRef) + FreeStructure(*Batch) + BakaShrot_Names_NoteDropped(*Client\PeerName, "topic", TopicRef, "not taken here") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Topic '" + TopicRef + "' isn't replicated here") + EndIf + NodeId = BakaShrot_Names_NodeByName(NodeRef) + If Not NameSetHas(@*Client\AcceptNodes, NodeId, NodeRef) + FreeStructure(*Batch) + BakaShrot_Names_NoteDropped(*Client\PeerName, "node", NodeRef, "not taken here") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Node '" + NodeRef + "' isn't replicated here") + EndIf + + ; Taken by a wildcard, new here. + If TopicId < 0 + TopicId = BakaShrot_Names_Ingest(#BakaShrot_NameKind_Topic, TopicRef, @StoreError) + EndIf + If TopicId >= 0 And NodeId < 0 + NodeId = BakaShrot_Names_Ingest(#BakaShrot_NameKind_Node, NodeRef, @StoreError) + EndIf + If TopicId < 0 Or NodeId < 0 + FreeStructure(*Batch) + PrintN("[Net] Failed to add '" + TopicRef + "':'" + NodeRef + "' from peer '" + *Client\PeerName + "': " + StoreError\s) + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The messages couldn't be stored") + EndIf + + IsStored = InsertReplicatedMessages(TopicId, NodeId, *Batch\Messages(), @StoreError) + FreeStructure(*Batch) + If Not IsStored + PrintN("[Net] Failed to store messages from peer '" + *Client\PeerName + "': " + StoreError\s) + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The messages couldn't be stored") + EndIf + + Pushed\MessageId = LastMessageId + *Answer = BakaShrot_MessagePushedPacket_Encode(@Pushed, @AnswerSize) + If Not *Answer + ProcedureReturn #False + EndIf + Sent = BakaShrot_SendPacket(*Client\ClientId, *Answer, AnswerSize\i, @*Client\Metadata\Cipher) + FreeMemory(*Answer) + + ProcedureReturn Sent +EndProcedure + + +; Handles one request from an authenticated client. +; Returns #False if the client must be aborted. +Procedure.i BakaShrot_NetClient_HandleRequest(*Client.BakaShrot_NetClient, *Packet, PacketSize.i) + Select BakaShrot_GetPacketType(*Packet, PacketSize) + Case #BakaShrot_PacketType_PushMessage + ProcedureReturn BakaShrot_NetClient_HandlePushMessage(*Client, *Packet, PacketSize) + + Case #BakaShrot_PacketType_GetLatestMessage + ProcedureReturn BakaShrot_NetClient_HandleGetLatestMessage(*Client, *Packet, PacketSize) + + Case #BakaShrot_PacketType_GetMessages + ProcedureReturn BakaShrot_NetClient_HandleGetMessages(*Client, *Packet, PacketSize) + + Case #BakaShrot_PacketType_QueryRequest + ProcedureReturn BakaShrot_NetClient_HandleQuery(*Client, *Packet, PacketSize) + + Case #BakaShrot_PacketType_ResolveName + ProcedureReturn BakaShrot_NetClient_HandleResolveName(*Client, *Packet, PacketSize) + + Case #BakaShrot_PacketType_ListNames + ProcedureReturn BakaShrot_NetClient_HandleListNames(*Client, *Packet, PacketSize) + + Case #BakaShrot_PacketType_SyncStateRequest + ProcedureReturn BakaShrot_NetClient_HandleSyncStateRequest(*Client, *Packet, PacketSize) + + Case #BakaShrot_PacketType_ReplicateMessages + ProcedureReturn BakaShrot_NetClient_HandleReplicateMessages(*Client, *Packet, PacketSize) + EndSelect + + PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an unexpected packet") + ProcedureReturn #False +EndProcedure + + +Procedure BakaShrot_NetClient_Thread(*Client.BakaShrot_NetClient) + Protected *Server.BakaShrot_NetServer = *Client\Server + Protected *Packet, PacketSize.Integer, Disconnected.i, Handled.i + + If BakaShrot_NetClient_Authenticate(*Client) + *Client\DbId = OpenStorageDatabase(*Server\DatabasePath) + If Not *Client\DbId + PrintN("[Net] Failed to open the database for client " + Str(*Client\ClientId) + ": " + DatabaseError()) + EndIf + EndIf + + If *Client\DbId + Repeat + *Packet = BakaShrot_NetClient_WaitPacket(*Client, @PacketSize, 0) + If Not *Packet + Break + EndIf + + Handled = BakaShrot_NetClient_HandleRequest(*Client, *Packet, PacketSize\i) + FreeMemory(*Packet) + If Not Handled + Break + EndIf + ForEver + EndIf + + ; Removes the client so the listener stops using it, unless it already did + ; because the client disconnected. + LockMutex(*Server\Mutex) + Disconnected = *Client\Disconnected + If FindMapElement(*Server\Clients(), Str(*Client\ClientId)) + If *Server\Clients() = *Client + DeleteMapElement(*Server\Clients()) + EndIf + EndIf + UnlockMutex(*Server\Mutex) + + If Disconnected + *Client\Metadata\Status = #BakaShrot_ConnectionStatus_Disconnected + Else + *Client\Metadata\Status = #BakaShrot_ConnectionStatus_Aborted + CloseNetworkConnection(*Client\ClientId) + PrintN("[Net] Client " + Str(*Client\ClientId) + " aborted") + EndIf + + If *Client\DbId + CloseDatabase(*Client\DbId) + EndIf + BakaShrot_Inbox_Clear(@*Client\Inbox) + BakaShrot_ClearConnectionMetadata(@*Client\Metadata) + ; Out of Clients(), the listener can't set it anymore. + BakaShrot_Signal_Free(*Client\Signal) + FreeStructure(*Client) + + LockMutex(*Server\Mutex) + *Server\ActiveClientThreads - 1 + UnlockMutex(*Server\Mutex) +EndProcedure + + +; Called by the listener thread when a client connects. +Procedure BakaShrot_NetServer_AcceptClient(*Server.BakaShrot_NetServer, ClientId.i) + Protected *Client.BakaShrot_NetClient + + *Client = AllocateStructure(BakaShrot_NetClient) + If Not *Client + PrintN("[Net] Out of memory, refusing client " + Str(ClientId)) + CloseNetworkConnection(ClientId) + ProcedureReturn + EndIf + *Client\Server = *Server + *Client\ClientId = ClientId + *Client\Signal = BakaShrot_Signal_Create() + If Not *Client\Signal + PrintN("[Net] Failed to create a signal, refusing client " + Str(ClientId)) + FreeStructure(*Client) + CloseNetworkConnection(ClientId) + ProcedureReturn + EndIf + + LockMutex(*Server\Mutex) + *Server\Clients(Str(ClientId)) = *Client + *Server\ActiveClientThreads + 1 + UnlockMutex(*Server\Mutex) + + If Not CreateThread(@BakaShrot_NetClient_Thread(), *Client) + LockMutex(*Server\Mutex) + DeleteMapElement(*Server\Clients(), Str(ClientId)) + *Server\ActiveClientThreads - 1 + UnlockMutex(*Server\Mutex) + + BakaShrot_Signal_Free(*Client\Signal) + FreeStructure(*Client) + CloseNetworkConnection(ClientId) + PrintN("[Net] Failed to start a thread, refusing client " + Str(ClientId)) + ProcedureReturn + EndIf + + PrintN("[Net] Client " + Str(ClientId) + " connected") +EndProcedure + + +; Called by the listener thread when a client sent data. +Procedure BakaShrot_NetServer_ReceiveClientData(*Server.BakaShrot_NetServer, ClientId.i, *Buffer) + Protected *Client.BakaShrot_NetClient, Received.i + + ; Done while holding the mutex, so the client's thread can't close the + ; connection in the middle of it. + LockMutex(*Server\Mutex) + If FindMapElement(*Server\Clients(), Str(ClientId)) + *Client = *Server\Clients() + Received = ReceiveNetworkData(ClientId, *Buffer, #BakaShrot_Net_ReceiveBufferSize) + If Received > 0 + If Not BakaShrot_Inbox_Append(@*Client\Inbox, *Buffer, Received) + *Client\Overflowed = #True + EndIf + BakaShrot_Signal_Set(*Client\Signal) + EndIf + EndIf + UnlockMutex(*Server\Mutex) +EndProcedure + + +; Called by the listener thread when a client disconnected. +Procedure BakaShrot_NetServer_DropClient(*Server.BakaShrot_NetServer, ClientId.i) + Protected *Client.BakaShrot_NetClient + + LockMutex(*Server\Mutex) + If FindMapElement(*Server\Clients(), Str(ClientId)) + *Client = *Server\Clients() + *Client\Disconnected = #True + BakaShrot_Signal_Set(*Client\Signal) + DeleteMapElement(*Server\Clients()) + EndIf + UnlockMutex(*Server\Mutex) +EndProcedure + + +; Sleeps until a client sends something, connects or disconnects, for up to +; TimeoutMs. *Set is just a buffer, reused to save allocating it every time. +Procedure BakaShrot_NetServer_WaitEvent(*Server.BakaShrot_NetServer, *Set.BakaShrot_SocketSet, TimeoutMs.i) + Protected *Client.BakaShrot_NetClient + + BakaShrot_SocketSet_Clear(*Set) + BakaShrot_SocketSet_Add(*Set, ServerID(*Server\ServerId)) + LockMutex(*Server\Mutex) + ForEach *Server\Clients() + *Client = *Server\Clients() + BakaShrot_SocketSet_Add(*Set, ConnectionID(*Client\ClientId)) + Next + UnlockMutex(*Server\Mutex) + + BakaShrot_SocketSet_Wait(*Set, TimeoutMs) +EndProcedure + + +Procedure BakaShrot_NetServer_Thread(*Server.BakaShrot_NetServer) + Protected *Buffer, *Set.BakaShrot_SocketSet + + *Buffer = AllocateMemory(#BakaShrot_Net_ReceiveBufferSize) + *Set = AllocateStructure(BakaShrot_SocketSet) + If Not *Buffer Or Not *Set + PrintN("[Net] Failed to allocate the receive buffer") + ProcedureReturn + EndIf + + While Not *Server\StopRequested + Select NetworkServerEvent(*Server\ServerId) + + Case #PB_NetworkEvent_Connect + BakaShrot_NetServer_AcceptClient(*Server, EventClient()) + + Case #PB_NetworkEvent_Data + BakaShrot_NetServer_ReceiveClientData(*Server, EventClient(), *Buffer) + + Case #PB_NetworkEvent_Disconnect + BakaShrot_NetServer_DropClient(*Server, EventClient()) + + Default + ; Nothing left, sleeps until there's something, waking up at + ; least every 20 ms to check StopRequested. + BakaShrot_NetServer_WaitEvent(*Server, *Set, 20) + + EndSelect + Wend + + FreeStructure(*Set) + FreeMemory(*Buffer) +EndProcedure + + +; Starts listening on Host:Port, an empty Host binds to every interface. +; Clients are authenticated against *Config's [BakaShrot.Client.] +; sections, and their messages are stored in its [BakaShrot.Server] +; DatabasePath. *Config must outlive the server. +; Returns 0 on failure, stop the returned server with BakaShrot_NetServer_Stop(). +Procedure.i BakaShrot_NetServer_Start(Host.s, Port.u, *Config.BakaShrot_CoreConfig) + Protected *Server.BakaShrot_NetServer + + ; Only needed before PureBasic 6.00. + CompilerIf #PB_Compiler_Version < 600 + If Not InitNetwork() + ProcedureReturn 0 + EndIf + CompilerEndIf + + ; Verifies the challenge responses. + If Not InitCryptography() + ProcedureReturn 0 + EndIf + + ; Challenges and nonces come from it. + If Not OpenCryptRandom() + ProcedureReturn 0 + EndIf + + *Server = AllocateStructure(BakaShrot_NetServer) + If Not *Server + CloseCryptRandom() + ProcedureReturn 0 + EndIf + *Server\Config = *Config + *Server\DatabasePath = *Config\Server\DatabasePath + + ; Its identity: clients seal their Hello for it, and check it signed the + ; handshake. + If Not DecodeKeyFromString(*Config\PrivateKey, @*Server\PrivateKey[0], #BakaShrot_Ed25519_PrivateKeySize) + PrintN("[Net] [BakaShrot] PrivateKey is missing or invalid") + FreeStructure(*Server) + CloseCryptRandom() + ProcedureReturn 0 + EndIf + GetPublicKeyFromPrivateKey(@*Server\PrivateKey[0], @*Server\PublicKey[0]) + If Not BakaShrot_Session_LoadHelloKeys(@*Server\HelloKeys, @*Server\PrivateKey[0]) + PrintN("[Net] [BakaShrot] PrivateKey can't be used to open hellos") + sodium_memzero(@*Server\PrivateKey[0], #BakaShrot_Ed25519_PrivateKeySize) + FreeStructure(*Server) + CloseCryptRandom() + ProcedureReturn 0 + EndIf + ; Clients need it as their ServerPublicKey. + PrintN("[Net] Server public key: " + EncodeKeyToString(@*Server\PublicKey[0], #BakaShrot_Ed25519_PublicKeySize)) + + *Server\Mutex = CreateMutex() + If Not *Server\Mutex + FreeStructure(*Server) + CloseCryptRandom() + ProcedureReturn 0 + EndIf + + If Host = "" + *Server\ServerId = CreateNetworkServer(#PB_Any, Port, #PB_Network_TCP | #PB_Network_IPv4) + Else + *Server\ServerId = CreateNetworkServer(#PB_Any, Port, #PB_Network_TCP | #PB_Network_IPv4, Host) + EndIf + If Not *Server\ServerId + FreeMutex(*Server\Mutex) + FreeStructure(*Server) + CloseCryptRandom() + ProcedureReturn 0 + EndIf + + *Server\ThreadId = CreateThread(@BakaShrot_NetServer_Thread(), *Server) + If Not *Server\ThreadId + CloseNetworkServer(*Server\ServerId) + FreeMutex(*Server\Mutex) + FreeStructure(*Server) + CloseCryptRandom() + ProcedureReturn 0 + EndIf + + ProcedureReturn *Server +EndProcedure + + +; Stops every thread, closes the server and frees *Server. +; Connected clients are dropped. Once it returns, no client thread is left, +; so none holds a database connection either. +Procedure BakaShrot_NetServer_Stop(*Server.BakaShrot_NetServer) + Protected ActiveClientThreads.i + + *Server\StopRequested = #True + WaitThread(*Server\ThreadId) + + ; Client threads notice StopRequested within a few ms and close their connection. + Repeat + LockMutex(*Server\Mutex) + ActiveClientThreads = *Server\ActiveClientThreads + UnlockMutex(*Server\Mutex) + If ActiveClientThreads = 0 + Break + EndIf + Delay(5) + ForEver + + CloseNetworkServer(*Server\ServerId) + FreeMutex(*Server\Mutex) + ; Don't leave the private key lying around in freed memory. + sodium_memzero(@*Server\PrivateKey[0], #BakaShrot_Ed25519_PrivateKeySize) + BakaShrot_Session_ClearHelloKeys(@*Server\HelloKeys) + FreeStructure(*Server) + CloseCryptRandom() +EndProcedure diff --git a/Server/Networking/Networking.pbi.cfg b/Server/Networking/Networking.pbi.cfg new file mode 100644 index 0000000..489f748 --- /dev/null +++ b/Server/Networking/Networking.pbi.cfg @@ -0,0 +1,7 @@ +IDE Options = PureBasic 6.41 beta 2 (Windows - x64) +EnableThread +EnableXP +DPIAware +CompileSourceDirectory +EnableCompileCount = 0 +EnableBuildCount = 0 diff --git a/Server/Networking/Peers.pbi b/Server/Networking/Peers.pbi new file mode 100644 index 0000000..214d65d --- /dev/null +++ b/Server/Networking/Peers.pbi @@ -0,0 +1,568 @@ +; ============================================================================ +; BakaShrot Server Peers +; +; Links this server to the other servers in its config's +; [BakaShrot.Peer.] 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.]. +; 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. +; 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.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: " + *Refused\Reason) + FreeStructure(*Refused) + 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 + Batch\Messages()\JsonData = Messages()\JsonData + 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 + + ProcedureReturn #True +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.] 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\Topic = BakaShrot_Names_TopicRef(*Config\TopicId) + *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 diff --git a/Server/Root.pbi b/Server/Root.pbi new file mode 100644 index 0000000..9336113 --- /dev/null +++ b/Server/Root.pbi @@ -0,0 +1,207 @@ +; ============================================================================ +; 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 "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 + + *Config = LoadConfig(*Root\ConfigPath) + 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 + "' (Topic=" + *Config\TopicText + ", 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 + + *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") + 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 + + *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) + "'") + 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 + 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 + + ; 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 diff --git a/Server/Storage/Names.pbi b/Server/Storage/Names.pbi new file mode 100644 index 0000000..70c1b0f --- /dev/null +++ b/Server/Storage/Names.pbi @@ -0,0 +1,484 @@ +; ============================================================================ +; 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 in [BakaShrot.Topics] / [BakaShrot.Nodes] +; origin "id" unnamed, its name is its id in digits +; origin "peer" sent by a peer, taken by a wildcard, named by the peer +; +; 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 + + +; --- 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 diff --git a/Server/Storage/Storage.pbi b/Server/Storage/Storage.pbi new file mode 100644 index 0000000..5fcf804 --- /dev/null +++ b/Server/Storage/Storage.pbi @@ -0,0 +1,751 @@ +; ============================================================================ +; 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_v5.dbml in this same folder. +; +; 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. +; +; 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" + + +CompilerIf #PB_Compiler_OS = #PB_OS_Windows + UseSQLiteDatabase("sqlite3.dll") +CompilerElse + UseSQLiteDatabase() +CompilerEndIf + + +; One row of the "data" table (see db_schema_v5.dbml). +Structure BakaShrot_Message + MessageId.q + JsonData.s +EndStructure + + +; 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. +; With WAL, NORMAL only syncs to disk at checkpoints instead of on every +; commit, which is most of what a push used to cost. 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. +; FULL syncs every commit, like before, but still lets reads and writes run +; side by side. +#BakaShrot_Storage_Synchronous = "NORMAL" + + +; 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 + + +; Creates the tables and indexes described by db_schema_v5.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 + + If Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS archives (" + + "delete_by INTEGER NOT NULL, " + + "message_data TEXT NOT NULL)") + ProcedureReturn #False + EndIf + + ; is_json is set by SQLite on insert, and can't be written. + ; 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, " + + "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 + + ; Not used yet, but created now so the on-disk schema already matches + ; db_schema_v1.dbml. + If Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS attachements (" + + "topic_id INTEGER NOT NULL, " + + "node_id INTEGER NOT NULL, " + + "message_id INTEGER NOT NULL, " + + "attachement_data BLOB NOT NULL)") + ProcedureReturn #False + EndIf + If Not DatabaseUpdate(DbId, "CREATE INDEX IF NOT EXISTS idx_attachements_topic_node ON attachements (topic_id, node_id)") + ProcedureReturn #False + EndIf + If Not DatabaseUpdate(DbId, "CREATE INDEX IF NOT EXISTS idx_attachements_message_id ON attachements (message_id)") + 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. + ; !!! Nothing deletes from "data" yet: whatever does must update it too. + 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. + If Not DatabaseUpdate(DbId, "CREATE VIEW IF NOT EXISTS 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 " + + "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 + + ProcedureReturn #True +EndProcedure + + +; Inserts one JSON message into the "data" table. +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) + + ProcedureReturn DatabaseUpdate(DbId, "INSERT INTO data (topic_id, node_id, message_id, message_data) 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 + + + +; 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 message_id, message_data FROM data WHERE topic_id = ? AND node_id = ? ORDER BY message_id DESC LIMIT 1") + ProcedureReturn #False + EndIf + + Found = NextDatabaseRow(DbId) + If Found + *Message\MessageId = GetDatabaseQuad(DbId, 0) + *Message\JsonData = GetDatabaseString(DbId, 1) + 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 sqlite3.dll as PureBasic's +; (DatabaseID() is its sqlite3 handle), like Writer.pbi. +; Elsewhere than Windows, 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 #PB_Compiler_OS = #PB_OS_Windows + 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 sqlite3.dll 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, "sqlite3.dll") + 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 #PB_Compiler_OS = #PB_OS_Windows + 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 #PB_Compiler_OS = #PB_OS_Windows + 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) + + ; Elsewhere than Windows, 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 #PB_Compiler_OS <> #PB_OS_Windows + 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 message_id, message_data FROM data WHERE topic_id = ? AND node_id = ? AND message_id > ? ORDER BY 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) + 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. +; Returns #False if the insert failed. +Procedure.i InsertReplicatedMessage(DbId.i, TopicId.i, NodeId.i, MessageId.q, JsonData.s) + SetDatabaseLong(DbId, 0, TopicId) + SetDatabaseLong(DbId, 1, NodeId) + SetDatabaseQuad(DbId, 2, MessageId) + SetDatabaseString(DbId, 3, JsonData) + ProcedureReturn DatabaseUpdate(DbId, "INSERT OR IGNORE INTO data (topic_id, node_id, message_id, message_data) VALUES (?, ?, ?, ?)") +EndProcedure + + + +; Every write: pushes (group commit), replicated batches, the WAL checkpoints. +XIncludeFile "Writer.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 diff --git a/Server/Storage/Writer.pbi b/Server/Storage/Writer.pbi new file mode 100644 index 0000000..ce1dc51 --- /dev/null +++ b/Server/Storage/Writer.pbi @@ -0,0 +1,783 @@ +; ============================================================================ +; BakaShrot Storage Writer +; +; Every write the server does to its database goes through here: +; InsertNextMessage() pushes, grouped (group commit) +; InsertReplicatedMessages() batches from peers +; on ONE connection, the writer, only ever used while holding +; BakaShrot_Storage_WriteMutex. Opened by OpenStorageWriter() when the +; workers start, closed by CloseStorageWriter() once they're stopped (see +; Server/Root.pbi). The exception to "one connection per thread" (see +; Storage.pbi): it's shared, but never by two threads at once. +; +; What makes it fast, see Design/StorageConcurrency.md: +; - Group commit: each push queues itself, then takes the write mutex. +; Whoever holds it writes every queued push in one transaction, the ones +; that were waiting find theirs done. The busier, the bigger the groups. +; - Prepared statements, kept for as long as the writer is open, through +; SQLite's own API: PureBasic prepares a statement again on every call. +; Same sqlite3.dll as PureBasic's (DatabaseID() is its sqlite3 handle). +; Elsewhere than Windows, PureBasic's own SQLite is linked in, so its +; functions are used instead (slower, same behaviour). +; - The next message id of every topic/node id kept in memory, instead of +; a MAX(message_id) on every push. Read from the database the first time +; a pair is pushed to, raised by the replicated messages, forgotten on a +; rollback. Only right as long as this writer is the only one writing, +; which the write mutex ensures within the server. +; - Checkpoints mostly off the write path: the writer only checkpoints by +; itself past #BakaShrot_Storage_WalBackstopFrames, a background thread +; checkpoints every +; #BakaShrot_Storage_CheckpointInterval ms on its own connection, in +; PASSIVE rounds that don't block anything, finishing with a short one +; under the write mutex so the WAL can start over (see +; BakaShrot_Writer_CheckpointThread()). +; +; Logs a [Storage] line every #BakaShrot_Storage_StatsInterval ms while +; pushes come in: pushes/s, per transaction, write time per push, how busy. +; ============================================================================ + + +; Most pushes in one transaction. +#BakaShrot_Storage_MaxGroupSize = 1000 + +#BakaShrot_Storage_CheckpointInterval = 1000 + +; A checkpoint finishes under the write mutex once at most this many WAL +; frames (4 KB pages) are left to copy, see BakaShrot_Writer_CheckpointThread(). +#BakaShrot_Storage_CheckpointFinishFrames = 2000 +#BakaShrot_Storage_StatsInterval = 10000 + +; The writer still checkpoints by itself (like SQLite does by default, at +; 1000) once the WAL reaches this many frames, when the checkpoint thread +; can't keep up: flat out, ~25,000 frames/s per server. Without it the WAL +; grew to 170,000 frames (700 MB) and Windows started throttling the writes, +; up to 5 s for a push. +#BakaShrot_Storage_WalBackstopFrames = 10000 + +; Once a checkpoint let the WAL start over, its file is truncated to this. +#BakaShrot_Storage_WalSizeLimit = 67108864 + + +CompilerIf #PB_Compiler_OS = #PB_OS_Windows + #BakaShrot_Storage_RawSqlite = #True +CompilerElse + #BakaShrot_Storage_RawSqlite = #False +CompilerEndIf + +#BakaShrot_Sqlite_Done = 101 +#BakaShrot_Sqlite_Row = 100 +#BakaShrot_Sqlite_Static = 0 + +CompilerIf #BakaShrot_Storage_RawSqlite + PrototypeC.l BakaShrot_Sqlite_Prepare16(Db.i, *Sql, Bytes.l, *Statement, *Tail) + PrototypeC.l BakaShrot_Sqlite_BindInt64(Statement.i, Index.l, Value.q) + PrototypeC.l BakaShrot_Sqlite_BindText16(Statement.i, Index.l, *Text, Bytes.l, Destructor.i) + PrototypeC.l BakaShrot_Sqlite_Step(Statement.i) + PrototypeC.l BakaShrot_Sqlite_Reset(Statement.i) + PrototypeC.l BakaShrot_Sqlite_Finalize(Statement.i) + PrototypeC.q BakaShrot_Sqlite_ColumnInt64(Statement.i, Column.l) + PrototypeC.l BakaShrot_Sqlite_Changes(Db.i) + PrototypeC.i BakaShrot_Sqlite_ErrMsg16(Db.i) + PrototypeC.i BakaShrot_Sqlite_DbFilename(Db.i, *Name) + + Structure BakaShrot_SqliteApi + Library.i + Prepare16.BakaShrot_Sqlite_Prepare16 + BindInt64.BakaShrot_Sqlite_BindInt64 + BindText16.BakaShrot_Sqlite_BindText16 + Step_.BakaShrot_Sqlite_Step + Reset.BakaShrot_Sqlite_Reset + Finalize.BakaShrot_Sqlite_Finalize + ColumnInt64.BakaShrot_Sqlite_ColumnInt64 + Changes.BakaShrot_Sqlite_Changes + ErrMsg16.BakaShrot_Sqlite_ErrMsg16 + DbFilename.BakaShrot_Sqlite_DbFilename + EndStructure + + Global BakaShrot_Sqlite.BakaShrot_SqliteApi +CompilerEndIf + + +; A queued push, on the stack of the thread that pushed it, which waits for +; it on the write mutex. +Structure BakaShrot_PushJob + TopicId.i + NodeId.i + JsonData.s + + ; Filled in by whoever writes it, under the write mutex. + MessageId.q + Error.s + Done.i +EndStructure + +Structure BakaShrot_StorageStats + LastLog.i + Groups.q + Pushes.q + Ticks.q +EndStructure + +Structure BakaShrot_StorageWriter + DatabasePath.s + + ; PureBasic database, and its sqlite3 handle. + DbId.i + Handle.i + + ; Prepared once (or the SQL, without the raw API). + Begin.i + Commit.i + Rollback.i + Insert.i + InsertOrIgnore.i + MaxId.i + + ; "TopicId:NodeId" -> the next message id to hand out. + Map NextIds.q() + + ; Set by the last failed statement. + LastError.s + + CheckpointThread.i + StopRequested.i + CheckpointCount.i + CheckpointTicks.q + ; The part of it holding the write mutex. + CheckpointLockedTicks.q + ; Frames in the WAL at the last checkpoint, 4 KB each by default. + WalFrames.i + + Stats.BakaShrot_StorageStats +EndStructure + + +; Taken around every write. SQLite already allows a single writer, but one +; that finds the database locked sleeps and retries (1, 2, 5, 10... ms): +; queued here instead, each one gets it the moment it's free. Only covers +; this process, the busy timeout still handles any other one. +Global BakaShrot_Storage_WriteMutex.i = CreateMutex() + +; Guards BakaShrot_Storage_Queue(), *BakaShrot_PushJob in arrival order. +Global BakaShrot_Storage_QueueMutex.i = CreateMutex() +Global NewList BakaShrot_Storage_Queue.i() + +Global BakaShrot_Storage_Writer.BakaShrot_StorageWriter + +Global BakaShrot_Storage_TicksPerMs.d = 1 + +CompilerIf #PB_Compiler_OS = #PB_OS_Windows + Define BakaShrot_Storage_Frequency.q + QueryPerformanceFrequency_(@BakaShrot_Storage_Frequency) + BakaShrot_Storage_TicksPerMs = BakaShrot_Storage_Frequency / 1000.0 +CompilerEndIf + + +Procedure.q BakaShrot_Storage_Ticks() + CompilerIf #PB_Compiler_OS = #PB_OS_Windows + Protected Ticks.q + QueryPerformanceCounter_(@Ticks) + ProcedureReturn Ticks + CompilerElse + ProcedureReturn ElapsedMilliseconds() + CompilerEndIf +EndProcedure + + +; --- Statements -------------------------------------------------------------- +; Everything below the "Statements" line runs holding the write mutex. + +Procedure.s BakaShrot_Writer_Error() + CompilerIf #BakaShrot_Storage_RawSqlite + If BakaShrot_Storage_Writer\Handle + ProcedureReturn PeekS(BakaShrot_Sqlite\ErrMsg16(BakaShrot_Storage_Writer\Handle), -1, #PB_Unicode) + EndIf + CompilerEndIf + ProcedureReturn DatabaseError() +EndProcedure + + +CompilerIf Not #BakaShrot_Storage_RawSqlite + Procedure.i BakaShrot_Writer_AllocateString(Text.s) + Protected *Buffer = AllocateMemory(StringByteLength(Text) + 2) + If *Buffer + PokeS(*Buffer, Text) + EndIf + ProcedureReturn *Buffer + EndProcedure +CompilerEndIf + +; Returns the prepared statement (the SQL itself without the raw API), or 0. +Procedure.i BakaShrot_Writer_Prepare(Sql.s) + CompilerIf #BakaShrot_Storage_RawSqlite + Protected Statement.i + If BakaShrot_Sqlite\Prepare16(BakaShrot_Storage_Writer\Handle, @Sql, -1, @Statement, 0) <> 0 + BakaShrot_Storage_Writer\LastError = BakaShrot_Writer_Error() + ProcedureReturn 0 + EndIf + ProcedureReturn Statement + CompilerElse + ProcedureReturn BakaShrot_Writer_AllocateString(Sql) + CompilerEndIf +EndProcedure + +Procedure BakaShrot_Writer_Finalize(*Statement.Integer) + If *Statement\i + CompilerIf #BakaShrot_Storage_RawSqlite + BakaShrot_Sqlite\Finalize(*Statement\i) + CompilerElse + FreeMemory(*Statement\i) + CompilerEndIf + *Statement\i = 0 + EndIf +EndProcedure + +; Runs a statement without parameters (BEGIN, COMMIT, ROLLBACK). +Procedure.i BakaShrot_Writer_Run(Statement.i) + CompilerIf #BakaShrot_Storage_RawSqlite + Protected Result.l = BakaShrot_Sqlite\Step_(Statement) + If Result <> #BakaShrot_Sqlite_Done And Result <> #BakaShrot_Sqlite_Row + BakaShrot_Storage_Writer\LastError = BakaShrot_Writer_Error() + BakaShrot_Sqlite\Reset(Statement) + ProcedureReturn #False + EndIf + BakaShrot_Sqlite\Reset(Statement) + ProcedureReturn #True + CompilerElse + If Not DatabaseUpdate(BakaShrot_Storage_Writer\DbId, PeekS(Statement)) + BakaShrot_Storage_Writer\LastError = DatabaseError() + ProcedureReturn #False + EndIf + ProcedureReturn #True + CompilerEndIf +EndProcedure + + +; Inserts one row with Statement (Insert or InsertOrIgnore). +; Returns 1 if inserted, 0 if ignored, -1 if it failed. +Procedure.i BakaShrot_Writer_InsertRow(Statement.i, TopicId.i, NodeId.i, MessageId.q, JsonData.s) + CompilerIf #BakaShrot_Storage_RawSqlite + Protected Result.l + + BakaShrot_Sqlite\BindInt64(Statement, 1, TopicId) + BakaShrot_Sqlite\BindInt64(Statement, 2, NodeId) + BakaShrot_Sqlite\BindInt64(Statement, 3, MessageId) + ; Static: JsonData outlives the step, the next insert binds it again. + BakaShrot_Sqlite\BindText16(Statement, 4, @JsonData, -1, #BakaShrot_Sqlite_Static) + Result = BakaShrot_Sqlite\Step_(Statement) + If Result <> #BakaShrot_Sqlite_Done + BakaShrot_Storage_Writer\LastError = BakaShrot_Writer_Error() + BakaShrot_Sqlite\Reset(Statement) + ProcedureReturn -1 + EndIf + BakaShrot_Sqlite\Reset(Statement) + ProcedureReturn BakaShrot_Sqlite\Changes(BakaShrot_Storage_Writer\Handle) + CompilerElse + Protected DbId.i = BakaShrot_Storage_Writer\DbId + SetDatabaseLong(DbId, 0, TopicId) + SetDatabaseLong(DbId, 1, NodeId) + SetDatabaseQuad(DbId, 2, MessageId) + SetDatabaseString(DbId, 3, JsonData) + If Not DatabaseUpdate(DbId, PeekS(Statement)) + BakaShrot_Storage_Writer\LastError = DatabaseError() + ProcedureReturn -1 + EndIf + ProcedureReturn AffectedDatabaseRows(DbId) + CompilerEndIf +EndProcedure + + +; The highest message id stored for a topic/node id, 0 if none, -1 on failure. +Procedure.q BakaShrot_Writer_ReadMaxId(TopicId.i, NodeId.i) + Protected MaxId.q = -1 + + CompilerIf #BakaShrot_Storage_RawSqlite + Protected Statement.i = BakaShrot_Storage_Writer\MaxId + BakaShrot_Sqlite\BindInt64(Statement, 1, TopicId) + BakaShrot_Sqlite\BindInt64(Statement, 2, NodeId) + If BakaShrot_Sqlite\Step_(Statement) = #BakaShrot_Sqlite_Row + MaxId = BakaShrot_Sqlite\ColumnInt64(Statement, 0) + Else + BakaShrot_Storage_Writer\LastError = BakaShrot_Writer_Error() + EndIf + BakaShrot_Sqlite\Reset(Statement) + CompilerElse + Protected DbId.i = BakaShrot_Storage_Writer\DbId + SetDatabaseLong(DbId, 0, TopicId) + SetDatabaseLong(DbId, 1, NodeId) + If DatabaseQuery(DbId, PeekS(BakaShrot_Storage_Writer\MaxId)) + If NextDatabaseRow(DbId) + MaxId = GetDatabaseQuad(DbId, 0) + EndIf + FinishDatabaseQuery(DbId) + Else + BakaShrot_Storage_Writer\LastError = DatabaseError() + EndIf + CompilerEndIf + + ProcedureReturn MaxId +EndProcedure + + +; The next message id to hand out for a topic/node id, -1 on failure. +Procedure.q BakaShrot_Writer_NextId(Key.s, TopicId.i, NodeId.i) + Protected MaxId.q + + If FindMapElement(BakaShrot_Storage_Writer\NextIds(), Key) + ProcedureReturn BakaShrot_Storage_Writer\NextIds() + EndIf + + MaxId = BakaShrot_Writer_ReadMaxId(TopicId, NodeId) + If MaxId < 0 + ProcedureReturn -1 + EndIf + BakaShrot_Storage_Writer\NextIds(Key) = MaxId + 1 + ProcedureReturn MaxId + 1 +EndProcedure + + +; --- Opening and closing ----------------------------------------------------- + +CompilerIf #BakaShrot_Storage_RawSqlite + Procedure.i BakaShrot_Writer_LoadSqlite() + With BakaShrot_Sqlite + If \Library + ProcedureReturn #True + EndIf + ; The one PureBasic's SQLite driver already loaded. + \Library = OpenLibrary(#PB_Any, "sqlite3.dll") + If Not \Library + ProcedureReturn #False + EndIf + \Prepare16 = GetFunction(\Library, "sqlite3_prepare16_v2") + \BindInt64 = GetFunction(\Library, "sqlite3_bind_int64") + \BindText16 = GetFunction(\Library, "sqlite3_bind_text16") + \Step_ = GetFunction(\Library, "sqlite3_step") + \Reset = GetFunction(\Library, "sqlite3_reset") + \Finalize = GetFunction(\Library, "sqlite3_finalize") + \ColumnInt64 = GetFunction(\Library, "sqlite3_column_int64") + \Changes = GetFunction(\Library, "sqlite3_changes") + \ErrMsg16 = GetFunction(\Library, "sqlite3_errmsg16") + \DbFilename = GetFunction(\Library, "sqlite3_db_filename") + If Not \Prepare16 Or Not \BindInt64 Or Not \BindText16 Or Not \Step_ Or Not \Reset Or Not \Finalize Or Not \ColumnInt64 Or Not \Changes Or Not \ErrMsg16 Or Not \DbFilename + CloseLibrary(\Library) + \Library = 0 + ProcedureReturn #False + EndIf + EndWith + ProcedureReturn #True + EndProcedure +CompilerEndIf + + +; One PASSIVE checkpoint: copies what it can of the WAL into the database, +; without waiting for the writer nor the readers. Fills *Frames\i with how +; many frames the WAL has, *Left\i with how many it couldn't copy yet. +Procedure BakaShrot_Writer_CheckpointOnce(DbId.i, *Frames.Integer, *Left.Integer) + *Frames\i = 0 + *Left\i = 0 + ; It only runs on the first NextDatabaseRow(). Its row: busy, frames in + ; the WAL, frames checkpointed. + If DatabaseQuery(DbId, "PRAGMA wal_checkpoint(PASSIVE)") + If NextDatabaseRow(DbId) + *Frames\i = GetDatabaseLong(DbId, 1) + *Left\i = *Frames\i - GetDatabaseLong(DbId, 2) + EndIf + FinishDatabaseQuery(DbId) + EndIf +EndProcedure + + +; Every #BakaShrot_Storage_CheckpointInterval ms, copies the WAL into the +; database in PASSIVE rounds, without the write mutex: they copy far faster +; than the pushes write, so each round leaves less behind. Once few enough +; frames are left, finishes under the write mutex, which takes a few ms: a +; checkpoint that's complete when the next transaction starts is what makes +; SQLite start the WAL over, otherwise it grows forever under steady writes. +; A long read can keep it from completing, it's tried again next time. +Procedure BakaShrot_Writer_CheckpointThread(Unused.i) + Protected DbId.i, LastCheckpoint.i, StartTicks.q, LockedTicks.q, Round.i + Protected Frames.Integer, Left.Integer + + DbId = OpenStorageDatabase(BakaShrot_Storage_Writer\DatabasePath) + If Not DbId + PrintN("[Storage] Can't open the database for the checkpoints, the WAL file will keep growing: " + DatabaseError()) + ProcedureReturn + EndIf + + LastCheckpoint = ElapsedMilliseconds() + While Not BakaShrot_Storage_Writer\StopRequested + Delay(50) + If ElapsedMilliseconds() - LastCheckpoint < #BakaShrot_Storage_CheckpointInterval + Continue + EndIf + + StartTicks = BakaShrot_Storage_Ticks() + Round = 0 + Repeat + BakaShrot_Writer_CheckpointOnce(DbId, @Frames, @Left) + Round + 1 + Until Left\i <= #BakaShrot_Storage_CheckpointFinishFrames Or Round >= 4 Or BakaShrot_Storage_Writer\StopRequested + + If Frames\i > 0 And Left\i <= #BakaShrot_Storage_CheckpointFinishFrames + LockMutex(BakaShrot_Storage_WriteMutex) + LockedTicks = BakaShrot_Storage_Ticks() + BakaShrot_Writer_CheckpointOnce(DbId, @Frames, @Left) + BakaShrot_Storage_Writer\CheckpointLockedTicks + BakaShrot_Storage_Ticks() - LockedTicks + UnlockMutex(BakaShrot_Storage_WriteMutex) + EndIf + + BakaShrot_Storage_Writer\WalFrames = Frames\i + BakaShrot_Storage_Writer\CheckpointTicks + BakaShrot_Storage_Ticks() - StartTicks + BakaShrot_Storage_Writer\CheckpointCount + 1 + LastCheckpoint = ElapsedMilliseconds() + Wend + + CloseDatabase(DbId) +EndProcedure + + +; Holding the write mutex. +Procedure BakaShrot_Writer_Release() + With BakaShrot_Storage_Writer + BakaShrot_Writer_Finalize(@\Begin) + BakaShrot_Writer_Finalize(@\Commit) + BakaShrot_Writer_Finalize(@\Rollback) + BakaShrot_Writer_Finalize(@\Insert) + BakaShrot_Writer_Finalize(@\InsertOrIgnore) + BakaShrot_Writer_Finalize(@\MaxId) + If \DbId + CloseDatabase(\DbId) + EndIf + \DbId = 0 + \Handle = 0 + ClearMap(\NextIds()) + EndWith +EndProcedure + + +; Opens the writer on DatabasePath, already set up by SetupStorageDatabase(), +; and starts the checkpoints. Returns #False with the reason in *Error\s. +Procedure.i OpenStorageWriter(DatabasePath.s, *Error.String) + Protected *Main + + LockMutex(BakaShrot_Storage_WriteMutex) + With BakaShrot_Storage_Writer + \DatabasePath = DatabasePath + \DbId = OpenStorageDatabase(DatabasePath) + If Not \DbId + *Error\s = "can't open it: " + DatabaseError() + UnlockMutex(BakaShrot_Storage_WriteMutex) + ProcedureReturn #False + EndIf + + ; The checkpoint thread does them, see the top of this file. This is + ; only the backstop for when it can't keep up. + If Not DatabaseUpdate(\DbId, "PRAGMA wal_autocheckpoint = " + Str(#BakaShrot_Storage_WalBackstopFrames)) Or + Not DatabaseUpdate(\DbId, "PRAGMA journal_size_limit = " + Str(#BakaShrot_Storage_WalSizeLimit)) + *Error\s = "can't set it up: " + DatabaseError() + BakaShrot_Writer_Release() + UnlockMutex(BakaShrot_Storage_WriteMutex) + ProcedureReturn #False + EndIf + + CompilerIf #BakaShrot_Storage_RawSqlite + If Not BakaShrot_Writer_LoadSqlite() + *Error\s = "sqlite3.dll doesn't have the functions needed" + BakaShrot_Writer_Release() + UnlockMutex(BakaShrot_Storage_WriteMutex) + ProcedureReturn #False + EndIf + \Handle = DatabaseID(\DbId) + *Main = UTF8("main") + If Not \Handle Or Not BakaShrot_Sqlite\DbFilename(\Handle, *Main) + FreeMemory(*Main) + *Error\s = "DatabaseID() didn't give a sqlite3 handle" + BakaShrot_Writer_Release() + UnlockMutex(BakaShrot_Storage_WriteMutex) + ProcedureReturn #False + EndIf + FreeMemory(*Main) + CompilerEndIf + + \Begin = BakaShrot_Writer_Prepare("BEGIN IMMEDIATE") + \Commit = BakaShrot_Writer_Prepare("COMMIT") + \Rollback = BakaShrot_Writer_Prepare("ROLLBACK") + \Insert = BakaShrot_Writer_Prepare("INSERT INTO data (topic_id, node_id, message_id, message_data) VALUES (?1, ?2, ?3, ?4)") + \InsertOrIgnore = BakaShrot_Writer_Prepare("INSERT OR IGNORE INTO data (topic_id, node_id, message_id, message_data) VALUES (?1, ?2, ?3, ?4)") + \MaxId = BakaShrot_Writer_Prepare("SELECT COALESCE(MAX(message_id), 0) FROM data WHERE topic_id = ?1 AND node_id = ?2") + If Not \Begin Or Not \Commit Or Not \Rollback Or Not \Insert Or Not \InsertOrIgnore Or Not \MaxId + *Error\s = "can't prepare its statements: " + \LastError + BakaShrot_Writer_Release() + UnlockMutex(BakaShrot_Storage_WriteMutex) + ProcedureReturn #False + EndIf + + \StopRequested = #False + \CheckpointThread = CreateThread(@BakaShrot_Writer_CheckpointThread(), 0) + If Not \CheckpointThread + *Error\s = "can't start the checkpoint thread" + BakaShrot_Writer_Release() + UnlockMutex(BakaShrot_Storage_WriteMutex) + ProcedureReturn #False + EndIf + EndWith + UnlockMutex(BakaShrot_Storage_WriteMutex) + + ProcedureReturn #True +EndProcedure + + +; Stops the checkpoints, checkpoints everything (emptying the WAL file) and +; closes the writer. Once nothing writes anymore: the workers are stopped. +Procedure CloseStorageWriter() + With BakaShrot_Storage_Writer + If \CheckpointThread + \StopRequested = #True + WaitThread(\CheckpointThread) + \CheckpointThread = 0 + EndIf + + LockMutex(BakaShrot_Storage_WriteMutex) + If \DbId + If DatabaseQuery(\DbId, "PRAGMA wal_checkpoint(TRUNCATE)") + NextDatabaseRow(\DbId) + FinishDatabaseQuery(\DbId) + EndIf + EndIf + BakaShrot_Writer_Release() + UnlockMutex(BakaShrot_Storage_WriteMutex) + EndWith +EndProcedure + + +; --- Writes ------------------------------------------------------------------ + +; Holding the write mutex. +Procedure BakaShrot_Writer_LogStats() + Protected Now.i = ElapsedMilliseconds(), Seconds.d, Checkpoints.s + + With BakaShrot_Storage_Writer\Stats + If \LastLog = 0 + \LastLog = Now + ProcedureReturn + EndIf + If Now - \LastLog < #BakaShrot_Storage_StatsInterval + ProcedureReturn + EndIf + + Seconds = (Now - \LastLog) / 1000.0 + If \Groups > 0 + If BakaShrot_Storage_Writer\CheckpointCount > 0 + Checkpoints = ", " + Str(BakaShrot_Storage_Writer\CheckpointCount) + " checkpoints of " + + StrD(BakaShrot_Storage_Writer\CheckpointTicks / BakaShrot_Storage_TicksPerMs / BakaShrot_Storage_Writer\CheckpointCount, 1) + " ms (" + + StrD(BakaShrot_Storage_Writer\CheckpointLockedTicks / BakaShrot_Storage_TicksPerMs / BakaShrot_Storage_Writer\CheckpointCount, 1) + " ms of it holding the writes), " + + Str(BakaShrot_Storage_Writer\WalFrames) + " frames in the WAL" + EndIf + PrintN("[Storage] " + Str(\Pushes) + " pushes in " + StrD(Seconds, 1) + " s (" + StrD(\Pushes / Seconds, 0) + "/s), " + + Str(\Groups) + " transactions of " + StrD(\Pushes / \Groups, 1) + " on average, " + + StrD(\Ticks / BakaShrot_Storage_TicksPerMs / \Groups, 3) + " ms each, " + + StrD(\Ticks / BakaShrot_Storage_TicksPerMs / \Pushes, 3) + " ms per push, writing " + + StrD(100.0 * \Ticks / BakaShrot_Storage_TicksPerMs / (Seconds * 1000.0), 0) + " % of the time" + Checkpoints) + EndIf + \LastLog = Now + \Groups = 0 + \Pushes = 0 + \Ticks = 0 + BakaShrot_Storage_Writer\CheckpointCount = 0 + BakaShrot_Storage_Writer\CheckpointTicks = 0 + BakaShrot_Storage_Writer\CheckpointLockedTicks = 0 + EndWith +EndProcedure + + +; Writes queued pushes in one transaction, filling in their MessageId (-1 and +; Error if that one failed) and setting Done. Holding the write mutex. +Procedure BakaShrot_Writer_WriteJobs(List Jobs.i()) + Protected *Job.BakaShrot_PushJob, InTransaction.i, Key.s, MessageId.q, JsonData.s + + ; If it can't start (another process writing past the busy timeout), + ; every insert still runs, each in its own transaction. + InTransaction = BakaShrot_Writer_Run(BakaShrot_Storage_Writer\Begin) + + ; One failed insert is only that statement's, SQLite keeps the others. + ForEach Jobs() + *Job = Jobs() + Key = Str(*Job\TopicId) + ":" + Str(*Job\NodeId) + MessageId = BakaShrot_Writer_NextId(Key, *Job\TopicId, *Job\NodeId) + JsonData = *Job\JsonData + If MessageId > 0 And BakaShrot_Writer_InsertRow(BakaShrot_Storage_Writer\Insert, *Job\TopicId, *Job\NodeId, MessageId, JsonData) = 1 + *Job\MessageId = MessageId + BakaShrot_Storage_Writer\NextIds(Key) = MessageId + 1 + Else + *Job\MessageId = -1 + *Job\Error = BakaShrot_Storage_Writer\LastError + EndIf + Next + + If InTransaction And Not BakaShrot_Writer_Run(BakaShrot_Storage_Writer\Commit) + ForEach Jobs() + *Job = Jobs() + *Job\MessageId = -1 + *Job\Error = BakaShrot_Storage_Writer\LastError + Next + BakaShrot_Writer_Run(BakaShrot_Storage_Writer\Rollback) + ; Some ids were handed out and rolled back. + ClearMap(BakaShrot_Storage_Writer\NextIds()) + EndIf + + ForEach Jobs() + *Job = Jobs() + *Job\Done = #True + Next +EndProcedure + + +; Inserts one JSON message for a topic_id/node_id pair, with the next +; message_id for that pair, starting at 1, grouped with the other pushes +; arriving meanwhile. Returns the new message's id once committed, or -1 with +; the reason in *Error\s. +Procedure.q InsertNextMessage(TopicId.i, NodeId.i, JsonData.s, *Error.String) + Protected Job.BakaShrot_PushJob + Protected NewList Jobs.i() + Protected StartTicks.q + + Job\TopicId = TopicId + Job\NodeId = NodeId + Job\JsonData = JsonData + Job\MessageId = -1 + + LockMutex(BakaShrot_Storage_QueueMutex) + AddElement(BakaShrot_Storage_Queue()) + BakaShrot_Storage_Queue() = @Job + UnlockMutex(BakaShrot_Storage_QueueMutex) + + ; Whoever gets the mutex writes everything queued so far, this one's + ; included unless an earlier holder already did. The queue is first in, + ; first out, so a capped group still gets to it eventually. + LockMutex(BakaShrot_Storage_WriteMutex) + If Not BakaShrot_Storage_Writer\DbId + ; Closed: the workers are stopping. + LockMutex(BakaShrot_Storage_QueueMutex) + ForEach BakaShrot_Storage_Queue() + If BakaShrot_Storage_Queue() = @Job + DeleteElement(BakaShrot_Storage_Queue()) + Break + EndIf + Next + UnlockMutex(BakaShrot_Storage_QueueMutex) + UnlockMutex(BakaShrot_Storage_WriteMutex) + *Error\s = "the storage writer isn't open" + ProcedureReturn -1 + EndIf + + While Not Job\Done + ClearList(Jobs()) + LockMutex(BakaShrot_Storage_QueueMutex) + ForEach BakaShrot_Storage_Queue() + If ListSize(Jobs()) >= #BakaShrot_Storage_MaxGroupSize + Break + EndIf + AddElement(Jobs()) + Jobs() = BakaShrot_Storage_Queue() + DeleteElement(BakaShrot_Storage_Queue()) + Next + UnlockMutex(BakaShrot_Storage_QueueMutex) + + StartTicks = BakaShrot_Storage_Ticks() + BakaShrot_Writer_WriteJobs(Jobs()) + With BakaShrot_Storage_Writer\Stats + \Ticks + BakaShrot_Storage_Ticks() - StartTicks + \Groups + 1 + \Pushes + ListSize(Jobs()) + EndWith + Wend + BakaShrot_Writer_LogStats() + UnlockMutex(BakaShrot_Storage_WriteMutex) + + If Job\MessageId < 1 + *Error\s = Job\Error + EndIf + ProcedureReturn Job\MessageId +EndProcedure + + +; Stores a batch of messages replicated from a peer, all of one topic/node +; id, under the ids they have on their origin, in a single transaction: +; either all of them are stored, or none. An id that's already stored is kept +; as is, the new one is dropped, even if it differs (Design/ReplicationIssues.md). +; Returns #False with the reason in *Error\s, the transaction is rolled back. +Procedure.i InsertReplicatedMessages(TopicId.i, NodeId.i, List Messages.BakaShrot_ReplicatedMessage(), *Error.String) + Protected Stored.i, Inserted.i, Key.s, JsonData.s + + Key = Str(TopicId) + ":" + Str(NodeId) + + LockMutex(BakaShrot_Storage_WriteMutex) + If Not BakaShrot_Storage_Writer\DbId + UnlockMutex(BakaShrot_Storage_WriteMutex) + *Error\s = "the storage writer isn't open" + ProcedureReturn #False + EndIf + + ; IMMEDIATE takes the write lock up front, instead of failing midway if + ; another process started writing first. + Stored = BakaShrot_Writer_Run(BakaShrot_Storage_Writer\Begin) + If Stored + ForEach Messages() + JsonData = Messages()\JsonData + Inserted = BakaShrot_Writer_InsertRow(BakaShrot_Storage_Writer\InsertOrIgnore, TopicId, NodeId, Messages()\MessageId, JsonData) + If Inserted < 0 + Stored = #False + Break + EndIf + ; A pair pushed to here too (drift): the next push goes after it. + If Inserted = 1 And FindMapElement(BakaShrot_Storage_Writer\NextIds(), Key) + If Messages()\MessageId + 1 > BakaShrot_Storage_Writer\NextIds() + BakaShrot_Storage_Writer\NextIds() = Messages()\MessageId + 1 + EndIf + EndIf + Next + + If Stored And Not BakaShrot_Writer_Run(BakaShrot_Storage_Writer\Commit) + Stored = #False + EndIf + If Not Stored + *Error\s = BakaShrot_Storage_Writer\LastError + BakaShrot_Writer_Run(BakaShrot_Storage_Writer\Rollback) + ClearMap(BakaShrot_Storage_Writer\NextIds()) + EndIf + Else + *Error\s = BakaShrot_Storage_Writer\LastError + EndIf + + UnlockMutex(BakaShrot_Storage_WriteMutex) + ProcedureReturn Stored +EndProcedure + + +; Adds a row to the "topics" or "nodes" table (Table), for Id, named Name +; (its id in digits if it has none), Origin "peer" or "id", see +; Server/Storage/Names.pbi. A row already there for that id is kept. +; Returns #False with the reason in *Error\s. +Procedure.i RegisterStorageName(Table.s, Id.i, Name.s, Origin.s, *Error.String) + Protected DbId.i, Stored.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 #False + EndIf + + SetDatabaseLong(DbId, 0, Id) + SetDatabaseString(DbId, 1, Name) + SetDatabaseString(DbId, 2, Origin) + Stored = DatabaseUpdate(DbId, "INSERT OR IGNORE INTO " + Table + " VALUES (?, ?, ?)") + If Not Stored + *Error\s = DatabaseError() + EndIf + + UnlockMutex(BakaShrot_Storage_WriteMutex) + ProcedureReturn Stored +EndProcedure diff --git a/Core/Storage/db_schema_v0.dbml b/Server/Storage/db_schema_v0.dbml similarity index 100% rename from Core/Storage/db_schema_v0.dbml rename to Server/Storage/db_schema_v0.dbml diff --git a/Core/Storage/db_schema_v1.dbml b/Server/Storage/db_schema_v1.dbml similarity index 100% rename from Core/Storage/db_schema_v1.dbml rename to Server/Storage/db_schema_v1.dbml diff --git a/Server/Storage/db_schema_v2.dbml b/Server/Storage/db_schema_v2.dbml new file mode 100644 index 0000000..7ffbebf --- /dev/null +++ b/Server/Storage/db_schema_v2.dbml @@ -0,0 +1,45 @@ +// Changes from v1, on "data" only: +// - UNIQUE (group_id, node_id, message_id), so a message id can't be stored twice. +// Its index also serves (group_id, node_id) lookups, replacing v1's index on them. +// - is_json, set by SQLite on insert, for JSON queries on message_data. +// +// Needs SQLite 3.38+ with its JSON functions (json_valid, ->>), see Storage.pbi. + +table archives { + // UTC Unix Timestamp after which this archived message should be deleted. + delete_by integer [not null] + + message_data text [not null] +} + +table data { + group_id integer [not null] + node_id integer [not null] + message_id integer [not null] + message_data text [not null] + + // 1 if message_data is well-formed JSON, 0 otherwise. + // Can't be written, SQLite computes it on insert and stores it. + is_json integer [not null, note: 'GENERATED ALWAYS AS (json_valid(message_data)) STORED'] + + indexes { + (group_id, node_id, message_id) [unique] + message_id + } +} + +// Create it, but we'll implement this later. +table attachements { + group_id integer [not null] + node_id integer [not null] + message_id integer [not null] + attachement_data blob [not null] + + indexes { + (group_id, node_id) + message_id + } +} + +// Note, ignore it +// msg_type TEXT GENERATED ALWAYS AS (data ->> '$.messageData.MsgType') VIRTUAL diff --git a/Server/Storage/db_schema_v3.dbml b/Server/Storage/db_schema_v3.dbml new file mode 100644 index 0000000..ff48129 --- /dev/null +++ b/Server/Storage/db_schema_v3.dbml @@ -0,0 +1,62 @@ +// Changes from v2: +// - node_heads, the highest message id of every group/node id, kept by the +// trg_data_node_heads trigger on every insert into data. The sync state +// (GetSyncState()) reads it instead of a GROUP BY over every message. +// Filled from data when it's created on an existing database. +// Nothing deletes from data yet, whatever does must update it too. +// +// Needs SQLite 3.38+ with its JSON functions (json_valid, ->>), see Storage.pbi. +// The database is in WAL mode, see Storage.pbi and Writer.pbi. + +table archives { + // UTC Unix Timestamp after which this archived message should be deleted. + delete_by integer [not null] + + message_data text [not null] +} + +table data { + group_id integer [not null] + node_id integer [not null] + message_id integer [not null] + message_data text [not null] + + // 1 if message_data is well-formed JSON, 0 otherwise. + // Can't be written, SQLite computes it on insert and stores it. + is_json integer [not null, note: 'GENERATED ALWAYS AS (json_valid(message_data)) STORED'] + + indexes { + (group_id, node_id, message_id) [unique] + message_id + } +} + +// One row per group/node id that has messages. +// AFTER INSERT ON data: INSERT ... ON CONFLICT DO UPDATE SET +// max_message_id = MAX(max_message_id, excluded.max_message_id) +// Only fires for rows actually inserted (not the ones INSERT OR IGNORE drops). +table node_heads [note: 'WITHOUT ROWID'] { + group_id integer [not null] + node_id integer [not null] + max_message_id integer [not null] + + indexes { + (group_id, node_id) [pk] + } +} + +// Create it, but we'll implement this later. +table attachements { + group_id integer [not null] + node_id integer [not null] + message_id integer [not null] + attachement_data blob [not null] + + indexes { + (group_id, node_id) + message_id + } +} + +// Note, ignore it +// msg_type TEXT GENERATED ALWAYS AS (data ->> '$.messageData.MsgType') VIRTUAL diff --git a/Server/Storage/db_schema_v4.dbml b/Server/Storage/db_schema_v4.dbml new file mode 100644 index 0000000..30bbd39 --- /dev/null +++ b/Server/Storage/db_schema_v4.dbml @@ -0,0 +1,61 @@ +// Changes from v3: +// - group_id is now topic_id, in every table. MigrateStorageTopicIds() +// (Storage.pbi) renames the columns of an older database on start, and +// the trigger and the attachements index are made again with the new +// names (idx_attachements_group_node -> idx_attachements_topic_node). +// +// Needs SQLite 3.38+ with its JSON functions (json_valid, ->>), see Storage.pbi. +// The database is in WAL mode, see Storage.pbi and Writer.pbi. + +table archives { + // UTC Unix Timestamp after which this archived message should be deleted. + delete_by integer [not null] + + message_data text [not null] +} + +table data { + topic_id integer [not null] + node_id integer [not null] + message_id integer [not null] + message_data text [not null] + + // 1 if message_data is well-formed JSON, 0 otherwise. + // Can't be written, SQLite computes it on insert and stores it. + is_json integer [not null, note: 'GENERATED ALWAYS AS (json_valid(message_data)) STORED'] + + indexes { + (topic_id, node_id, message_id) [unique] + message_id + } +} + +// One row per topic/node id that has messages. +// AFTER INSERT ON data: INSERT ... ON CONFLICT DO UPDATE SET +// max_message_id = MAX(max_message_id, excluded.max_message_id) +// Only fires for rows actually inserted (not the ones INSERT OR IGNORE drops). +table node_heads [note: 'WITHOUT ROWID'] { + topic_id integer [not null] + node_id integer [not null] + max_message_id integer [not null] + + indexes { + (topic_id, node_id) [pk] + } +} + +// Create it, but we'll implement this later. +table attachements { + topic_id integer [not null] + node_id integer [not null] + message_id integer [not null] + attachement_data blob [not null] + + indexes { + (topic_id, node_id) + message_id + } +} + +// Note, ignore it +// msg_type TEXT GENERATED ALWAYS AS (data ->> '$.messageData.MsgType') VIRTUAL diff --git a/Server/Storage/db_schema_v5.dbml b/Server/Storage/db_schema_v5.dbml new file mode 100644 index 0000000..458eb5c --- /dev/null +++ b/Server/Storage/db_schema_v5.dbml @@ -0,0 +1,88 @@ +// Changes from v4: +// - topics and nodes: every topic and node id in data, with its name (its +// id in digits if it has none) and where that comes from. Kept by +// Server/Storage/Names.pbi from the config. Only names on both servers +// replicate. Names are shared between servers, ids aren't. +// - messages: a view of data with the names, for queries by name. +// - No foreign keys from data to them (Notes.md): an unknown id would fail +// a whole replicated batch. +// +// Needs SQLite 3.38+ with its JSON functions (json_valid, ->>), see Storage.pbi. +// The database is in WAL mode, see Storage.pbi and Writer.pbi. + +table archives { + // UTC Unix Timestamp after which this archived message should be deleted. + delete_by integer [not null] + + message_data text [not null] +} + +table data { + topic_id integer [not null] + node_id integer [not null] + message_id integer [not null] + message_data text [not null] + + // 1 if message_data is well-formed JSON, 0 otherwise. + // Can't be written, SQLite computes it on insert and stores it. + is_json integer [not null, note: 'GENERATED ALWAYS AS (json_valid(message_data)) STORED'] + + indexes { + (topic_id, node_id, message_id) [unique] + message_id + } +} + +// One row per topic/node id that has messages. +// AFTER INSERT ON data: INSERT ... ON CONFLICT DO UPDATE SET +// max_message_id = MAX(max_message_id, excluded.max_message_id) +// Only fires for rows actually inserted (not the ones INSERT OR IGNORE drops). +table node_heads [note: 'WITHOUT ROWID'] { + topic_id integer [not null] + node_id integer [not null] + max_message_id integer [not null] + + indexes { + (topic_id, node_id) [pk] + } +} + +// Create it, but we'll implement this later. +table attachements { + topic_id integer [not null] + node_id integer [not null] + message_id integer [not null] + attachement_data blob [not null] + + indexes { + (topic_id, node_id) + message_id + } +} + +// origin: "config" (named in [BakaShrot.Topics]), "id" (unnamed, name is +// the id in digits). +table topics { + topic_id integer [pk] + name text [not null, unique, note: 'COLLATE NOCASE'] + origin text [not null] +} + +// origin: "config" (named in [BakaShrot.Nodes]), "id" (unnamed), "peer" +// (only in databases from the short-lived version that added peer nodes). +table nodes { + node_id integer [pk] + name text [not null, unique, note: 'COLLATE NOCASE'] + origin text [not null] +} + +// View messages: +// SELECT t.name AS topic, n.name AS node, d.message_id, d.message_data, +// d.is_json, d.topic_id, d.node_id +// FROM data d JOIN topics t ON t.topic_id = d.topic_id +// JOIN nodes n ON n.node_id = d.node_id +// WHERE topic = ... AND node = ... goes through the name indexes, then +// data's (topic_id, node_id, message_id) one. + +// Note, ignore it +// msg_type TEXT GENERATED ALWAYS AS (data ->> '$.messageData.MsgType') VIRTUAL diff --git a/Tests/Bench/Bench-Replication.ps1 b/Tests/Bench/Bench-Replication.ps1 new file mode 100644 index 0000000..d6c79ee --- /dev/null +++ b/Tests/Bench/Bench-Replication.ps1 @@ -0,0 +1,658 @@ +# ============================================================================ +# BakaShrot replication benchmark +# +# Runs several servers linked as peers on localhost (by default 4 in a Y: one +# hub linked to 3 leaves), each with its own nodes pushing to it, and +# measures, stage by stage: +# - the push path: achieved vs offered rate, latency, failures +# - replication: lag on every server while pushing, whether it keeps up +# (trough slope, see Bench_TroughSlope() in BenchClient.pb), and how long +# it takes to drain once the pushes stop +# - every server's CPU and RAM, and its database's size +# - a query suite (queries.txt) after every stage, as the data grows +# +# Three parts: +# 1. Ramp: from an empty database, stages of -Ramp ("NodesxRate", Rate per +# node in msg/s, 0 = as fast as the server answers), to find where the +# push path and the replication saturate. +# 2. Scale: seeds every database up to each of -SeedTotals rows (identical +# on every server, see BenchSeed.pb), then runs -SteadyStage and the +# query suite at that size: how check-ins and queries hold up with +# lots of data. +# 3. Mixed: -MixedStage with queries_load.txt running in a loop against +# the hub meanwhile: reads under write load, and writes under reads. +# +# Results go into Build\Bench\runs\\: configs, per-stage samples +# (CSV, one row per sample), summaries (JSON), and report.md / results.json +# for the whole run. +# The databases and server logs go into -DataDir\\ instead, out of +# the repo: every push rewrites them, and file watchers on the repo (git +# caches, editors) otherwise burn a core or two reacting to it, skewing the +# CPU numbers. The databases are deleted at the end, unless -KeepData. +# +# Usage: +# powershell -ExecutionPolicy Bypass -File Tests\Bench\Bench-Replication.ps1 +# ... -Ramp "5x20,10x50" -SeedTotals @() -PushSeconds 10 quick run +# ... -Topology Mesh -PeerSyncInterval 1 variations +# ... -Names Wildcard each server only names its own nodes, and +# takes the others' by AcceptNodes = n* +# ... -Parts Ramp only part 1 +# Keep -PushSeconds at 6+ times PeerSyncInterval for the trough slope to mean +# something. +# +# ... -Compiler "C:\Program Files\PureBasic_640\Compilers\pbcompilerc.exe" ` +# -CompilerFlags "/OPTIMIZER" PB 6.40, C backend +# +# Needs: PureBasic 5.73 x64 (found by itself, or -Compiler), libsodium +# extracted in Libs\libsodium\x64 (see Build.ps1), and a sqlite3.dll with +# the JSON functions (3.38+): Libs\sqlite\x64\sqlite3.dll by default, or +# -SqliteDll. +# Everything runs on one machine: the load generator competes with the +# servers for the CPU, its own CPU use is in the report. +# ============================================================================ + +param( + [ValidateSet("Y", "Chain", "Mesh")] + [string]$Topology = "Y", + [ValidateSet("Declared", "Wildcard")] + [string]$Names = "Declared", + [int]$ServerCount = 4, + [int]$MaxNodesPerServer = 10, + [int]$MessageSize = 200, + [int]$PushSeconds = 30, + [int]$PeerSyncInterval = 5, + [int]$PeerBatchSize = 100, + [int]$PortBase = 13001, + [string]$Ramp = "5x5,5x20,5x50,5x100,5x0,10x20,10x50,10x100,10x0", + [int[]]$SeedTotals = @(250000, 1000000), + [string]$SteadyStage = "10x10", + [string]$MixedStage = "10x10", + + [string]$Parts = "Ramp,Scale,Mixed", + [int]$QueryRepeats = 3, + [int]$DrainTimeout = 180, + [string]$Compiler = "", + [string]$CompilerFlags = "", + [string]$SqliteDll = "", + [string]$DataDir = (Join-Path ([IO.Path]::GetTempPath()) "BakaShrot-Bench"), + [switch]$KeepData, + [switch]$SkipBuild +) + +$ErrorActionPreference = "Stop" + +# "Ramp,Scale" or "Ramp", "Scale", from -File or -Command alike. +$PartList = @($Parts -split "[, ]" | ForEach-Object { $_.Trim() } | Where-Object { $_ }) +foreach ($Part in $PartList) { if ($Part -notin @("Ramp", "Scale", "Mixed")) { throw "Unknown part $Part, use Ramp, Scale and/or Mixed" } } + +$Stamp = Get-Date -Format "yyyyMMdd-HHmmss" +$Root = Resolve-Path (Join-Path $PSScriptRoot "..\..") +$BenchDir = $PSScriptRoot +$OutDir = Join-Path $Root "Build\Bench" +$RunDir = Join-Path $OutDir "runs\$Stamp" +$RunData = Join-Path $DataDir $Stamp +$LogDir = Join-Path $RunData "logs" +$TopicId = 1 + + +# --- Build ------------------------------------------------------------------ + +function Find-Compiler { + if ($Compiler) { return $Compiler } + foreach ($Candidate in @("C:\Program Files\PureBasic_573\Compilers\pbcompiler.exe", + "C:\Program Files\PureBasic573\Compilers\pbcompiler.exe")) { + if (Test-Path $Candidate) { return $Candidate } + } + throw "PureBasic 5.73 x64 not found, pass -Compiler" +} + +function Copy-Dlls { + New-Item -ItemType Directory -Force $OutDir | Out-Null + + $Sodium = Join-Path $Root "Libs\libsodium\x64\libsodium.dll" + if (-not (Test-Path $Sodium)) { throw "Missing $Sodium, run Build.ps1 once to extract it" } + Copy-Item $Sodium $OutDir -Force + + $Sqlite = $SqliteDll + if (-not $Sqlite) { $Sqlite = Join-Path $Root "Libs\sqlite\x64\sqlite3.dll" } + if (-not (Test-Path $Sqlite)) { throw "Missing $Sqlite, run Build.ps1 once to extract it, or pass -SqliteDll" } + Copy-Item $Sqlite (Join-Path $OutDir "sqlite3.dll") -Force + Write-Host "Using SQLite $((Get-Item $Sqlite).VersionInfo.ProductVersion) from $Sqlite" +} + +$script:CompilerName = "(not rebuilt, -SkipBuild)" + +function Invoke-Build { + $Pb = Find-Compiler + New-Item -ItemType Directory -Force $OutDir | Out-Null + + # "PureBasic 6.40 - C Backend (Windows - x64) - (c) ...", 5.73 takes /EXE, + # 6.x /OUTPUT. + $script:CompilerName = ((& $Pb /VERSION) | Select-Object -First 1) -replace " - \(c\).*$", "" + $OutputFlag = if ($script:CompilerName -match "PureBasic 5\.") { "/EXE" } else { "/OUTPUT" } + $Extra = @($CompilerFlags -split " " | Where-Object { $_ }) + if ($Extra.Count -gt 0) { $script:CompilerName += " " + ($Extra -join " ") } + Write-Host "Compiler: $($script:CompilerName)" + + foreach ($Item in @( + @("Tests\Bench\BenchServer.pb", "BenchServer.exe", @("/CONSOLE", "/THREAD")), + @("Tests\Bench\BenchClient.pb", "BenchClient.exe", @("/CONSOLE", "/THREAD")), + @("Tests\Bench\BenchSeed.pb", "BenchSeed.exe", @("/CONSOLE")), + @("Tools\KeyGen\KeyGen.pb", "KeyGen.exe", @("/CONSOLE")))) { + Write-Host "Compiling $($Item[0])" + $Flags = $Item[2] + $Extra + & $Pb (Join-Path $Root $Item[0]) @Flags /QUIET $OutputFlag (Join-Path $OutDir $Item[1]) + if ($LASTEXITCODE -ne 0) { throw "Failed to compile $($Item[0])" } + } +} + +function New-KeyPair { + $Lines = & (Join-Path $OutDir "KeyGen.exe") + if ($LASTEXITCODE -ne 0) { throw "KeyGen failed: $Lines" } + return @{ + PrivateKey = $Lines[0] -replace "^PrivateKey = ", "" + PublicKey = $Lines[1] -replace "^PublicKey = ", "" + } +} + + +# --- Topology and configs ----------------------------------------------------- + +function Get-Edges { + $Edges = @() + switch ($Topology) { + "Y" { for ($i = 1; $i -lt $ServerCount; $i++) { $Edges += , @(0, $i) } } + "Chain" { for ($i = 0; $i -lt $ServerCount - 1; $i++) { $Edges += , @($i, ($i + 1)) } } + "Mesh" { for ($i = 0; $i -lt $ServerCount; $i++) { for ($j = $i + 1; $j -lt $ServerCount; $j++) { $Edges += , @($i, $j) } } } + } + return , $Edges +} + +function New-Servers { + $Servers = @() + for ($i = 0; $i -lt $ServerCount; $i++) { + if ($Topology -eq "Y") { + if ($i -eq 0) { $Name = "hub" } else { $Name = "leaf$i" } + } else { + $Name = "s$($i + 1)" + } + $Keys = New-KeyPair + $Servers += [pscustomobject]@{ + Index = $i + Name = $Name + NodeId = $i + 1 + Port = $PortBase + $i + PrivateKey = $Keys.PrivateKey + PublicKey = $Keys.PublicKey + DatabasePath = Join-Path $RunData "$Name.sqlite" + ConfigPath = Join-Path $RunDir "$Name.ini" + StopFile = Join-Path $RunData "$Name.stop" + FirstNode = ($i + 1) * 100 + 1 + MonitorNode = 900 + $i + 1 + QueryNode = 950 + $i + 1 + Peers = @() + Process = $null + } + } + foreach ($Edge in (Get-Edges)) { + $Servers[$Edge[0]].Peers += $Edge[1] + $Servers[$Edge[1]].Peers += $Edge[0] + } + return $Servers +} + +function Write-ServerConfig($Server, $Servers, $ClientKeys) { + $LastNode = $Server.FirstNode + $MaxNodesPerServer - 1 + $Identities = (@($Server.FirstNode..$LastNode) + @($Server.MonitorNode, $Server.QueryNode) | ForEach-Object { "${TopicId}:$_" }) -join ";" + + # Only named topics and nodes replicate, and they must be named on both + # ends (Declared): every server names every node of every server, with + # the same ids. Wildcard: each server only names its own, the peers take + # them by AcceptNodes = n*, and give them ids of their own. The servers' + # own nodes are named everywhere either way: a peer authenticates by + # name, the others must know it. + $NodeNames = @() + foreach ($Other in $Servers) { + $NodeNames += "n$($Other.NodeId) = $($Other.NodeId)" + if ($Names -eq "Wildcard" -and $Other -ne $Server) { continue } + $OtherLast = $Other.FirstNode + $MaxNodesPerServer - 1 + foreach ($Id in (@($Other.FirstNode..$OtherLast) + @($Other.MonitorNode, $Other.QueryNode))) { + $NodeNames += "n$Id = $Id" + } + } + + $Text = @" +[BakaShrot] +PrivateKey = $($Server.PrivateKey) +Topic = $TopicId +Node = $($Server.NodeId) + +[BakaShrot.Topics] +bench = $TopicId + +[BakaShrot.Nodes] +$($NodeNames -join "`r`n") + +[BakaShrot.Server] +Host = 127.0.0.1 +Port = $($Server.Port) +ReplicatingTopics = $TopicId +DatabasePath = $($Server.DatabasePath) +PeerRetryDelay = 2 +PeerSyncInterval = $PeerSyncInterval +PeerBatchSize = $PeerBatchSize + +[BakaShrot.Client.bench] +PublicKeys = $($ClientKeys.PublicKey) +Identities = $Identities +AllowRead = 1 +AllowWrite = 1 +AllowQuery = 1 + +"@ + foreach ($PeerIndex in $Server.Peers) { + $Peer = $Servers[$PeerIndex] + $Text += @" +[BakaShrot.Peer.$($Peer.Name)] +Host = 127.0.0.1 +Port = $($Peer.Port) +Topic = $TopicId +Node = $($Peer.NodeId) +PublicKey = $($Peer.PublicKey) +$(if ($Names -eq "Wildcard") { "AcceptNodes = n*" }) + +[BakaShrot.Client.$($Peer.Name)] +PublicKeys = $($Peer.PublicKey) +Identities = ${TopicId}:$($Peer.NodeId) +AllowRead = 0 +AllowWrite = 0 +AllowQuery = 0 + +"@ + } + Set-Content -Path $Server.ConfigPath -Value $Text -Encoding Ascii +} + + +# --- Servers ---------------------------------------------------------------- + +$script:StartCount = 0 + +function Test-Port($Port) { + $Client = New-Object System.Net.Sockets.TcpClient + try { + $Async = $Client.BeginConnect("127.0.0.1", $Port, $null, $null) + if ($Async.AsyncWaitHandle.WaitOne(200) -and $Client.Connected) { return $true } + return $false + } catch { + return $false + } finally { + $Client.Close() + } +} + +function Start-Servers($Servers) { + $script:StartCount++ + foreach ($Server in $Servers) { + Remove-Item $Server.StopFile -ErrorAction SilentlyContinue + $Log = Join-Path $LogDir "$($Server.Name)-$($script:StartCount).log" + $Server.Process = Start-Process -FilePath (Join-Path $OutDir "BenchServer.exe") ` + -ArgumentList "`"$($Server.ConfigPath)`"", "`"$($Server.StopFile)`"" ` + -WorkingDirectory $OutDir -NoNewWindow -PassThru ` + -RedirectStandardOutput $Log -RedirectStandardError "$Log.err" + } + foreach ($Server in $Servers) { + $Deadline = (Get-Date).AddSeconds(15) + while (-not (Test-Port $Server.Port)) { + if ($Server.Process.HasExited) { throw "$($Server.Name) exited, see its log in $LogDir" } + if ((Get-Date) -gt $Deadline) { throw "$($Server.Name) isn't listening on $($Server.Port)" } + Start-Sleep -Milliseconds 100 + } + } + # Let the peers link (they retry every 2 s) and run their first check-in. + Start-Sleep -Seconds 4 + Write-Host "Servers up: $(($Servers | ForEach-Object { "$($_.Name)=pid $($_.Process.Id)" }) -join ', ')" +} + +function Stop-Servers($Servers) { + foreach ($Server in $Servers) { + if ($Server.Process -and -not $Server.Process.HasExited) { + Set-Content -Path $Server.StopFile -Value "stop" + } + } + foreach ($Server in $Servers) { + if ($Server.Process) { + if (-not $Server.Process.WaitForExit(30000)) { + Write-Warning "$($Server.Name) didn't stop, killing it" + $Server.Process.Kill() + } + $Server.Process = $null + } + } +} + + +# --- Stages ----------------------------------------------------------------- + +function ConvertTo-Stage($Spec) { + $Fields = $Spec.Trim().ToLower().Split("x") + return [pscustomobject]@{ Nodes = [int]$Fields[0]; Rate = [double]$Fields[1] } +} + +function Write-Plan($Path, $Servers, $ClientKeys, $Stage, $Name, $QueryFile, $QueryLoad) { + $Text = @" +[Bench] +PrivateKey = $($ClientKeys.PrivateKey) +PublicKey = $($ClientKeys.PublicKey) +TopicId = $TopicId +ServerCount = $($Servers.Count) +PushSeconds = $PushSeconds +Rate = $($Stage.Rate) +MessageSize = $MessageSize +SampleMs = 1000 +DrainSampleMs = 250 +DrainTimeout = $DrainTimeout +PeerSyncInterval = $PeerSyncInterval +SamplesCsv = $(Join-Path $RunDir "$Name.samples.csv") +SummaryOut = $(Join-Path $RunDir "$Name.summary.json") +QueryFile = $QueryFile +QueryRepeats = $QueryRepeats +QueryOut = $(Join-Path $RunDir "$Name.queries.json") + +"@ + foreach ($Server in $Servers) { + $ProcId = 0 + if ($Server.Process) { $ProcId = $Server.Process.Id } + # The query suite runs on the hub and the first leaf, the query load + # only on the hub. + $Text += @" +[Server$($Server.Index + 1)] +Name = $($Server.Name) +Host = 127.0.0.1 +Port = $($Server.Port) +PublicKey = $($Server.PublicKey) +Pid = $ProcId +DatabasePath = $($Server.DatabasePath) +FirstNode = $($Server.FirstNode) +MaxNodes = $MaxNodesPerServer +NodeCount = $($Stage.Nodes) +MonitorNode = $($Server.MonitorNode) +QueryNode = $($Server.QueryNode) +QueryLoad = $([int]($QueryLoad -and $Server.Index -eq 0)) +Query = $([int]($Server.Index -le 1)) + +"@ + } + Set-Content -Path $Path -Value $Text -Encoding Ascii +} + +function Invoke-BenchClient($Mode, $Plan) { + & (Join-Path $OutDir "BenchClient.exe") $Mode $Plan | ForEach-Object { Write-Host " $_" } + if ($LASTEXITCODE -ne 0) { throw "BenchClient $Mode failed" } +} + +$script:Results = @() +$script:QueryResults = @() + +function Invoke-Stage($Part, $Name, $Stage, $Servers, $ClientKeys, [switch]$QueryLoad) { + $Plan = Join-Path $RunDir "$Name.plan.ini" + $LoadFile = "" + if ($QueryLoad) { $LoadFile = Join-Path $BenchDir "queries_load.txt" } + Write-Plan $Plan $Servers $ClientKeys $Stage $Name $LoadFile $QueryLoad + + $RateText = if ($Stage.Rate -gt 0) { "$($Stage.Rate) msg/s" } else { "max" } + Write-Host "" + Write-Host "=== $Name : $($Stage.Nodes) nodes/server x $RateText, $PushSeconds s ===" -ForegroundColor Cyan + # Other processes busy meanwhile (antivirus scanning the databases...), + # tick-based, only good enough to spot the big ones. + $Before = @{} + Get-Process | ForEach-Object { $Before[$_.Id] = $_.CPU } + $StartTime = Get-Date + Invoke-BenchClient "run" $Plan + $Seconds = ((Get-Date) - $StartTime).TotalSeconds + $Others = Get-Process | Where-Object { $_.Name -notin @("BenchServer", "BenchClient", "Idle") -and $null -ne $_.CPU } | ForEach-Object { + $Previous = 0 + if ($Before.ContainsKey($_.Id)) { $Previous = $Before[$_.Id] } + [pscustomobject]@{ Name = $_.Name; Percent = 100 * ($_.CPU - $Previous) / $Seconds } + } | Sort-Object Percent -Descending | Select-Object -First 3 + $Summary = Get-Content (Join-Path $RunDir "$Name.summary.json") -Raw | ConvertFrom-Json + $Summary | Add-Member -NotePropertyName OtherProcesses -NotePropertyValue (($Others | Where-Object Percent -ge 5 | ForEach-Object { "$($_.Name) $(Format-Num $_.Percent)" }) -join ", ") + $Summary | Add-Member -NotePropertyName Stage -NotePropertyValue $Name + $Summary | Add-Member -NotePropertyName Part -NotePropertyValue $Part + $Summary | Add-Member -NotePropertyName NodesPerServer -NotePropertyValue $Stage.Nodes + $script:Results += $Summary + + # The query suite, on the idle servers. + Write-Plan $Plan $Servers $ClientKeys $Stage $Name (Join-Path $BenchDir "queries.txt") $false + Invoke-BenchClient "query" $Plan + $Rows = ($Summary.Servers | Measure-Object -Property Rows -Maximum).Maximum + foreach ($Query in (Get-Content (Join-Path $RunDir "$Name.queries.json") -Raw | ConvertFrom-Json)) { + $Query | Add-Member -NotePropertyName Stage -NotePropertyValue $Name + $Query | Add-Member -NotePropertyName DataRows -NotePropertyValue $Rows + $script:QueryResults += $Query + } + return $Summary +} + +function Invoke-Seed($Servers, $TargetRows, $CurrentRows) { + $Nodes = $Servers.Count * $MaxNodesPerServer + $PerNode = [math]::Ceiling(($TargetRows - $CurrentRows) / $Nodes) + if ($PerNode -le 0) { return } + $Spec = ($Servers | ForEach-Object { "$($_.FirstNode)-$($_.FirstNode + $MaxNodesPerServer - 1)" }) -join "," + Write-Host "" + Write-Host "=== Seeding to ~$TargetRows rows per server ($PerNode more per node, in every database) ===" -ForegroundColor Cyan + Stop-Servers $Servers + $Dbs = $Servers | ForEach-Object { $_.DatabasePath } + & (Join-Path $OutDir "BenchSeed.exe") $TopicId $Spec $PerNode $MessageSize @Dbs | ForEach-Object { Write-Host " $_" } + if ($LASTEXITCODE -ne 0) { throw "BenchSeed failed" } + Start-Servers $Servers +} + + +# --- Report ----------------------------------------------------------------- + +function Format-Num($Value, $Decimals = 0) { + return ([double]$Value).ToString("N$Decimals", [Globalization.CultureInfo]::InvariantCulture) +} + +function Get-Verdict($Summary) { + $Notes = @() + if ($Summary.Rate -gt 0 -and $Summary.PushRate -lt 0.9 * $Summary.OfferedRate) { $Notes += "push saturated" } + if ($Summary.Failed -gt 0) { $Notes += "$($Summary.Failed) failed pushes" } + # The trough slope is too noisy for a verdict (check-ins drift against the + # windows), the lag in seconds of pushes isn't: keeping up means about + # two check-ins' worth at most, through the hub. + $MaxLagSeconds = ($Summary.Servers | Measure-Object -Property LagMaxSeconds -Maximum).Maximum + if ($MaxLagSeconds -gt 2 * $PeerSyncInterval + 2) { $Notes += "replication lagging" } + if (-not $Summary.Drained) { $Notes += "NOT drained" } + elseif ($Summary.DrainSeconds -gt 2 * $PeerSyncInterval + 5) { $Notes += "slow drain" } + if ($Notes.Count -eq 0) { return "ok" } + return $Notes -join ", " +} + +function Get-LogIssues($Servers) { + $Issues = @() + foreach ($Server in $Servers) { + $Logs = Get-ChildItem $LogDir -Filter "$($Server.Name)-*.log" + $Counts = [ordered]@{} + foreach ($Pattern in @("Refused", "Failed", "locked", "timed out", "Dropping", "Lost the link", "too big")) { + $Counts[$Pattern] = @($Logs | Select-String -SimpleMatch $Pattern).Count + } + $Sent = @($Logs | Select-String -Pattern "\[Peer\] Sent (\d+) messages .* in (\d+) ms") + $Messages = 0; $Ms = 0 + foreach ($Match in $Sent) { + $Messages += [int]$Match.Matches[0].Groups[1].Value + $Ms += [int]$Match.Matches[0].Groups[2].Value + } + $Issues += [pscustomobject]@{ + Server = $Server.Name; Counts = $Counts + ReplicatedOut = $Messages; ReplicateMs = $Ms; CatchUps = $Sent.Count + } + } + return $Issues +} + +function Write-Report($Servers) { + $Lines = @() + $Lines += "# BakaShrot replication benchmark, $(Get-Date -Format 'yyyy-MM-dd HH:mm')" + $Lines += "" + $Cpu = (Get-CimInstance Win32_Processor | Select-Object -First 1).Name.Trim() + $Ram = [math]::Round((Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory / 1GB) + $Lines += "- Machine: $Cpu, $Ram GB RAM, everything on localhost" + $Lines += "- Topology: $Topology, $ServerCount servers ($(($Servers | ForEach-Object { "$($_.Name) <-> " + (($_.Peers | ForEach-Object { $Servers[$_].Name }) -join '/') }) -join '; '))" + $Lines += "- Names: $Names ($(if ($Names -eq 'Wildcard') { 'each server names its own nodes, peers take them by AcceptNodes = n*' } else { 'every node named on every server' }))" + $Lines += "- Messages: ~$MessageSize bytes of JSON, PeerSyncInterval $PeerSyncInterval s, PeerBatchSize $PeerBatchSize, $PushSeconds s per stage" + $Lines += "- Built with: $($script:CompilerName), SQLite $((Get-Item (Join-Path $OutDir 'sqlite3.dll')).VersionInfo.ProductVersion)" + $Lines += "- CPU in % of one core (100 = one core busy), System = whole machine in %, Bench = the load generator itself (% of one core)" + $Lines += "" + + $Lines += "## Stages" + $Lines += "" + $Lines += "- Max lag: most messages a server was missing while pushing. Trough: the lowest lag of the last check-in window, slope: how fast those troughs rise (~0 = keeps up)." + $Lines += "" + $Lines += "| Stage | Nodes | Offered msg/s | Pushed msg/s | Push p50 / p99 / max ms | Failed | Max lag msgs (s of pushes) | Last trough | Trough slope msg/s | Drain s | Verdict |" + $Lines += "|---|---|---|---|---|---|---|---|---|---|---|" + foreach ($R in $script:Results) { + $Offered = if ($R.Rate -gt 0) { Format-Num $R.OfferedRate } else { "max" } + $Lag = ($R.Servers | Measure-Object -Property LagMaxPush -Maximum).Maximum + $LagSeconds = ($R.Servers | Measure-Object -Property LagMaxSeconds -Maximum).Maximum + $Trough = ($R.Servers | Measure-Object -Property LagTroughLast -Maximum).Maximum + $Slope = ($R.Servers | Measure-Object -Property LagSlope -Maximum).Maximum + $Drain = if ($R.Drained) { Format-Num $R.DrainSeconds 1 } else { "> $DrainTimeout" } + $Lines += "| $($R.Stage) | $($R.NodesPerServer) x $ServerCount | $Offered | $(Format-Num $R.PushRate) | $(Format-Num $R.PushP50Ms 1) / $(Format-Num $R.PushP99Ms 1) / $(Format-Num $R.PushMaxMs 0) | $($R.Failed) | $(Format-Num $Lag) ($(Format-Num $LagSeconds 1)) | $(Format-Num $Trough) | $(Format-Num $Slope 1) | $Drain | $(Get-Verdict $R) |" + } + $Lines += "" + + $Lines += "## Resources while pushing" + $Lines += "" + $Header = "| Stage | System CPU avg / max | Bench CPU |" + $Sep = "|---|---|---|" + foreach ($Server in $Servers) { $Header += " $($Server.Name) CPU avg / max | $($Server.Name) RAM WS / private MB |"; $Sep += "---|---|" } + $Header += " Other busy processes (% core) |"; $Sep += "---|" + $Lines += $Header + $Lines += $Sep + foreach ($R in $script:Results) { + $Row = "| $($R.Stage) | $(Format-Num $R.SystemCpuAvg) % / $(Format-Num $R.SystemCpuMax) % | $(Format-Num $R.BenchCpuAvg) |" + foreach ($S in $R.Servers) { $Row += " $(Format-Num $S.CpuAvgPush) / $(Format-Num $S.CpuMaxPush) | $(Format-Num $S.WorkingSetMaxMb 1) / $(Format-Num $S.PrivateMaxMb 1) |" } + $Row += " $($R.OtherProcesses) |" + $Lines += $Row + } + $Lines += "" + + $Lines += "## Per server, end of stage" + $Lines += "" + $Header = "| Stage |" + $Sep = "|---|" + foreach ($Server in $Servers) { $Header += " $($Server.Name) rows | DB MB | max lag | monitor query avg / max ms |"; $Sep += "---|---|---|---|" } + $Lines += $Header + $Lines += $Sep + foreach ($R in $script:Results) { + $Row = "| $($R.Stage) |" + foreach ($S in $R.Servers) { $Row += " $(Format-Num $S.Rows) | $(Format-Num $S.DbMb 1) | $(Format-Num $S.LagMaxPush) | $(Format-Num $S.MonitorAvgMs 1) / $(Format-Num $S.MonitorMaxMs 1) |" } + $Lines += $Row + } + $Lines += "" + + $Lines += "## Queries, idle, median ms (on $($Servers[0].Name))" + $Lines += "" + $Stages = $script:QueryResults | Where-Object Server -eq $Servers[0].Name | Select-Object -ExpandProperty Stage -Unique + $Names = $script:QueryResults | Select-Object -ExpandProperty Name -Unique + $Header = "| Query |" + $Sep = "|---|" + foreach ($Stage in $Stages) { + $Rows = ($script:QueryResults | Where-Object { $_.Stage -eq $Stage } | Select-Object -First 1).DataRows + $Header += " $Stage ($(Format-Num $Rows) rows) |"; $Sep += "---|" + } + $Lines += $Header + $Lines += $Sep + foreach ($Name in $Names) { + $Row = "| $Name |" + foreach ($Stage in $Stages) { + $Q = $script:QueryResults | Where-Object { $_.Stage -eq $Stage -and $_.Name -eq $Name -and $_.Server -eq $Servers[0].Name } | Select-Object -First 1 + if (-not $Q) { $Row += " |" } + elseif ($Q.Count -eq 0) { $Row += " FAIL: $($Q.LastError) |" } + else { $Row += " $(Format-Num $Q.P50Ms 1) |" } + } + $Lines += $Row + } + $Lines += "" + + $Mixed = $script:Results | Where-Object { $_.QueriesUnderLoad.Count -gt 0 } + foreach ($R in $Mixed) { + $Lines += "## Queries under load ($($R.Stage), on $($Servers[0].Name), while pushing $(Format-Num $R.PushRate) msg/s)" + $Lines += "" + $Lines += "| Query | Runs | p50 ms | p90 ms | max ms | Failures |" + $Lines += "|---|---|---|---|---|---|" + foreach ($Q in $R.QueriesUnderLoad) { + $Lines += "| $($Q.Name) | $($Q.Count) | $(Format-Num $Q.P50Ms 1) | $(Format-Num $Q.P90Ms 1) | $(Format-Num $Q.MaxMs 1) | $($Q.Failures) $($Q.LastError) |" + } + $Lines += "" + } + + $Lines += "## Server logs" + $Lines += "" + $Lines += "| Server | Catch-ups sent | Messages replicated out | ms spent sending | Refused | Failed | locked | timed out | Dropping | Lost the link | too big |" + $Lines += "|---|---|---|---|---|---|---|---|---|---|---|" + foreach ($I in (Get-LogIssues $Servers)) { + $Lines += "| $($I.Server) | $($I.CatchUps) | $(Format-Num $I.ReplicatedOut) | $(Format-Num $I.ReplicateMs) | $(($I.Counts.Values) -join ' | ') |" + } + $Lines += "" + + $Report = Join-Path $RunDir "report.md" + Set-Content -Path $Report -Value ($Lines -join "`r`n") -Encoding UTF8 + @{ Results = $script:Results; Queries = $script:QueryResults } | ConvertTo-Json -Depth 8 | Set-Content (Join-Path $RunDir "results.json") -Encoding UTF8 + return $Report +} + + +# --- Main ------------------------------------------------------------------- + +if (-not $SkipBuild) { Invoke-Build } +Copy-Dlls +New-Item -ItemType Directory -Force $RunDir, $LogDir | Out-Null +Write-Host "Run folder: $RunDir" + +$ClientKeys = New-KeyPair +$Servers = @(New-Servers) +foreach ($Server in $Servers) { Write-ServerConfig $Server $Servers $ClientKeys } + +try { + Start-Servers $Servers + $Last = $null + + if ($PartList -contains "Ramp") { + $i = 0 + foreach ($Spec in $Ramp.Split(",")) { + $i++ + $Stage = ConvertTo-Stage $Spec + $Last = Invoke-Stage "Ramp" ("ramp{0:D2}-{1}" -f $i, $Spec.Trim()) $Stage $Servers $ClientKeys + } + } + + if ($PartList -contains "Scale") { + foreach ($Target in $SeedTotals) { + $Current = 0 + if ($Last) { $Current = ($Last.Servers | Measure-Object -Property Rows -Minimum).Minimum } + Invoke-Seed $Servers $Target $Current + $Last = Invoke-Stage "Scale" ("scale-{0}k" -f [math]::Round($Target / 1000)) (ConvertTo-Stage $SteadyStage) $Servers $ClientKeys + } + } + + if ($PartList -contains "Mixed") { + $Last = Invoke-Stage "Mixed" "mixed" (ConvertTo-Stage $MixedStage) $Servers $ClientKeys -QueryLoad + } +} +finally { + Stop-Servers $Servers + if ($script:Results.Count -gt 0) { + $Report = Write-Report $Servers + Write-Host "" + Write-Host "Report: $Report" + } + Write-Host "Server logs: $LogDir" + if (-not $KeepData) { + Get-ChildItem $RunData -Filter "*.sqlite*" | Remove-Item -Force + } else { + Write-Host "Databases kept in $RunData" + } +} diff --git a/Tests/Bench/BenchClient.pb b/Tests/Bench/BenchClient.pb new file mode 100644 index 0000000..9d07018 --- /dev/null +++ b/Tests/Bench/BenchClient.pb @@ -0,0 +1,1356 @@ +; ============================================================================ +; BakaShrot Bench Client +; +; Usage: BenchClient +; +; run One benchmark stage: +; 1. One thread per pushing node, each with its own connection to +; its server, all connected before the clock starts. +; 2. They push for [Bench] PushSeconds, at [Bench] Rate messages +; per second each (0: as fast as the server answers). +; 3. Meanwhile, every [Bench] SampleMs, samples every server: +; how many messages of every node it has (replication lag), +; its CPU and RAM, its database's size. +; 4. Then keeps sampling, every [Bench] DrainSampleMs, until every +; server has every message (drained) or [Bench] DrainTimeout. +; Optionally, a thread runs [Bench] QueryFile in a loop against the +; servers with QueryLoad = 1 while pushing, to see how queries hold +; up under load. +; Writes every sample to [Bench] SamplesCsv, and the stage's summary +; to [Bench] SummaryOut (JSON). +; query Runs every query of [Bench] QueryFile against every server with +; Query = 1, [Bench] QueryRepeats times each (plus a warm-up), and +; writes their timings to [Bench] QueryOut (JSON). +; +; Plan.ini (written by Tests/Bench/Bench-Replication.ps1): +; [Bench] +; PrivateKey, PublicKey The client key every server registers. +; TopicId Topic every node pushes into. +; ServerCount Number of [Server] sections, 1-based. +; PushSeconds, Rate, MessageSize, SampleMs, DrainSampleMs, DrainTimeout +; SamplesCsv, SummaryOut, QueryFile, QueryRepeats, QueryOut +; [Server] +; Name, Host, Port, Pid, DatabasePath +; PublicKey The server's, it must prove it holds the private one. +; FirstNode, MaxNodes Its nodes are FirstNode to FirstNode+MaxNodes-1, +; all of them are monitored. +; NodeCount How many of them push in this stage, from FirstNode. +; MonitorNode, QueryNode Identities used by the sampler and the queries. +; QueryLoad, Query 0/1, see above. +; +; Query file: one query per line, "Name | SQL", # starts a comment. +; {TOPIC} and {NODE} are replaced by the topic id and the server's FirstNode. +; "@latest" as the SQL does a GetLatestMessage of {NODE} instead. +; +; CPU is in % of one core (200 = two cores busy), the system's in % of the +; whole machine. RAM is the working set and the private bytes, in MB. +; Windows only (process sampling), compile as a thread-safe console program. +; ============================================================================ + +EnableExplicit + +CompilerIf Not #PB_Compiler_Thread + CompilerError "BenchClient needs the thread-safe option." +CompilerEndIf + +XIncludeFile "../../Commons/Networking/Outbound.pbi" + + +#Bench_RequestTimeout = 60000 +#Bench_MaxNodes = 512 + + +; --- Windows process sampling ------------------------------------------------ + +Structure BenchMemoryCounters + cb.l + PageFaultCount.l + PeakWorkingSetSize.i + WorkingSetSize.i + QuotaPeakPagedPoolUsage.i + QuotaPagedPoolUsage.i + QuotaPeakNonPagedPoolUsage.i + QuotaNonPagedPoolUsage.i + PagefileUsage.i + PeakPagefileUsage.i +EndStructure + +; CPU use is measured in cycles, not with GetProcessTimes(): that one is +; charged per clock tick, and threads that wake up from a Delay(), work a bit +; and sleep again before the next tick (all of BakaShrot's polling) are +; mostly never charged at all. +Prototype.i Proto_QueryProcessCycleTime(Process.i, *Cycles) +Prototype.i Proto_QueryThreadCycleTime(Thread.i, *Cycles) +Prototype.i Proto_QueryIdleProcessorCycleTime(*BufferLength, *Buffer) +Prototype.i Proto_GetProcessMemoryInfo(Process.i, *Counters, Cb.l) + +Global Bench_QueryProcessCycleTime.Proto_QueryProcessCycleTime +Global Bench_QueryThreadCycleTime.Proto_QueryThreadCycleTime +Global Bench_QueryIdleProcessorCycleTime.Proto_QueryIdleProcessorCycleTime +Global Bench_GetProcessMemoryInfo.Proto_GetProcessMemoryInfo +Global Bench_CyclesPerMs.d +Global Bench_CpuCount.i +Global Bench_QpcFrequency.q + + +; --- State ------------------------------------------------------------------- + +Structure BenchLagSample + T.d + Lag.q +EndStructure + +Structure BenchServer + Name.s + Host.s + Port.i + Pid.i + DatabasePath.s + FirstNode.i + MaxNodes.i + NodeCount.i + MonitorNode.i + QueryNode.i + QueryLoad.i + Query.i + ; The server's Ed25519 public key, it must prove it holds the private one. + PublicKey.a[#BakaShrot_Ed25519_PublicKeySize] + + Monitor.BakaShrot_Outbound + Process.i + LastCpu.q + + ; Latest sample + Present.q + Lag.q + CpuPercent.d + WorkingSetMb.d + PrivateMb.d + DbMb.d + MonitorMs.d + + ; Stage stats + CpuSumPush.d + CpuMaxPush.d + CpuCountPush.i + CpuSumDrain.d + CpuMaxDrain.d + CpuCountDrain.i + WorkingSetMaxMb.d + PrivateMaxMb.d + PresentAtPushStart.q + LagMaxPush.q + LagAtPushEnd.q + MonitorSumMs.d + MonitorMaxMs.d + MonitorCount.i + MonitorFailures.i + ; Every lag sample while pushing, see Bench_TroughSlope(). + List PushLag.BenchLagSample() +EndStructure + +Structure BenchPusher + ServerIndex.i + NodeId.i + ThreadId.i + Ready.i + ConnectFailed.i + Sent.q + Failed.q + Reconnects.i + LastError.s + List LatencyMs.f() +EndStructure + +Structure BenchQueryStats + Name.s + Sql.s + List LatencyMs.f() + Failures.i + LastError.s +EndStructure + +Global Bench_PlanPath.s +Global Bench_TopicId.i +Global Bench_PublicKey.s +Global Dim Bench_PrivateKey.a(#BakaShrot_Ed25519_PrivateKeySize - 1) +Global Bench_PushSeconds.i, Bench_Rate.d, Bench_MessageSize.i +Global Bench_SampleMs.i, Bench_DrainSampleMs.i, Bench_DrainTimeout.i +Global Bench_SamplesCsv.s, Bench_SummaryOut.s, Bench_QueryFile.s, Bench_QueryOut.s +Global Bench_QueryRepeats.i + +Global Bench_ServerCount.i +Global Dim Bench_Servers.BenchServer(0) + +; Every monitored node, and how many messages of it each server has. +Global Bench_NodeCount.i +Global Dim Bench_Nodes.i(0) +Global Dim Bench_Present.q(0, 0) +Global Bench_MonitorSql.s + +Global Bench_PusherCount.i +Global Dim Bench_Pushers.BenchPusher(0) + +Global Bench_PushStarted.i, Bench_StopPush.i +Global Bench_StartMs.d + +; Query load during the push +Global NewList Bench_LoadStats.BenchQueryStats() + +; Sampling +Global Bench_LastSampleMs.d +Global Bench_LastIdleCycles.q +Global Bench_LastSelfCpu.q +Global Bench_SyncInterval.i +Global Bench_SystemCpu.d, Bench_SelfCpu.d +Global Bench_SystemCpuSum.d, Bench_SystemCpuMax.d, Bench_SystemCpuCount.i +Global Bench_SelfCpuSum.d, Bench_SelfCpuCount.i +Global Bench_LastPushed.q +Global Bench_CsvFile.i + + +Procedure.d Bench_NowMs() + Protected Count.q + QueryPerformanceCounter_(@Count) + ProcedureReturn Count * 1000.0 / Bench_QpcFrequency +EndProcedure + + +Procedure Bench_Fail(Message.s) + PrintN("[Bench] " + Message) + End 1 +EndProcedure + + +; --- Plan -------------------------------------------------------------------- + +Procedure Bench_LoadPlan(PlanPath.s) + Protected i.i, n.i, Node.i + + If Not OpenPreferences(PlanPath) + Bench_Fail("Failed to open the plan '" + PlanPath + "'") + EndIf + + PreferenceGroup("Bench") + Bench_PublicKey = ReadPreferenceString("PublicKey", "") + Bench_TopicId = ReadPreferenceLong("TopicId", 1) + Bench_ServerCount = ReadPreferenceLong("ServerCount", 0) + Bench_PushSeconds = ReadPreferenceLong("PushSeconds", 10) + Bench_Rate = ReadPreferenceDouble("Rate", 10) + Bench_MessageSize = ReadPreferenceLong("MessageSize", 200) + Bench_SampleMs = ReadPreferenceLong("SampleMs", 1000) + Bench_DrainSampleMs = ReadPreferenceLong("DrainSampleMs", 250) + Bench_DrainTimeout = ReadPreferenceLong("DrainTimeout", 120) + Bench_SyncInterval = ReadPreferenceLong("PeerSyncInterval", 5) + Bench_SamplesCsv = ReadPreferenceString("SamplesCsv", "samples.csv") + Bench_SummaryOut = ReadPreferenceString("SummaryOut", "summary.json") + Bench_QueryFile = ReadPreferenceString("QueryFile", "") + Bench_QueryRepeats = ReadPreferenceLong("QueryRepeats", 5) + Bench_QueryOut = ReadPreferenceString("QueryOut", "queries.json") + If Not DecodeKeyFromString(ReadPreferenceString("PrivateKey", ""), @Bench_PrivateKey(0), #BakaShrot_Ed25519_PrivateKeySize) + Bench_Fail("Invalid [Bench] PrivateKey") + EndIf + If Bench_ServerCount < 1 + Bench_Fail("No servers in the plan") + EndIf + + Dim Bench_Servers.BenchServer(Bench_ServerCount - 1) + Bench_NodeCount = 0 + For i = 0 To Bench_ServerCount - 1 + PreferenceGroup("Server" + Str(i + 1)) + With Bench_Servers(i) + \Name = ReadPreferenceString("Name", "server" + Str(i + 1)) + \Host = ReadPreferenceString("Host", "127.0.0.1") + \Port = ReadPreferenceLong("Port", 0) + \Pid = ReadPreferenceLong("Pid", 0) + \DatabasePath = ReadPreferenceString("DatabasePath", "") + \FirstNode = ReadPreferenceLong("FirstNode", 0) + \MaxNodes = ReadPreferenceLong("MaxNodes", 0) + \NodeCount = ReadPreferenceLong("NodeCount", 0) + \MonitorNode = ReadPreferenceLong("MonitorNode", 0) + \QueryNode = ReadPreferenceLong("QueryNode", 0) + \QueryLoad = ReadPreferenceLong("QueryLoad", 0) + \Query = ReadPreferenceLong("Query", 0) + If Not DecodeKeyFromString(ReadPreferenceString("PublicKey", ""), @\PublicKey[0], #BakaShrot_Ed25519_PublicKeySize) + Bench_Fail("Server" + Str(i + 1) + " has no valid PublicKey in the plan") + EndIf + If \NodeCount > \MaxNodes + \MaxNodes = \NodeCount + EndIf + Bench_NodeCount + \MaxNodes + EndWith + Next + ClosePreferences() + + If Bench_NodeCount > #Bench_MaxNodes + Bench_Fail("Too many nodes") + EndIf + + ; Every monitored node, and one query asking a server for all of them. + ; One indexed MAX() per node: cheap, even with millions of rows. By name + ; ("bench", "n" + id, see Bench-Replication.ps1) through the "messages" + ; view: each server can have its own ids for them (-Names Wildcard). + Dim Bench_Nodes.i(Bench_NodeCount - 1) + Dim Bench_Present.q(Bench_ServerCount - 1, Bench_NodeCount - 1) + n = 0 + Bench_MonitorSql = "SELECT " + For i = 0 To Bench_ServerCount - 1 + For Node = Bench_Servers(i)\FirstNode To Bench_Servers(i)\FirstNode + Bench_Servers(i)\MaxNodes - 1 + Bench_Nodes(n) = Node + If n > 0 + Bench_MonitorSql + ", " + EndIf + Bench_MonitorSql + "(SELECT COALESCE(MAX(message_id), 0) FROM messages WHERE topic = 'bench' AND node = 'n" + Str(Node) + "')" + n + 1 + Next + Next +EndProcedure + + +; --- Requests ---------------------------------------------------------------- + +Procedure.i Bench_Connect(*Outbound.BakaShrot_Outbound, *Server.BenchServer, NodeId.i) + Protected Identity.BakaShrot_OutboundIdentity + + Identity\Topic = Str(Bench_TopicId) + Identity\Node = Str(NodeId) + Identity\PublicKey = Bench_PublicKey + Identity\PrivateKey = @Bench_PrivateKey(0) + ProcedureReturn BakaShrot_Outbound_Connect(*Outbound, *Server\Host, *Server\Port, @Identity, @*Server\PublicKey[0]) +EndProcedure + + +; Sends *Request, returns the answer (free it) or 0 if the connection failed. +Procedure.i Bench_Request(*Outbound.BakaShrot_Outbound, *Request, RequestSize.i, *AnswerSize.Integer) + If Not BakaShrot_Outbound_Send(*Outbound, *Request, RequestSize) + ProcedureReturn 0 + EndIf + ProcedureReturn BakaShrot_Outbound_WaitPacket(*Outbound, *AnswerSize, #Bench_RequestTimeout) +EndProcedure + + +Procedure.s Bench_RefusalReason(*Answer, AnswerSize.i) + Protected *View.MsgPackData, *Refused.BakaShrot_RequestRefused, Reason.s + + Reason = "unexpected answer" + If BakaShrot_GetPacketType(*Answer, AnswerSize) = #BakaShrot_PacketType_RequestRefused + *Refused = 0 + *View = MsgPackWrapMsgBuffer(*Answer, AnswerSize) + If *View + *Refused = BakaShrot_RequestRefusedPacket_Decode(*View) + MsgPackFree(*View, #False) + EndIf + If *Refused + Reason = "refused: " + *Refused\Reason + FreeStructure(*Refused) + EndIf + EndIf + ProcedureReturn Reason +EndProcedure + + +; Runs a query (or "@latest", a GetLatestMessage of NodeId). +; Returns #True with the time it took in *Ms\d, the answer's size in +; *Bytes\i and the JSON result in *Result\s, or #False with *Error\s set. +; Reconnects as ConnectNode if the connection was lost. +Procedure.i Bench_RunQuery(*Outbound.BakaShrot_Outbound, *Server.BenchServer, ConnectNode.i, Sql.s, NodeId.i, *Ms.Double, *Bytes.Integer, *Result.String, *Error.String) + Protected Request.BakaShrot_QueryRequest, Latest.BakaShrot_GetLatestMessage + Protected *QueryResult.BakaShrot_QueryResult, *LatestMessage.BakaShrot_LatestMessage + Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer, *View.MsgPackData + Protected StartMs.d, Expected.i, Ok.i + + If Not *Outbound\ConnectionId + If Not Bench_Connect(*Outbound, *Server, ConnectNode) + *Error\s = "can't connect" + ProcedureReturn #False + EndIf + EndIf + + If Sql = "@latest" + Latest\Topic = Str(Bench_TopicId) + Latest\Node = Str(NodeId) + *Packet = BakaShrot_GetLatestMessagePacket_Encode(@Latest, @PacketSize) + Expected = #BakaShrot_PacketType_LatestMessage + Else + Request\Sql = Sql + *Packet = BakaShrot_QueryRequestPacket_Encode(@Request, @PacketSize) + Expected = #BakaShrot_PacketType_QueryResult + EndIf + If Not *Packet + *Error\s = "can't encode" + ProcedureReturn #False + EndIf + + StartMs = Bench_NowMs() + *Answer = Bench_Request(*Outbound, *Packet, PacketSize\i, @AnswerSize) + *Ms\d = Bench_NowMs() - StartMs + FreeMemory(*Packet) + + If Not *Answer + BakaShrot_Outbound_Close(*Outbound, #BakaShrot_ConnectionStatus_Aborted) + *Error\s = "connection lost" + ProcedureReturn #False + EndIf + + *Bytes\i = AnswerSize\i + If BakaShrot_GetPacketType(*Answer, AnswerSize\i) <> Expected + *Error\s = Bench_RefusalReason(*Answer, AnswerSize\i) + FreeMemory(*Answer) + ProcedureReturn #False + EndIf + + Ok = #False + *View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i) + If *View + If Expected = #BakaShrot_PacketType_QueryResult + *QueryResult = BakaShrot_QueryResultPacket_Decode(*View) + If *QueryResult + *Result\s = *QueryResult\JsonResult + FreeStructure(*QueryResult) + Ok = #True + EndIf + Else + *LatestMessage = BakaShrot_LatestMessagePacket_Decode(*View) + If *LatestMessage + *Result\s = ~"{\"columns\": [\"message_id\"], \"rows\": [[\"" + Str(*LatestMessage\MessageId) + ~"\"]]}" + FreeStructure(*LatestMessage) + Ok = #True + EndIf + EndIf + MsgPackFree(*View, #False) + EndIf + FreeMemory(*Answer) + + If Not Ok + *Error\s = "can't decode the answer" + EndIf + ProcedureReturn Ok +EndProcedure + + +; Number of rows in a query's JSON result, -1 if it can't be parsed. +Procedure.i Bench_CountRows(Result.s) + Protected JsonId.i, *Rows, Count.i = -1 + + JsonId = ParseJSON(#PB_Any, Result) + If JsonId + *Rows = GetJSONMember(JSONValue(JsonId), "rows") + If *Rows + Count = JSONArraySize(*Rows) + EndIf + FreeJSON(JsonId) + EndIf + ProcedureReturn Count +EndProcedure + + +; Loads the query file into Queries(). +Procedure Bench_LoadQueries(Path.s, List Queries.BenchQueryStats()) + Protected FileId.i, Line.s, Separator.i + + ClearList(Queries()) + If Path = "" + ProcedureReturn + EndIf + FileId = ReadFile(#PB_Any, Path) + If Not FileId + Bench_Fail("Failed to open the query file '" + Path + "'") + EndIf + While Not Eof(FileId) + Line = Trim(ReadString(FileId, #PB_UTF8)) + If Line = "" Or Left(Line, 1) = "#" + Continue + EndIf + Separator = FindString(Line, "|") + If Separator < 2 + Continue + EndIf + AddElement(Queries()) + Queries()\Name = Trim(Left(Line, Separator - 1)) + Queries()\Sql = Trim(Mid(Line, Separator + 1)) + Wend + CloseFile(FileId) +EndProcedure + + +Procedure.s Bench_ExpandSql(Sql.s, *Server.BenchServer) + Sql = ReplaceString(Sql, "{TOPIC}", Str(Bench_TopicId)) + Sql = ReplaceString(Sql, "{NODE}", Str(*Server\FirstNode)) + ProcedureReturn Sql +EndProcedure + + +; --- Pushers ----------------------------------------------------------------- + +Procedure Bench_PusherThread(*Pusher.BenchPusher) + Protected *Server.BenchServer = @Bench_Servers(*Pusher\ServerIndex) + Protected Outbound.BakaShrot_Outbound + Protected Push.BakaShrot_PushMessage + Protected *Request, RequestSize.Integer, *Answer, AnswerSize.Integer + Protected Attempt.i, Seq.q, Kind.s, Pad.s, Json.s, Spread.i, Value.i + Protected IntervalMs.d, NextDueMs.d, NowMs.d, StartMs.d, LatencyMs.d + + For Attempt = 1 To 5 + If Bench_Connect(@Outbound, *Server, *Pusher\NodeId) + Break + EndIf + Delay(200 * Attempt) + Next + If Not Outbound\ConnectionId + *Pusher\ConnectFailed = #True + *Pusher\LastError = "can't connect" + *Pusher\Ready = #True + ProcedureReturn + EndIf + *Pusher\Ready = #True + + ; About MessageSize bytes of JSON, ~90 without the padding. + If Bench_MessageSize > 90 + Pad = LSet("", Bench_MessageSize - 90, "x") + EndIf + + While Not Bench_PushStarted And Not Bench_StopPush + Delay(1) + Wend + + If Bench_Rate > 0 + IntervalMs = 1000.0 / Bench_Rate + ; Spread the nodes' pushes over the interval. + Spread = *Pusher\NodeId % 97 + NextDueMs = Bench_NowMs() + IntervalMs * Spread / 97.0 + EndIf + + While Not Bench_StopPush + If Bench_Rate > 0 + NowMs = Bench_NowMs() + If NowMs < NextDueMs + Delay(1) + Continue + EndIf + NextDueMs + IntervalMs + ; More than a second behind: the server can't keep up, don't + ; build up a backlog to burst later. + If NowMs - NextDueMs > 1000 + NextDueMs = NowMs + EndIf + EndIf + + Seq + 1 + If Seq % 50 = 0 + Kind = "alert" + Else + Select Seq % 4 + Case 0 : Kind = "temp" + Case 1 : Kind = "humidity" + Case 2 : Kind = "pressure" + Default : Kind = "status" + EndSelect + EndIf + Value = (Seq * 7919 + *Pusher\NodeId) % 10000 + Json = ~"{\"kind\":\"" + Kind + ~"\",\"node\":" + Str(*Pusher\NodeId) + ~",\"seq\":" + Str(Seq) + + ~",\"value\":" + StrD(Value / 100.0, 2) + + ~",\"ts\":" + Str(Date()) + ~",\"pad\":\"" + Pad + ~"\"}" + + Push\JsonData = Json + *Request = BakaShrot_PushMessagePacket_Encode(@Push, @RequestSize) + If Not *Request + *Pusher\Failed + 1 + *Pusher\LastError = "can't encode" + Continue + EndIf + + StartMs = Bench_NowMs() + *Answer = Bench_Request(@Outbound, *Request, RequestSize\i, @AnswerSize) + LatencyMs = Bench_NowMs() - StartMs + FreeMemory(*Request) + + If Not *Answer + *Pusher\Failed + 1 + *Pusher\LastError = "connection lost" + BakaShrot_Outbound_Close(@Outbound, #BakaShrot_ConnectionStatus_Aborted) + *Pusher\Reconnects + 1 + If Not Bench_Connect(@Outbound, *Server, *Pusher\NodeId) + Delay(500) + If Not Bench_Connect(@Outbound, *Server, *Pusher\NodeId) + *Pusher\LastError = "connection lost, can't reconnect" + Break + EndIf + EndIf + Continue + EndIf + + If BakaShrot_GetPacketType(*Answer, AnswerSize\i) = #BakaShrot_PacketType_MessagePushed + AddElement(*Pusher\LatencyMs()) + *Pusher\LatencyMs() = LatencyMs + *Pusher\Sent + 1 + Else + *Pusher\Failed + 1 + *Pusher\LastError = Bench_RefusalReason(*Answer, AnswerSize\i) + EndIf + FreeMemory(*Answer) + Wend + + BakaShrot_Outbound_Close(@Outbound, #BakaShrot_ConnectionStatus_Disconnected) +EndProcedure + + +; Runs the query file in a loop against the QueryLoad servers until the push +; ends. +Procedure Bench_QueryLoadThread(Unused.i) + Protected NewList Queries.BenchQueryStats() + Protected Dim Outbounds.BakaShrot_Outbound(Bench_ServerCount - 1) + Protected i.i, Ms.Double, Bytes.Integer, Result.String, Error.String, Sql.s + + While Not Bench_PushStarted And Not Bench_StopPush + Delay(1) + Wend + + While Not Bench_StopPush + ForEach Bench_LoadStats() + For i = 0 To Bench_ServerCount - 1 + If Not Bench_Servers(i)\QueryLoad + Continue + EndIf + If Bench_StopPush + Break 2 + EndIf + Sql = Bench_ExpandSql(Bench_LoadStats()\Sql, @Bench_Servers(i)) + If Bench_RunQuery(@Outbounds(i), @Bench_Servers(i), Bench_Servers(i)\QueryNode, Sql, Bench_Servers(i)\FirstNode, @Ms, @Bytes, @Result, @Error) + AddElement(Bench_LoadStats()\LatencyMs()) + Bench_LoadStats()\LatencyMs() = Ms\d + Else + Bench_LoadStats()\Failures + 1 + Bench_LoadStats()\LastError = Error\s + EndIf + Next + Next + Delay(100) + Wend + + For i = 0 To Bench_ServerCount - 1 + BakaShrot_Outbound_Close(@Outbounds(i), #BakaShrot_ConnectionStatus_Disconnected) + Next +EndProcedure + + +; --- Sampling ---------------------------------------------------------------- + +Procedure.q Bench_ProcessCycles(Process.i) + Protected Cycles.q + If Not Bench_QueryProcessCycleTime(Process, @Cycles) + ProcedureReturn 0 + EndIf + ProcedureReturn Cycles +EndProcedure + + +; Idle cycles of every processor, summed. +Procedure.q Bench_IdleCycles() + Protected Dim Buffer.q(255), Size.l, i.i, Total.q + + Size = 256 * SizeOf(Quad) + If Bench_QueryIdleProcessorCycleTime(@Size, @Buffer(0)) + Bench_CpuCount = Size / SizeOf(Quad) + For i = 0 To Bench_CpuCount - 1 + Total + Buffer(i) + Next + EndIf + ProcedureReturn Total +EndProcedure + + +; How many cycles a busy processor counts per ms: spins a few times for +; 200 ms, keeps the best (the least preempted). +Procedure Bench_CalibrateCycles() + Protected Attempt.i, StartMs.d, NowMs.d, Start.q, Finish.q, Rate.d + + For Attempt = 1 To 3 + Bench_QueryThreadCycleTime(GetCurrentThread_(), @Start) + StartMs = Bench_NowMs() + Repeat + NowMs = Bench_NowMs() + Until NowMs - StartMs >= 200 + Bench_QueryThreadCycleTime(GetCurrentThread_(), @Finish) + Rate = (Finish - Start) / (NowMs - StartMs) + If Rate > Bench_CyclesPerMs + Bench_CyclesPerMs = Rate + EndIf + Next +EndProcedure + + +Procedure Bench_InitSampling() + Protected Kernel32.i, i.i + + Kernel32 = OpenLibrary(#PB_Any, "kernel32.dll") + If Not Kernel32 + Bench_Fail("Can't open kernel32.dll") + EndIf + Bench_QueryProcessCycleTime = GetFunction(Kernel32, "QueryProcessCycleTime") + Bench_QueryThreadCycleTime = GetFunction(Kernel32, "QueryThreadCycleTime") + Bench_QueryIdleProcessorCycleTime = GetFunction(Kernel32, "QueryIdleProcessorCycleTime") + Bench_GetProcessMemoryInfo = GetFunction(Kernel32, "K32GetProcessMemoryInfo") + If Not Bench_QueryProcessCycleTime Or Not Bench_QueryThreadCycleTime Or Not Bench_QueryIdleProcessorCycleTime Or Not Bench_GetProcessMemoryInfo + Bench_Fail("Missing kernel32 functions") + EndIf + + Bench_CalibrateCycles() + Bench_LastIdleCycles = Bench_IdleCycles() + Bench_LastSelfCpu = Bench_ProcessCycles(GetCurrentProcess_()) + + For i = 0 To Bench_ServerCount - 1 + With Bench_Servers(i) + If \Pid + ; PROCESS_QUERY_INFORMATION | PROCESS_VM_READ + \Process = OpenProcess_($0400 | $0010, 0, \Pid) + If \Process + \LastCpu = Bench_ProcessCycles(\Process) + Else + PrintN("[Bench] Can't open the process of '" + \Name + "' (pid " + Str(\Pid) + "), no CPU/RAM for it") + EndIf + EndIf + EndWith + Next + Bench_LastSampleMs = Bench_NowMs() +EndProcedure + + +Procedure Bench_WriteCsvHeader() + Protected Line.s, i.i, Prefix.s + + Bench_CsvFile = CreateFile(#PB_Any, Bench_SamplesCsv) + If Not Bench_CsvFile + Bench_Fail("Can't create '" + Bench_SamplesCsv + "'") + EndIf + Line = "t_s,phase,pushed,push_rate,system_cpu,bench_cpu" + For i = 0 To Bench_ServerCount - 1 + Prefix = Bench_Servers(i)\Name + "_" + Line + "," + Prefix + "present," + Prefix + "lag," + Prefix + "cpu," + Prefix + "ws_mb," + Prefix + "private_mb," + Prefix + "db_mb," + Prefix + "monitor_ms" + Next + WriteStringN(Bench_CsvFile, Line) +EndProcedure + + +Procedure.q Bench_TotalPushed() + Protected i.i, Total.q + For i = 0 To Bench_PusherCount - 1 + Total + Bench_Pushers(i)\Sent + Next + ProcedureReturn Total +EndProcedure + + +; Phase: "push", "push-end" or "drain". Returns the total lag of every server. +Procedure.q Bench_Sample(Phase.s) + Protected NowMs.d, ElapsedS.d, IntervalMs.d, i.i, n.i + Protected Idle.q, Cpu.q, BusyCycles.d + Protected Counters.BenchMemoryCounters + Protected Ms.Double, Bytes.Integer, Result.String, Error.String + Protected JsonId.i, *Row, *Value, Expected.q, TotalLag.q, Pushed.q, PushRate.d, Line.s + + NowMs = Bench_NowMs() + IntervalMs = NowMs - Bench_LastSampleMs + If IntervalMs < 1 + IntervalMs = 1 + EndIf + Bench_LastSampleMs = NowMs + ElapsedS = (NowMs - Bench_StartMs) / 1000.0 + + ; Machine and self CPU + ; Cycles a fully busy processor would have counted meanwhile. + BusyCycles = Bench_CyclesPerMs * IntervalMs + Idle = Bench_IdleCycles() + If Bench_CpuCount > 0 + Bench_SystemCpu = 100.0 * (1.0 - (Idle - Bench_LastIdleCycles) / (BusyCycles * Bench_CpuCount)) + If Bench_SystemCpu < 0 + Bench_SystemCpu = 0 + EndIf + EndIf + Bench_LastIdleCycles = Idle + Cpu = Bench_ProcessCycles(GetCurrentProcess_()) + Bench_SelfCpu = 100.0 * (Cpu - Bench_LastSelfCpu) / BusyCycles + Bench_LastSelfCpu = Cpu + + For i = 0 To Bench_ServerCount - 1 + With Bench_Servers(i) + If \Process + Cpu = Bench_ProcessCycles(\Process) + \CpuPercent = 100.0 * (Cpu - \LastCpu) / BusyCycles + \LastCpu = Cpu + Counters\cb = SizeOf(BenchMemoryCounters) + If Bench_GetProcessMemoryInfo(\Process, @Counters, SizeOf(BenchMemoryCounters)) + \WorkingSetMb = Counters\WorkingSetSize / 1048576.0 + \PrivateMb = Counters\PagefileUsage / 1048576.0 + EndIf + EndIf + If \DatabasePath <> "" + \DbMb = FileSize(\DatabasePath) / 1048576.0 + EndIf + + ; How many messages of every node it has. + If Bench_RunQuery(@\Monitor, @Bench_Servers(i), \MonitorNode, Bench_MonitorSql, 0, @Ms, @Bytes, @Result, @Error) + \MonitorMs = Ms\d + \MonitorSumMs + Ms\d + \MonitorCount + 1 + If Ms\d > \MonitorMaxMs + \MonitorMaxMs = Ms\d + EndIf + JsonId = ParseJSON(#PB_Any, Result\s) + If JsonId + *Row = GetJSONElement(GetJSONMember(JSONValue(JsonId), "rows"), 0) + If *Row + For n = 0 To Bench_NodeCount - 1 + *Value = GetJSONElement(*Row, n) + If *Value And JSONType(*Value) = #PB_JSON_String + Bench_Present(i, n) = Val(GetJSONString(*Value)) + EndIf + Next + EndIf + FreeJSON(JsonId) + EndIf + Else + \MonitorMs = -1 + \MonitorFailures + 1 + PrintN("[Bench] Monitor query on '" + \Name + "' failed: " + Error\s) + EndIf + EndWith + Next + + ; A node's messages are only pushed to its own server, so whoever has the + ; most has all of them so far. + For i = 0 To Bench_ServerCount - 1 + Bench_Servers(i)\Present = 0 + Bench_Servers(i)\Lag = 0 + Next + For n = 0 To Bench_NodeCount - 1 + Expected = 0 + For i = 0 To Bench_ServerCount - 1 + If Bench_Present(i, n) > Expected + Expected = Bench_Present(i, n) + EndIf + Next + For i = 0 To Bench_ServerCount - 1 + Bench_Servers(i)\Present + Bench_Present(i, n) + Bench_Servers(i)\Lag + Expected - Bench_Present(i, n) + Next + Next + + Pushed = Bench_TotalPushed() + PushRate = (Pushed - Bench_LastPushed) * 1000.0 / IntervalMs + Bench_LastPushed = Pushed + + ; Stats + If Phase = "push" + Bench_SystemCpuSum + Bench_SystemCpu + Bench_SystemCpuCount + 1 + If Bench_SystemCpu > Bench_SystemCpuMax + Bench_SystemCpuMax = Bench_SystemCpu + EndIf + Bench_SelfCpuSum + Bench_SelfCpu + Bench_SelfCpuCount + 1 + EndIf + For i = 0 To Bench_ServerCount - 1 + With Bench_Servers(i) + TotalLag + \Lag + If \WorkingSetMb > \WorkingSetMaxMb + \WorkingSetMaxMb = \WorkingSetMb + EndIf + If \PrivateMb > \PrivateMaxMb + \PrivateMaxMb = \PrivateMb + EndIf + If Phase = "push" + \CpuSumPush + \CpuPercent + \CpuCountPush + 1 + If \CpuPercent > \CpuMaxPush + \CpuMaxPush = \CpuPercent + EndIf + If \Lag > \LagMaxPush + \LagMaxPush = \Lag + EndIf + AddElement(\PushLag()) + \PushLag()\T = ElapsedS + \PushLag()\Lag = \Lag + ElseIf Phase = "push-end" + \LagAtPushEnd = \Lag + If \Lag > \LagMaxPush + \LagMaxPush = \Lag + EndIf + Else + \CpuSumDrain + \CpuPercent + \CpuCountDrain + 1 + If \CpuPercent > \CpuMaxDrain + \CpuMaxDrain = \CpuPercent + EndIf + EndIf + EndWith + Next + + Line = StrD(ElapsedS, 3) + "," + Phase + "," + Str(Pushed) + "," + StrD(PushRate, 1) + "," + StrD(Bench_SystemCpu, 1) + "," + StrD(Bench_SelfCpu, 1) + For i = 0 To Bench_ServerCount - 1 + With Bench_Servers(i) + Line + "," + Str(\Present) + "," + Str(\Lag) + "," + StrD(\CpuPercent, 1) + "," + StrD(\WorkingSetMb, 1) + "," + StrD(\PrivateMb, 1) + "," + StrD(\DbMb, 2) + "," + StrD(\MonitorMs, 1) + EndWith + Next + WriteStringN(Bench_CsvFile, Line) + + ProcedureReturn TotalLag +EndProcedure + + +; --- Stats helpers ----------------------------------------------------------- + +; Fills Sorted() from Values() and sorts it. +Procedure Bench_Sorted(List Values.f(), Array Sorted.f(1)) + Protected n.i + + If ListSize(Values()) = 0 + Dim Sorted.f(0) + ProcedureReturn + EndIf + Dim Sorted.f(ListSize(Values()) - 1) + ForEach Values() + Sorted(n) = Values() + n + 1 + Next + SortArray(Sorted(), #PB_Sort_Ascending) +EndProcedure + +Procedure.d Bench_Percentile(Array Sorted.f(1), Count.i, P.d) + If Count = 0 + ProcedureReturn 0 + EndIf + ProcedureReturn Sorted(Int((Count - 1) * P)) +EndProcedure + +Procedure.d Bench_Average(Array Sorted.f(1), Count.i) + Protected i.i, Sum.d + If Count = 0 + ProcedureReturn 0 + EndIf + For i = 0 To Count - 1 + Sum + Sorted(i) + Next + ProcedureReturn Sum / Count +EndProcedure + +Procedure Bench_AddLatencyStats(*Object, Prefix.s, List Values.f()) + Protected Dim Sorted.f(0), Count.i = ListSize(Values()) + + Bench_Sorted(Values(), Sorted()) + SetJSONInteger(AddJSONMember(*Object, Prefix + "Count"), Count) + SetJSONDouble(AddJSONMember(*Object, Prefix + "AvgMs"), Bench_Average(Sorted(), Count)) + SetJSONDouble(AddJSONMember(*Object, Prefix + "P50Ms"), Bench_Percentile(Sorted(), Count, 0.50)) + SetJSONDouble(AddJSONMember(*Object, Prefix + "P90Ms"), Bench_Percentile(Sorted(), Count, 0.90)) + SetJSONDouble(AddJSONMember(*Object, Prefix + "P99Ms"), Bench_Percentile(Sorted(), Count, 0.99)) + If Count > 0 + SetJSONDouble(AddJSONMember(*Object, Prefix + "MaxMs"), Sorted(Count - 1)) + SetJSONDouble(AddJSONMember(*Object, Prefix + "MinMs"), Sorted(0)) + Else + SetJSONDouble(AddJSONMember(*Object, Prefix + "MaxMs"), 0) + SetJSONDouble(AddJSONMember(*Object, Prefix + "MinMs"), 0) + EndIf +EndProcedure + + +; Replication catches up in bursts, once per check-in (every PeerSyncInterval +; plus the catch-up's own time), and a message pushed to a leaf needs two +; check-ins to reach the other leaves through the hub, so the lag is a +; sawtooth. Whether it keeps up shows in its troughs: the lowest lag of every +; window of two check-ins. Returns how fast they rise, in messages per second +; (~0 keeps up, > 0 falls further behind every check-in), and the last full +; window's trough in *LastTrough\q. Needs a push of 3+ windows to mean much. +Procedure.d Bench_TroughSlope(List Samples.BenchLagSample(), *LastTrough.Quad) + Protected Window.d, Index.i, LastIndex.i, n.d, SumT.d, SumL.d, SumTT.d, SumTL.d, Denominator.d + Protected NewMap Troughs.q(), NewMap Centers.d() + + *LastTrough\q = 0 + Window = 2 * Bench_SyncInterval + If Window <= 0 + Window = 10 + EndIf + + LastIndex = -1 + ForEach Samples() + Index = Int(Samples()\T / Window) + If Not FindMapElement(Troughs(), Str(Index)) Or Samples()\Lag < Troughs(Str(Index)) + Troughs(Str(Index)) = Samples()\Lag + EndIf + Centers(Str(Index)) = (Index + 0.5) * Window + If Index > LastIndex + LastIndex = Index + EndIf + Next + + ; The last window is usually cut short by the end of the push. + ForEach Troughs() + If Val(MapKey(Troughs())) = LastIndex And MapSize(Troughs()) > 1 + Continue + EndIf + n + 1 + SumT + Centers(MapKey(Troughs())) + SumL + Troughs() + SumTT + Centers(MapKey(Troughs())) * Centers(MapKey(Troughs())) + SumTL + Centers(MapKey(Troughs())) * Troughs() + If Val(MapKey(Troughs())) = LastIndex - 1 Or MapSize(Troughs()) = 1 + *LastTrough\q = Troughs() + EndIf + Next + + Denominator = n * SumTT - SumT * SumT + If n < 2 Or Denominator = 0 + ProcedureReturn 0 + EndIf + ProcedureReturn (n * SumTL - SumT * SumL) / Denominator +EndProcedure + + +; --- run --------------------------------------------------------------------- + +Procedure Bench_Run() + Protected i.i, n.i, Node.i, NextSampleMs.d, PushEndMs.d, DrainMs.d, TotalLag.q + Protected QueryThread.i, Connected.i, ConnectFailures.i, Pushed.q, Failed.q, Reconnects.i + Protected JsonId.i, *Root, *Servers, *Server, *Queries, *Query, *Errors + Protected NewList AllLatencies.f(), NewMap Errors.i() + Protected PushMs.d, PushRate.d, Trough.Quad + + ; Everyone's identity in place, nothing pushing yet. + Bench_InitSampling() + Bench_WriteCsvHeader() + + For i = 0 To Bench_ServerCount - 1 + If Not Bench_Connect(@Bench_Servers(i)\Monitor, @Bench_Servers(i), Bench_Servers(i)\MonitorNode) + Bench_Fail("Can't connect the monitor to '" + Bench_Servers(i)\Name + "'") + EndIf + Next + + Bench_PusherCount = 0 + For i = 0 To Bench_ServerCount - 1 + Bench_PusherCount + Bench_Servers(i)\NodeCount + Next + If Bench_PusherCount > 0 + Dim Bench_Pushers.BenchPusher(Bench_PusherCount - 1) + EndIf + n = 0 + For i = 0 To Bench_ServerCount - 1 + For Node = Bench_Servers(i)\FirstNode To Bench_Servers(i)\FirstNode + Bench_Servers(i)\NodeCount - 1 + Bench_Pushers(n)\ServerIndex = i + Bench_Pushers(n)\NodeId = Node + Bench_Pushers(n)\ThreadId = CreateThread(@Bench_PusherThread(), @Bench_Pushers(n)) + If Not Bench_Pushers(n)\ThreadId + Bench_Fail("Can't start a pusher thread") + EndIf + n + 1 + Next + Next + + Bench_LoadQueries(Bench_QueryFile, Bench_LoadStats()) + If ListSize(Bench_LoadStats()) > 0 + For i = 0 To Bench_ServerCount - 1 + If Bench_Servers(i)\QueryLoad + QueryThread = CreateThread(@Bench_QueryLoadThread(), 0) + Break + EndIf + Next + EndIf + + ; Wait for every pusher to be connected. + Repeat + Connected = 0 + For i = 0 To Bench_PusherCount - 1 + If Bench_Pushers(i)\Ready + Connected + 1 + EndIf + Next + If Connected = Bench_PusherCount + Break + EndIf + Delay(10) + ForEver + For i = 0 To Bench_PusherCount - 1 + If Bench_Pushers(i)\ConnectFailed + ConnectFailures + 1 + EndIf + Next + PrintN("[Bench] " + Str(Bench_PusherCount - ConnectFailures) + "/" + Str(Bench_PusherCount) + " pushers connected, pushing for " + Str(Bench_PushSeconds) + " s at " + StrD(Bench_Rate, 1) + " msg/s each") + + ; Baseline, then go. + Bench_StartMs = Bench_NowMs() + Bench_Sample("start") + For i = 0 To Bench_ServerCount - 1 + Bench_Servers(i)\PresentAtPushStart = Bench_Servers(i)\Present + Next + Bench_StartMs = Bench_NowMs() + Bench_LastPushed = 0 + Bench_PushStarted = #True + + NextSampleMs = Bench_StartMs + Bench_SampleMs + While Bench_NowMs() - Bench_StartMs < Bench_PushSeconds * 1000.0 + If Bench_NowMs() >= NextSampleMs + Bench_Sample("push") + NextSampleMs + Bench_SampleMs + EndIf + Delay(5) + Wend + Bench_StopPush = #True + PushEndMs = Bench_NowMs() + For i = 0 To Bench_PusherCount - 1 + If Bench_Pushers(i)\ThreadId + WaitThread(Bench_Pushers(i)\ThreadId) + EndIf + Next + If QueryThread + WaitThread(QueryThread) + EndIf + PushMs = Bench_NowMs() - Bench_StartMs + Pushed = Bench_TotalPushed() + PushRate = Pushed * 1000.0 / PushMs + PrintN("[Bench] Pushed " + Str(Pushed) + " in " + StrD(PushMs / 1000.0, 1) + " s (" + StrD(PushRate, 1) + " msg/s), draining") + + ; Drain + TotalLag = Bench_Sample("push-end") + DrainMs = -1 + If TotalLag = 0 + DrainMs = Bench_NowMs() - PushEndMs + Else + NextSampleMs = Bench_NowMs() + Bench_DrainSampleMs + While Bench_NowMs() - PushEndMs < Bench_DrainTimeout * 1000.0 + If Bench_NowMs() >= NextSampleMs + TotalLag = Bench_Sample("drain") + If TotalLag = 0 + DrainMs = Bench_NowMs() - PushEndMs + Break + EndIf + NextSampleMs + Bench_DrainSampleMs + EndIf + Delay(5) + Wend + EndIf + CloseFile(Bench_CsvFile) + + If DrainMs >= 0 + PrintN("[Bench] Drained in " + StrD(DrainMs / 1000.0, 2) + " s") + Else + PrintN("[Bench] NOT drained after " + Str(Bench_DrainTimeout) + " s, " + Str(TotalLag) + " messages still missing") + EndIf + + ; Summary + For i = 0 To Bench_PusherCount - 1 + Failed + Bench_Pushers(i)\Failed + Reconnects + Bench_Pushers(i)\Reconnects + ForEach Bench_Pushers(i)\LatencyMs() + AddElement(AllLatencies()) + AllLatencies() = Bench_Pushers(i)\LatencyMs() + Next + If Bench_Pushers(i)\LastError <> "" + Errors(Bench_Pushers(i)\LastError) + 1 + EndIf + Next + + JsonId = CreateJSON(#PB_Any) + *Root = SetJSONObject(JSONValue(JsonId)) + SetJSONDouble(AddJSONMember(*Root, "Rate"), Bench_Rate) + SetJSONInteger(AddJSONMember(*Root, "Pushers"), Bench_PusherCount) + SetJSONInteger(AddJSONMember(*Root, "ConnectFailures"), ConnectFailures) + SetJSONInteger(AddJSONMember(*Root, "MessageSize"), Bench_MessageSize) + SetJSONDouble(AddJSONMember(*Root, "PushSeconds"), PushMs / 1000.0) + SetJSONDouble(AddJSONMember(*Root, "OfferedRate"), Bench_Rate * Bench_PusherCount) + SetJSONInteger(AddJSONMember(*Root, "Pushed"), Pushed) + SetJSONInteger(AddJSONMember(*Root, "Failed"), Failed) + SetJSONInteger(AddJSONMember(*Root, "Reconnects"), Reconnects) + SetJSONDouble(AddJSONMember(*Root, "PushRate"), PushRate) + Bench_AddLatencyStats(*Root, "Push", AllLatencies()) + SetJSONDouble(AddJSONMember(*Root, "DrainSeconds"), DrainMs / 1000.0) + SetJSONBoolean(AddJSONMember(*Root, "Drained"), Bool(DrainMs >= 0)) + SetJSONInteger(AddJSONMember(*Root, "LagAtTimeout"), TotalLag) + SetJSONInteger(AddJSONMember(*Root, "CpuCount"), Bench_CpuCount) + SetJSONDouble(AddJSONMember(*Root, "CyclesPerMs"), Bench_CyclesPerMs) + If Bench_SystemCpuCount > 0 + SetJSONDouble(AddJSONMember(*Root, "SystemCpuAvg"), Bench_SystemCpuSum / Bench_SystemCpuCount) + SetJSONDouble(AddJSONMember(*Root, "BenchCpuAvg"), Bench_SelfCpuSum / Bench_SelfCpuCount) + Else + SetJSONDouble(AddJSONMember(*Root, "SystemCpuAvg"), 0) + SetJSONDouble(AddJSONMember(*Root, "BenchCpuAvg"), 0) + EndIf + SetJSONDouble(AddJSONMember(*Root, "SystemCpuMax"), Bench_SystemCpuMax) + + *Errors = SetJSONObject(AddJSONMember(*Root, "Errors")) + ForEach Errors() + SetJSONInteger(AddJSONMember(*Errors, MapKey(Errors())), Errors()) + Next + + *Servers = SetJSONArray(AddJSONMember(*Root, "Servers")) + For i = 0 To Bench_ServerCount - 1 + With Bench_Servers(i) + *Server = SetJSONObject(AddJSONElement(*Servers)) + SetJSONString(AddJSONMember(*Server, "Name"), \Name) + SetJSONInteger(AddJSONMember(*Server, "Nodes"), \NodeCount) + SetJSONInteger(AddJSONMember(*Server, "Rows"), \Present) + SetJSONDouble(AddJSONMember(*Server, "ReceiveRate"), (\Present - \PresentAtPushStart) * 1000.0 / PushMs) + If \CpuCountPush > 0 + SetJSONDouble(AddJSONMember(*Server, "CpuAvgPush"), \CpuSumPush / \CpuCountPush) + Else + SetJSONDouble(AddJSONMember(*Server, "CpuAvgPush"), 0) + EndIf + SetJSONDouble(AddJSONMember(*Server, "CpuMaxPush"), \CpuMaxPush) + If \CpuCountDrain > 0 + SetJSONDouble(AddJSONMember(*Server, "CpuAvgDrain"), \CpuSumDrain / \CpuCountDrain) + Else + SetJSONDouble(AddJSONMember(*Server, "CpuAvgDrain"), 0) + EndIf + SetJSONDouble(AddJSONMember(*Server, "WorkingSetMaxMb"), \WorkingSetMaxMb) + SetJSONDouble(AddJSONMember(*Server, "PrivateMaxMb"), \PrivateMaxMb) + SetJSONDouble(AddJSONMember(*Server, "DbMb"), \DbMb) + SetJSONInteger(AddJSONMember(*Server, "LagMaxPush"), \LagMaxPush) + ; How many seconds of pushes that was. + If PushRate > 0 + SetJSONDouble(AddJSONMember(*Server, "LagMaxSeconds"), \LagMaxPush / PushRate) + Else + SetJSONDouble(AddJSONMember(*Server, "LagMaxSeconds"), 0) + EndIf + SetJSONInteger(AddJSONMember(*Server, "LagAtPushEnd"), \LagAtPushEnd) + ; Messages per second it falls further behind, over the push's + ; second half. ~0 keeps up, > 0 doesn't. + SetJSONDouble(AddJSONMember(*Server, "LagSlope"), Bench_TroughSlope(\PushLag(), @Trough)) + SetJSONInteger(AddJSONMember(*Server, "LagTroughLast"), Trough\q) + If \MonitorCount > 0 + SetJSONDouble(AddJSONMember(*Server, "MonitorAvgMs"), \MonitorSumMs / \MonitorCount) + Else + SetJSONDouble(AddJSONMember(*Server, "MonitorAvgMs"), 0) + EndIf + SetJSONDouble(AddJSONMember(*Server, "MonitorMaxMs"), \MonitorMaxMs) + SetJSONInteger(AddJSONMember(*Server, "MonitorFailures"), \MonitorFailures) + EndWith + Next + + *Queries = SetJSONArray(AddJSONMember(*Root, "QueriesUnderLoad")) + ForEach Bench_LoadStats() + *Query = SetJSONObject(AddJSONElement(*Queries)) + SetJSONString(AddJSONMember(*Query, "Name"), Bench_LoadStats()\Name) + Bench_AddLatencyStats(*Query, "", Bench_LoadStats()\LatencyMs()) + SetJSONInteger(AddJSONMember(*Query, "Failures"), Bench_LoadStats()\Failures) + SetJSONString(AddJSONMember(*Query, "LastError"), Bench_LoadStats()\LastError) + Next + + If Not SaveJSON(JsonId, Bench_SummaryOut, #PB_JSON_PrettyPrint) + Bench_Fail("Can't write '" + Bench_SummaryOut + "'") + EndIf + FreeJSON(JsonId) + + For i = 0 To Bench_ServerCount - 1 + BakaShrot_Outbound_Close(@Bench_Servers(i)\Monitor, #BakaShrot_ConnectionStatus_Disconnected) + If Bench_Servers(i)\Process + CloseHandle_(Bench_Servers(i)\Process) + EndIf + Next +EndProcedure + + +; --- query ------------------------------------------------------------------- + +Procedure Bench_Query() + Protected NewList Queries.BenchQueryStats() + Protected i.i, r.i, Sql.s, Ms.Double, Bytes.Integer, Result.String, Error.String, Ok.i, Rows.i + Protected JsonId.i, *Root, *Entry, LastBytes.i + + Bench_LoadQueries(Bench_QueryFile, Queries()) + If ListSize(Queries()) = 0 + Bench_Fail("No queries in '" + Bench_QueryFile + "'") + EndIf + + JsonId = CreateJSON(#PB_Any) + *Root = SetJSONArray(JSONValue(JsonId)) + + For i = 0 To Bench_ServerCount - 1 + With Bench_Servers(i) + If Not \Query + Continue + EndIf + ForEach Queries() + ClearList(Queries()\LatencyMs()) + Queries()\Failures = 0 + Queries()\LastError = "" + Rows = -1 + LastBytes = 0 + Sql = Bench_ExpandSql(Queries()\Sql, @Bench_Servers(i)) + + ; Warm-up, also gives the row count. + Ok = Bench_RunQuery(@\Monitor, @Bench_Servers(i), \QueryNode, Sql, \FirstNode, @Ms, @Bytes, @Result, @Error) + If Ok + Rows = Bench_CountRows(Result\s) + LastBytes = Bytes\i + For r = 1 To Bench_QueryRepeats + If Bench_RunQuery(@\Monitor, @Bench_Servers(i), \QueryNode, Sql, \FirstNode, @Ms, @Bytes, @Result, @Error) + AddElement(Queries()\LatencyMs()) + Queries()\LatencyMs() = Ms\d + Else + Queries()\Failures + 1 + Queries()\LastError = Error\s + EndIf + Next + Else + Queries()\Failures + 1 + Queries()\LastError = Error\s + EndIf + + *Entry = SetJSONObject(AddJSONElement(*Root)) + SetJSONString(AddJSONMember(*Entry, "Server"), \Name) + SetJSONString(AddJSONMember(*Entry, "Name"), Queries()\Name) + Bench_AddLatencyStats(*Entry, "", Queries()\LatencyMs()) + SetJSONInteger(AddJSONMember(*Entry, "Rows"), Rows) + SetJSONInteger(AddJSONMember(*Entry, "Bytes"), LastBytes) + SetJSONInteger(AddJSONMember(*Entry, "Failures"), Queries()\Failures) + SetJSONString(AddJSONMember(*Entry, "LastError"), Queries()\LastError) + If ListSize(Queries()\LatencyMs()) > 0 + LastElement(Queries()\LatencyMs()) + PrintN("[Bench] " + \Name + " " + Queries()\Name + ": " + StrD(Queries()\LatencyMs(), 1) + " ms (last), " + Str(Rows) + " rows") + Else + PrintN("[Bench] " + \Name + " " + Queries()\Name + ": FAILED " + Queries()\LastError) + EndIf + Next + BakaShrot_Outbound_Close(@\Monitor, #BakaShrot_ConnectionStatus_Disconnected) + EndWith + Next + + If Not SaveJSON(JsonId, Bench_QueryOut, #PB_JSON_PrettyPrint) + Bench_Fail("Can't write '" + Bench_QueryOut + "'") + EndIf + FreeJSON(JsonId) +EndProcedure + + +; --- Main -------------------------------------------------------------------- + +Define Mode.s + +OpenConsole() + +If CountProgramParameters() < 2 + PrintN("Usage: BenchClient ") + End 1 +EndIf +Mode = LCase(ProgramParameter(0)) + +QueryPerformanceFrequency_(@Bench_QpcFrequency) +; Delay(1) closer to 1 ms, for the pacing. +timeBeginPeriod_(1) + +CompilerIf #PB_Compiler_Version < 600 + InitNetwork() +CompilerEndIf +If Not InitCryptography() + Bench_Fail("Can't initialize libsodium") +EndIf + +Bench_LoadPlan(ProgramParameter(1)) + +Select Mode + Case "run" + Bench_Run() + Case "query" + Bench_Query() + Default + Bench_Fail("Unknown mode '" + Mode + "'") +EndSelect + +timeEndPeriod_(1) +End 0 diff --git a/Tests/Bench/BenchSeed.pb b/Tests/Bench/BenchSeed.pb new file mode 100644 index 0000000..40f296c --- /dev/null +++ b/Tests/Bench/BenchSeed.pb @@ -0,0 +1,181 @@ +; ============================================================================ +; BakaShrot Bench Seed +; +; Usage: BenchSeed [Db...] +; Nodes Node ids, "101-110,201-210". +; +; Adds RowsPerNode messages to every node, identical in every database, so +; servers that were in sync stay in sync without replicating anything: a +; quick way to get millions of rows for the query and check-in benchmarks. +; Each node continues from the highest message id any database has for it, +; and INSERT OR IGNORE keeps what's already there. +; Nodes go by name ("n" + id, like Bench-Replication.ps1 names them): each +; database stores a node under its own id for that name, and gets the name +; (origin "peer", as if a peer had sent it) if it doesn't have it yet, so +; servers that take nodes by wildcard (-Names Wildcard) see them as known. +; The servers must be stopped. Same JSON as BenchClient's pushes. +; +; Used by Tests/Bench/Bench-Replication.ps1, compile as a console program. +; ============================================================================ + +EnableExplicit + +XIncludeFile "../../Server/Storage/Storage.pbi" + + +#Seed_BatchSize = 50000 + + +; The id DbId has for node "n", given that name if it has none yet. +; Returns -1 on failure. +Procedure.i Seed_LocalNode(DbId.i, Node.i) + Protected Name.s = "n" + Str(Node), Id.i = -1 + + SetDatabaseString(DbId, 0, Name) + If DatabaseQuery(DbId, "SELECT node_id FROM nodes WHERE name = ?") + If NextDatabaseRow(DbId) + Id = GetDatabaseLong(DbId, 0) + EndIf + FinishDatabaseQuery(DbId) + EndIf + If Id >= 0 + ProcedureReturn Id + EndIf + + ; Its own id, unless something else is named there. + SetDatabaseLong(DbId, 0, Node) + SetDatabaseString(DbId, 1, Name) + If Not DatabaseUpdate(DbId, "INSERT INTO nodes (node_id, name, origin) VALUES (?, ?, 'peer') " + + "ON CONFLICT (node_id) DO UPDATE SET name = excluded.name, origin = 'peer' WHERE origin = 'id'") + ProcedureReturn -1 + EndIf + SetDatabaseString(DbId, 0, Name) + If DatabaseQuery(DbId, "SELECT node_id FROM nodes WHERE name = ?") + If NextDatabaseRow(DbId) + Id = GetDatabaseLong(DbId, 0) + EndIf + FinishDatabaseQuery(DbId) + EndIf + ProcedureReturn Id +EndProcedure + + +Procedure.s Seed_Json(NodeId.i, Seq.q, Pad.s) + Protected Kind.s, Value.i + + If Seq % 50 = 0 + Kind = "alert" + Else + Select Seq % 4 + Case 0 : Kind = "temp" + Case 1 : Kind = "humidity" + Case 2 : Kind = "pressure" + Default : Kind = "status" + EndSelect + EndIf + Value = (Seq * 7919 + NodeId) % 10000 + ProcedureReturn ~"{\"kind\":\"" + Kind + ~"\",\"node\":" + Str(NodeId) + ~",\"seq\":" + Str(Seq) + + ~",\"value\":" + StrD(Value / 100.0, 2) + ~",\"ts\":" + Str(1700000000 + Seq) + + ~",\"pad\":\"" + Pad + ~"\"}" +EndProcedure + + +Define TopicId.i, NodesSpec.s, RowsPerNode.i, MessageSize.i, Pad.s +Define NewList Nodes.i(), NewList Dbs.i() +Define i.i, Part.s, First.i, Last.i, Node.i, StartId.q, Id.q, MaxId.q, Count.q, StartMs.i, Total.q, d.i +Define Dim LocalIds.i(0) + +OpenConsole() + +If CountProgramParameters() < 5 + PrintN("Usage: BenchSeed [Db...]") + End 1 +EndIf + +TopicId = Val(ProgramParameter(0)) +NodesSpec = ProgramParameter(1) +RowsPerNode = Val(ProgramParameter(2)) +MessageSize = Val(ProgramParameter(3)) +If MessageSize > 90 + Pad = LSet("", MessageSize - 90, "x") +EndIf + +For i = 1 To CountString(NodesSpec, ",") + 1 + Part = Trim(StringField(NodesSpec, i, ",")) + If Part = "" + Continue + EndIf + If FindString(Part, "-") + First = Val(StringField(Part, 1, "-")) + Last = Val(StringField(Part, 2, "-")) + Else + First = Val(Part) + Last = First + EndIf + For Node = First To Last + AddElement(Nodes()) + Nodes() = Node + Next +Next + +For i = 4 To CountProgramParameters() - 1 + AddElement(Dbs()) + Dbs() = OpenStorageDatabase(ProgramParameter(i)) + If Not Dbs() Or Not SetupStorageDatabase(Dbs()) + PrintN("Can't open '" + ProgramParameter(i) + "': " + DatabaseError()) + End 1 + EndIf +Next + +StartMs = ElapsedMilliseconds() +ReDim LocalIds(ListSize(Dbs()) - 1) +ForEach Nodes() + ; Where every database is at for this node, continue after the furthest. + StartId = 0 + d = 0 + ForEach Dbs() + LocalIds(d) = Seed_LocalNode(Dbs(), Nodes()) + If LocalIds(d) < 0 + PrintN("Can't name node " + Str(Nodes()) + ": " + DatabaseError()) + End 1 + EndIf + MaxId = GetLatestMessageId(Dbs(), TopicId, LocalIds(d)) + If MaxId > StartId + StartId = MaxId + EndIf + d + 1 + Next + + d = -1 + ForEach Dbs() + d + 1 + Id = StartId + While Id < StartId + RowsPerNode + If Not DatabaseUpdate(Dbs(), "BEGIN IMMEDIATE") + PrintN("BEGIN failed: " + DatabaseError()) + End 1 + EndIf + Count = 0 + While Count < #Seed_BatchSize And Id < StartId + RowsPerNode + Id + 1 + Count + 1 + If Not InsertReplicatedMessage(Dbs(), TopicId, LocalIds(d), Id, Seed_Json(Nodes(), Id, Pad)) + PrintN("Insert failed: " + DatabaseError()) + End 1 + EndIf + Wend + If Not DatabaseUpdate(Dbs(), "COMMIT") + PrintN("COMMIT failed: " + DatabaseError()) + End 1 + EndIf + Total + Count + Wend + Next +Next + +ForEach Dbs() + CloseDatabase(Dbs()) +Next + +PrintN("Seeded " + Str(Total) + " rows (" + Str(RowsPerNode) + " per node, " + Str(ListSize(Nodes())) + " nodes, " + Str(ListSize(Dbs())) + " databases) in " + StrD((ElapsedMilliseconds() - StartMs) / 1000.0, 1) + " s") +End 0 diff --git a/Tests/Bench/BenchServer.pb b/Tests/Bench/BenchServer.pb new file mode 100644 index 0000000..f458de5 --- /dev/null +++ b/Tests/Bench/BenchServer.pb @@ -0,0 +1,58 @@ +; ============================================================================ +; BakaShrot Bench Server +; +; Usage: BenchServer +; +; The real server (Server/Root.pbi), without the console commands: it runs +; until StopFile exists, then stops its workers cleanly and exits. +; BakaShrot_Server.exe can't run headless, with no console input its +; Input() returns Chr(4) and it stops right away, see Notes.md. +; +; Used by Tests/Bench/Bench-Replication.ps1, compile as a thread-safe console +; program. +; ============================================================================ + +EnableExplicit + +XIncludeFile "../../Server/Root.pbi" + + +Define Root.BakaShrot_Root +Define StopFile.s + +OpenConsole("BakaShrot Bench Server") + +If CountProgramParameters() < 2 + PrintN("Usage: BenchServer ") + End 1 +EndIf + +Root\ConfigPath = ProgramParameter(0) +StopFile = ProgramParameter(1) + +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 until '" + StopFile + "' exists.") + +While FileSize(StopFile) < 0 + Delay(200) +Wend + +PrintN("Stopping...") +BakaShrot_Root_StopWorkers(@Root) +BakaShrot_Root_CloseDatabase(@Root) +FreeConfig(Root\Config) +End 0 diff --git a/Tests/Bench/Compare-Runs.ps1 b/Tests/Bench/Compare-Runs.ps1 new file mode 100644 index 0000000..54672b2 --- /dev/null +++ b/Tests/Bench/Compare-Runs.ps1 @@ -0,0 +1,106 @@ +# ============================================================================ +# Compares runs of Bench-Replication.ps1 side by side, as a markdown table. +# +# Usage: +# powershell -ExecutionPolicy Bypass -File Tests\Bench\Compare-Runs.ps1 ` +# -Runs "Build\Bench\runs\20261107-123413,Build\Bench\runs\20261107-125334" ` +# -Labels "Before,WAL + wake-ups" [-Out comparison.md] +# +# Picks the key numbers of each run's results.json: the push ceilings, the +# latencies, replication lag and drain, CPU and RAM, the queries at the +# biggest data size, and the mixed stage. Stages missing from a run show "-". +# ============================================================================ + +param( + [Parameter(Mandatory = $true)] [string[]]$Runs, + [string[]]$Labels = @(), + [string]$Out = "" +) + +$ErrorActionPreference = "Stop" + +# "powershell -File" passes "a,b" as one string. +$Runs = @($Runs | ForEach-Object { $_ -split "," } | ForEach-Object { $_.Trim() } | Where-Object { $_ }) +$Labels = @($Labels | ForEach-Object { $_ -split "," } | ForEach-Object { $_.Trim() } | Where-Object { $_ }) + +$Culture = [Globalization.CultureInfo]::InvariantCulture + +function Format-Num($Value, $Decimals = 0) { + if ($null -eq $Value) { return "-" } + return ([double]$Value).ToString("N$Decimals", $Culture) +} + +$Data = @() +for ($i = 0; $i -lt $Runs.Count; $i++) { + $Json = Get-Content (Join-Path $Runs[$i] "results.json") -Raw | ConvertFrom-Json + $Label = if ($i -lt $Labels.Count) { $Labels[$i] } else { Split-Path $Runs[$i] -Leaf } + $Data += [pscustomobject]@{ Label = $Label; Results = @($Json.Results); Queries = @($Json.Queries) } +} + +# A stage by the end of its name ("5x0" matches "ramp05-5x0"). +function Get-Stage($Run, $Suffix) { + return $Run.Results | Where-Object { $_.Stage -like "*$Suffix" } | Select-Object -First 1 +} + +function Get-Max($Stage, $Property) { + if (-not $Stage) { return $null } + return ($Stage.Servers | Measure-Object -Property $Property -Maximum).Maximum +} + +function Get-Avg($Stage, $Property) { + if (-not $Stage) { return $null } + return ($Stage.Servers | Measure-Object -Property $Property -Average).Average +} + +# Median of a query on the first server, in the last stage that ran it. +function Get-Query($Run, $Name) { + $Q = $Run.Queries | Where-Object { $_.Name -eq $Name -and $_.Server -eq $Run.Results[0].Servers[0].Name } | Select-Object -Last 1 + if (-not $Q -or $Q.Count -eq 0) { return $null } + return $Q.P50Ms +} + +function Get-LoadQuery($Run, $Name) { + $Mixed = Get-Stage $Run "mixed" + if (-not $Mixed) { return $null } + $Q = $Mixed.QueriesUnderLoad | Where-Object Name -eq $Name | Select-Object -First 1 + if (-not $Q) { return $null } + return $Q.P50Ms +} + +$Rows = @( + @("**Push ceiling**, msg/s, 5 nodes/server", { param($R) Format-Num (Get-Stage $R "5x0").PushRate }), + @("**Push ceiling**, msg/s, 10 nodes/server", { param($R) Format-Num (Get-Stage $R "10x0").PushRate }), + @("Pushed of 2,000 offered (10 x 50)", { param($R) Format-Num (Get-Stage $R "10x50").PushRate }), + @("Pushed of 4,000 offered (10 x 100)", { param($R) Format-Num (Get-Stage $R "10x100").PushRate }), + @("Push p50 / p99 ms, 10 x 50", { param($R) $S = Get-Stage $R "10x50"; if ($S) { "$(Format-Num $S.PushP50Ms 1) / $(Format-Num $S.PushP99Ms 1)" } else { "-" } }), + @("Push p50 / p99 / max ms, flat out (10 nodes)", { param($R) $S = Get-Stage $R "10x0"; if ($S) { "$(Format-Num $S.PushP50Ms 1) / $(Format-Num $S.PushP99Ms 1) / $(Format-Num $S.PushMaxMs)" } else { "-" } }), + @("Replication lag, s of pushes, flat out", { param($R) Format-Num (Get-Max (Get-Stage $R "10x0") "LagMaxSeconds") 1 }), + @("Drain after the push, s, flat out", { param($R) Format-Num (Get-Stage $R "10x0").DrainSeconds 1 }), + @("Server CPU, % of a core, flat out (avg of the 4)", { param($R) Format-Num (Get-Avg (Get-Stage $R "10x0") "CpuAvgPush") }), + @("Machine CPU %, flat out", { param($R) Format-Num (Get-Stage $R "10x0").SystemCpuAvg }), + @("Hub RAM, working set MB, max", { param($R) Format-Num (($R.Results | ForEach-Object { $_.Servers[0].WorkingSetMaxMb } | Measure-Object -Maximum).Maximum) 1 }), + @("Rows per server at the end", { param($R) Format-Num $R.Results[-1].Servers[0].Rows }), + @("Query: latest message, ms (1M rows)", { param($R) Format-Num (Get-Query $R "latest_message") 1 }), + @("Query: last 50 of a node, ms", { param($R) Format-Num (Get-Query $R "last_50_of_node") 1 }), + @("Query: sync state (GROUP BY all), ms", { param($R) Format-Num (Get-Query $R "sync_state") 1 }), + @("Query: sync state from node_heads (what check-ins use now), ms", { param($R) Format-Num (Get-Query $R "sync_state_heads") 1 }), + @("Query: JSON count over all rows, ms", { param($R) Format-Num (Get-Query $R "json_count_all") 1 }), + @("Query: JSON aggregate over all rows, ms", { param($R) Format-Num (Get-Query $R "json_agg_all") 1 }), + @("**Mixed:** pushed of 400 msg/s with a query loop", { param($R) Format-Num (Get-Stage $R "mixed").PushRate }), + @("Mixed: push p99 / max ms", { param($R) $S = Get-Stage $R "mixed"; if ($S) { "$(Format-Num $S.PushP99Ms 1) / $(Format-Num $S.PushMaxMs)" } else { "-" } }), + @("Mixed: failed pushes", { param($R) $S = Get-Stage $R "mixed"; if ($S) { $S.Failed } else { "-" } }), + @("Mixed: JSON count over all rows, ms, under load", { param($R) Format-Num (Get-LoadQuery $R "json_count_all") 1 }), + @("Mixed: latest message, ms, under load", { param($R) Format-Num (Get-LoadQuery $R "latest_message") 1 }) +) + +$Lines = @() +$Lines += "| | " + (($Data | ForEach-Object { $_.Label }) -join " | ") + " |" +$Lines += "|---|" + (($Data | ForEach-Object { "---" }) -join "|") + "|" +foreach ($Row in $Rows) { + $Cells = foreach ($Run in $Data) { & $Row[1] $Run } + $Lines += "| $($Row[0]) | " + ($Cells -join " | ") + " |" +} + +$Text = $Lines -join "`r`n" +if ($Out) { Set-Content -Path $Out -Value $Text -Encoding UTF8 } +$Text diff --git a/Tests/Bench/Results-2026-11-07.md b/Tests/Bench/Results-2026-11-07.md new file mode 100644 index 0000000..cad5af3 --- /dev/null +++ b/Tests/Bench/Results-2026-11-07.md @@ -0,0 +1,182 @@ +# Benchmark results, 2026-11-07 + +`Bench-Replication.ps1` with its defaults: 4 servers in a Y (a hub linked to +3 leaves), 5-10 nodes pushing to each, ~200-byte JSON messages, 30 s per +stage, `PeerSyncInterval = 5`, `PeerBatchSize = 100`. All on one machine +(i5-13500, 16 GB, NVMe), PureBasic 5.73 x64 unless said otherwise, SQLite +3.54.1. Table made with `Compare-Runs.ps1`. + +| Version | What changed | +|---|---| +| Before | Rollback journal, a sync to disk per push, every wait a `Delay(5)` / `Delay(1)` loop | +| WAL + wake-ups | WAL with `synchronous = NORMAL`, threads woken by an event / `select()`, a write mutex instead of SQLite's busy-wait | +| + grouping | Pushes arriving together share one transaction (group commit) | +| + no per-push log | The `PrintN()` per push / read / query removed (`#BakaShrot_Net_LogRequests`) | +| + prepared/cache/checkpoints/heads | One writer connection with prepared statements (SQLite's own API), next ids cached in memory, WAL checkpoints in a background thread, the sync state from `node_heads` (`Server/Storage/Writer.pbi`) | +| same on PB 6.40 C | The same code, built with PureBasic 6.40's C backend and `/OPTIMIZER` (the load generator too) | + +| | Before | WAL + wake-ups | + grouping | + no per-push log | + prepared/cache/checkpoints/heads (5.73) | same on PB 6.40 C | +|---|---|---|---|---|---|---| +| **Push ceiling**, msg/s, 5 nodes/server | 958 | 5,771 | 5,709 | 25,681 | 33,522 | 37,162 | +| **Push ceiling**, msg/s, 10 nodes/server | 904 | 5,726 | 5,814 | 25,707 | 34,345 | 38,358 | +| Pushed of 2,000 offered (10 x 50) | 924 | 1,999 | 2,000 | 2,000 | 2,000 | 1,999 | +| Pushed of 4,000 offered (10 x 100) | 899 | 4,000 | 4,000 | 4,000 | 4,000 | 4,000 | +| Push p50 / p99 ms, 10 x 50 | 18.0 / 491.5 | 0.4 / 5.1 | 0.5 / 7.2 | 0.5 / 13.6 | 0.3 / 0.8 | 0.2 / 0.9 | +| Push p50 / p99 / max ms, flat out (10 nodes) | 18.0 / 574.9 / 2,642 | 5.5 / 25.2 / 193 | 5.6 / 23.1 / 56 | 0.9 / 16.5 / 149 | 0.5 / 2.8 / 854 | 0.5 / 2.5 / 1,485 | +| Replication lag, s of pushes, flat out | 8.9 | 5.1 | 5.0 | 8.9 | 9.9 | 8.3 | +| Drain after the push, s, flat out | 6.2 | 5.8 | 5.8 | 10.3 | 11.3 | 11.3 | +| Server CPU, % of a core, flat out (avg of the 4) | 45 | 65 | 66 | 130 | 120 | 121 | +| Machine CPU %, flat out | 41 | 33 | 34 | 67 | 65 | 65 | +| Hub RAM, working set MB, max | 34.6 | 42.9 | 44.6 | 45.2 | 38.8 | 40.1 | +| Rows per server at the end | 1,021,883 | 1,024,025 | 1,024,025 | 1,887,117 | 2,389,201 | 2,619,806 | +| Query: latest message, ms (1M rows) | 5.9 | 0.5 | 0.5 | 0.1 | 0.1 | 0.1 | +| Query: last 50 of a node, ms | 5.8 | 1.0 | 1.0 | 0.7 | 0.8 | 0.7 | +| Query: sync state (GROUP BY all), ms | 78.0 | 73.1 | 72.1 | 131.9 | 166.7 | 184.1 | +| Query: sync state from node_heads (what check-ins use now), ms | - | - | - | - | 0.6 | 0.5 | +| Query: JSON count over all rows, ms | 473.6 | 475.1 | 475.3 | 857.5 | 1,080.7 | 1,199.4 | +| Query: JSON aggregate over all rows, ms | 1,647.8 | 1,575.8 | 1,533.9 | 2,800.2 | 3,974.2 | 4,371.2 | +| **Mixed:** pushed of 400 msg/s with a query loop | 323 | 396 | 397 | 397 | 392 | 396 | +| Mixed: push p99 / max ms | 820.2 / 5,119 | 0.7 / 17 | 7.9 / 17 | 18.0 / 30 | 1.2 / 17 | 0.9 / 17 | +| Mixed: failed pushes | 1 | 0 | 0 | 0 | 0 | 0 | +| Mixed: JSON count over all rows, ms, under load | 545.4 | 502.3 | 506.5 | 925.0 | 1,148.2 | 1,265.6 | +| Mixed: latest message, ms, under load | 12.0 | 0.2 | 0.2 | 0.1 | 0.2 | 0.2 | + +The full-table scans grow with the data, and the later runs' flat-out stages +wrote more of it: 1.9M, 2.4M, then 2.6M rows per server instead of ~1.02M. +Per row they cost the same (~0.45 ms per 1,000 rows for the JSON count). +PB 6.40 doesn't change them either, SQLite does the scanning. + +## What limited each version + +- **Before:** the sync to disk on every push, ~250 commits/s per database. +- **WAL + wake-ups:** not the database anymore. The `PrintN()` logging every + push takes ~0.4 ms and serializes every thread behind it: ~2,400 pushes/s + per server whatever the number of nodes, with the server mostly idle + (measured on a single server: the listener asleep in `select()` 91 % of + the time, the writes busy 33 %, 0.14 ms per push). +- **+ grouping:** same cap, so no gain yet: the pushes never piled up + behind the write mutex (1.0 per transaction on average). It did cut the + worst push from 193 to 56 ms. +- **+ no per-push log:** a single server went from ~2,400 to ~12,000 + pushes/s, and grouping now kicks in: 2.5 pushes per transaction at 5 + nodes, ~5-9 at 10-20, the database busy 70-90 % of the time at 0.07-0.11 + ms per push. The cluster tops out at ~25,700 msg/s with the machine at + 67 % CPU (the load generator itself ~85 % of a core). Next limits: each + server's write section, and running everything on one machine. +- **+ prepared/cache/checkpoints/heads:** ~25,700 -> ~34,300 msg/s. A push + costs ~0.05 ms of write time instead of 0.07-0.11, no statement is + prepared again, no MAX() per push. The p99 at moderate load is back under + 1 ms (13.6 -> 0.8 ms at 10 x 50, 18 -> 1.2 ms in the mixed stage): the + checkpoints were what held the writes up. Flat out, the WAL grows faster + than the background checkpoints keep up with, so the writer checkpoints by + itself past 10,000 frames, and the worst push goes from 149 to 854 ms. The + sync state every check-in reads: 0.5 ms instead of a 167 ms GROUP BY. +- **Same on PB 6.40 C:** ~34,300 -> ~38,400 msg/s (+12 %), the same + latencies, slightly less lag. Both the servers and the load generator are + built with it, so part of it may be the generator. The SQLite side (the + write section, the queries) is the same DLL either way. + +## Notes + +- Ids checked after the last four runs: every node 1..N, no gap, no + duplicate, on all 4 servers, and `node_heads` exactly matching `data`. +- **p99 at moderate load went up with grouping** (0.7 -> 8-18 ms), and came + back down once the checkpoints left the write path (see above). +- Replication keeps up at every load: it drains within ~11 s even after + 38,000 msg/s. The lag is the check-in wait (`PeerSyncInterval`) plus the + hub relaying to its leaves, see `Design/Suggestions.md` #2 to lower it. +- The worst push flat out (0.85-1.5 s) is the writer's backstop checkpoint, + see `Design/Suggestions.md` #3. + +## Names and wildcards (evening) + +Same benchmark, PureBasic 5.73, after topics and nodes got names, strict +"named on both sides" replication, and wildcards, run with `-Names +Wildcard`: each server only names its own nodes, and takes everyone else's +by `AcceptNodes = n*`, so each server adds the other servers' 30 nodes +under ids of its own (counting down from 65535), and the hub relays them on +by name. The worst case for the new code: every batch goes through a name +lookup and every check-in through the patterns. Run `20261107-220433`, +compared with `Compare-Runs.ps1` (`comparison.md` in the run's folder). + +| | Before names (5.73) | Before names (PB 6.40 C) | Names + wildcards (5.73) | +|---|---|---|---| +| **Push ceiling**, msg/s, 5 nodes/server | 33,522 | 37,162 | 35,124 | +| **Push ceiling**, msg/s, 10 nodes/server | 34,345 | 38,358 | 32,846 | +| Push p50 / p99 ms, 10 x 50 | 0.3 / 0.8 | 0.2 / 0.9 | 0.3 / 1.1 | +| Push p50 / p99 / max ms, flat out (10 nodes) | 0.5 / 2.8 / 854 | 0.5 / 2.5 / 1,485 | 0.6 / 3.2 / 1,503 | +| Replication lag, s of pushes, flat out | 9.9 | 8.3 | 8.6 | +| Drain after the push, s, flat out | 11.3 | 11.3 | 11.8 | +| Server CPU, % of a core, flat out (avg of the 4) | 120 | 121 | 129 | +| Hub RAM, working set MB, max | 38.8 | 40.1 | 39.3 | +| Rows per server at the end | 2,389,201 | 2,619,806 | 2,395,509 | +| Query: sync state from node_heads, ms | 0.6 | 0.5 | 0.7 | +| Query: JSON count over all rows, ms | 1,080.7 | 1,199.4 | 1,105.8 | +| **Mixed:** pushed of 400 msg/s with a query loop | 392 | 396 | 397 | +| Mixed: push p99 / max ms | 1.2 / 17 | 0.9 / 17 | 0.9 / 18 | +| Failed pushes, refusals between servers | 0 | 0 | 0 | + +- **Same speed, within run-to-run noise.** Flat out at 10 nodes, the same + build gave 32,976 and 37,003 msg/s in two ramp-only runs (declared names) + earlier this evening: ±6 % between runs is usual on this machine. The push + path itself didn't change, only the check-ins and the batches' first + lines. +- **Server CPU +7 %** flat out (129 vs 120 % of a core), the name lookups + and the bigger sync states, possibly part of the noise too. +- **Replication** keeps up at every load and drains in the same time; no + batch refused anywhere, every server ended with the same rows. +- **Measuring changed slightly:** the lag monitor now asks for each node's + latest id by name through the `messages` view (ids differ between + servers in this mode), the old runs asked `data` by id. Both are index + lookups. + +## Big messages, no JSON check on push, is_json clause (2026-11-08) + +Same setup as the evening run (`-Names Wildcard`), after: packets up to +16 MB once authenticated (new inbox: growth by doubling, a read offset), +replication batches still ~64 KB, pushes no longer checked to be JSON +(`ParseJSON()` gone from the push path, `is_json` flags them), and +`is_json = 1` added to the JSON queries. + +| | Before names (5.73) | Before names (PB 6.40 C) | Names + wildcards (5.73) | Big messages, no JSON check, is_json clause (5.73) | +|---|---|---|---|---| +| **Push ceiling**, msg/s, 5 nodes/server | 33,522 | 37,162 | 35,124 | **38,199** | +| **Push ceiling**, msg/s, 10 nodes/server | 34,345 | 38,358 | 32,846 | **37,745** | +| Pushed of 2,000 offered (10 x 50) | 2,000 | 1,999 | 1,999 | 2,001 | +| Pushed of 4,000 offered (10 x 100) | 4,000 | 4,000 | 4,000 | 4,000 | +| Push p50 / p99 ms, 10 x 50 | 0.3 / 0.8 | 0.2 / 0.9 | 0.3 / 1.1 | 0.3 / 1.0 | +| Push p50 / p99 / max ms, flat out (10 nodes) | 0.5 / 2.8 / 854 | 0.5 / 2.5 / 1,485 | 0.6 / 3.2 / 1,503 | 0.5 / 2.9 / 822 | +| Replication lag, s of pushes, flat out | 9.9 | 8.3 | 8.6 | 10.5 | +| Drain after the push, s, flat out | 11.3 | 11.3 | 11.8 | 13.8 | +| Server CPU, % of a core, flat out (avg of the 4) | 120 | 121 | 129 | 120 | +| Machine CPU %, flat out | 65 | 65 | 69 | 66 | +| Hub RAM, working set MB, max | 38.8 | 40.1 | 39.3 | 42.8 | +| Rows per server at the end | 2,389,201 | 2,619,806 | 2,395,509 | 2,628,001 | +| Query: latest message, ms | 0.1 | 0.1 | 0.1 | 0.1 | +| Query: last 50 of a node, ms | 0.8 | 0.7 | 0.8 | 0.8 | +| Query: sync state (GROUP BY all), ms | 166.7 | 184.1 | 170.5 | 187.9 | +| Query: sync state from node_heads (what check-ins use now), ms | 0.6 | 0.5 | 0.7 | 0.6 | +| Query: JSON count over all rows, ms | 1,080.7 | 1,199.4 | 1,105.8 | 1,233.6 | +| Query: JSON aggregate over all rows, ms | 3,974.2 | 4,371.2 | 4,084.2 | 4,464.4 | +| Same, per million rows: sync state / JSON count / JSON aggregate, ms | 69.8 / 452 / 1,663 | 70.3 / 458 / 1,669 | 71.2 / 462 / 1,705 | 71.5 / 469 / 1,699 | +| **Mixed:** pushed of 400 msg/s with a query loop | 392 | 396 | 397 | 384 | +| Mixed: push p99 / max ms | 1.2 / 17 | 0.9 / 17 | 0.9 / 18 | 1.0 / 15 | +| Mixed: failed pushes | 0 | 0 | 0 | 0 | +| Mixed: JSON count over all rows, ms, under load | 1,148.2 | 1,265.6 | 1,179.5 | 1,313.4 | +| Mixed: latest message, ms, under load | 0.2 | 0.2 | 0.2 | 0.2 | + +Runs: `20261107-140556`, `20261107-141735`, `20261107-220433`, `20261108-033149` (all 4 servers in a Y, ~200-byte messages; the last two with `-Names Wildcard`). Query times are from the end of each run, so they scale with its row count: compare the per-million row. + +- **Push ceiling up 9-15 %** (38,199 / 37,745 msg/s), the best yet on 5.73, + for the same server CPU (120 % of a core). Likely mostly `ParseJSON()` + leaving the push path, though runs of one build have spread 33-37k. +- **Lag and drain** are a bit higher in seconds, with 15 % more messages + pushed per second to relay (397,066 messages behind at most, vs 282,621). +- **The `is_json = 1` clause costs nothing measurable:** per million rows, + the JSON count is 469 ms vs 462, the aggregate 1,699 vs 1,705. +- **Mixed: 384 of 400 msg/s pushed** (397 before), with no failures and a + lower p99. The bench's pushers are paced by its own loop, and this run's + database was 10 % bigger, so the query loop beside them was slower. Worth + a second run before reading anything into it. +- 0 refused, failed or "too big" in the server logs, 2,628,001 rows on all + 4 servers. diff --git a/Tests/Bench/queries.txt b/Tests/Bench/queries.txt new file mode 100644 index 0000000..674bb8e --- /dev/null +++ b/Tests/Bench/queries.txt @@ -0,0 +1,30 @@ +# Query suite, run by BenchClient's "query" mode after every stage, see +# Bench-Replication.ps1. One per line: Name | SQL +# {TOPIC} and {NODE} are replaced by the topic id and the server's first node. +# "@latest" is a GetLatestMessage of {NODE}, the regular read path. +# Results must fit in one packet (64 KB) and 10000 rows. +# +# The messages look like: +# {"kind":"temp","node":101,"seq":12,"value":42.17,"ts":1700000012,"pad":"xxx"} +# kind is "alert" for 1 in 50, the others are spread evenly. + +# Indexed, should stay flat as the data grows. +latest_message | @latest +last_50_of_node | SELECT message_id, message_data FROM data WHERE topic_id = {TOPIC} AND node_id = {NODE} ORDER BY message_id DESC LIMIT 50 +max_of_node | SELECT MAX(message_id) FROM data WHERE topic_id = {TOPIC} AND node_id = {NODE} +by_message_id | SELECT topic_id, node_id FROM data WHERE message_id = 100 +recent_global | SELECT topic_id, node_id, message_id FROM data ORDER BY rowid DESC LIMIT 100 + +# Bounded JSON scan: newest alerts of one node, about 50 rows read per hit. +json_alerts_node | SELECT message_id, message_data ->> '$.value' FROM data WHERE topic_id = {TOPIC} AND node_id = {NODE} AND is_json = 1 AND message_data ->> '$.kind' = 'alert' ORDER BY message_id DESC LIMIT 100 + +# Index scans, grow with the data. +count_node | SELECT COUNT(*) FROM data WHERE topic_id = {TOPIC} AND node_id = {NODE} +count_all | SELECT COUNT(*) FROM data +sync_state | SELECT topic_id, node_id, MAX(message_id) FROM data GROUP BY topic_id, node_id ORDER BY topic_id, node_id +sync_state_heads | SELECT topic_id, node_id, max_message_id FROM node_heads ORDER BY topic_id, node_id + +# Full table scans parsing every message's JSON, the ones that die first. +json_count_all | SELECT COUNT(*) FROM data WHERE is_json = 1 AND message_data ->> '$.kind' = 'alert' +json_agg_all | SELECT message_data ->> '$.kind', COUNT(*), ROUND(AVG(message_data ->> '$.value'), 2) FROM data WHERE is_json = 1 GROUP BY 1 +json_agg_node | SELECT message_data ->> '$.kind', COUNT(*), ROUND(AVG(message_data ->> '$.value'), 2) FROM data WHERE topic_id = {TOPIC} AND node_id = {NODE} AND is_json = 1 GROUP BY 1 diff --git a/Tests/Bench/queries_load.txt b/Tests/Bench/queries_load.txt new file mode 100644 index 0000000..8a8f4e7 --- /dev/null +++ b/Tests/Bench/queries_load.txt @@ -0,0 +1,13 @@ +# Queries run in a loop while pushing, in the "mixed" stage of +# Bench-Replication.ps1, to see how reads hold up under write load, and how +# much a long read slows the writes down (it used to block every commit, +# before WAL). +# Same format as queries.txt. + +latest_message | @latest +last_50_of_node | SELECT message_id, message_data FROM data WHERE topic_id = {TOPIC} AND node_id = {NODE} ORDER BY message_id DESC LIMIT 50 +json_alerts_node | SELECT message_id, message_data ->> '$.value' FROM data WHERE topic_id = {TOPIC} AND node_id = {NODE} AND is_json = 1 AND message_data ->> '$.kind' = 'alert' ORDER BY message_id DESC LIMIT 100 +count_node | SELECT COUNT(*) FROM data WHERE topic_id = {TOPIC} AND node_id = {NODE} +sync_state | SELECT topic_id, node_id, MAX(message_id) FROM data GROUP BY topic_id, node_id ORDER BY topic_id, node_id +sync_state_heads | SELECT topic_id, node_id, max_message_id FROM node_heads ORDER BY topic_id, node_id +json_count_all | SELECT COUNT(*) FROM data WHERE is_json = 1 AND message_data ->> '$.kind' = 'alert' diff --git a/Tests/BigMessages-Test.ps1 b/Tests/BigMessages-Test.ps1 new file mode 100644 index 0000000..9dcf3f3 --- /dev/null +++ b/Tests/BigMessages-Test.ps1 @@ -0,0 +1,336 @@ +# End-to-end test of big messages: up to 16 MB once authenticated, 4 KB +# frames before that (Commons/Networking/Connections.pbi). +# Two linked servers: pushes of 100 KB, 1 MB and just under the cap, read +# back through the client DLL, replicated to the other server, small ones +# still batched, a push over the cap refused, and frames too big for the +# handshake cutting the connection right away. +# Needs Build\ (Build.ps1) and Build\Bench\BenchServer.exe (Bench-Replication.ps1, +# or compile Tests\Bench\BenchServer.pb into it). Uses ports 12403-12404. +# Usage: powershell -ExecutionPolicy Bypass -File Tests\BigMessages-Test.ps1 +param([string]$Build = (Join-Path $PSScriptRoot "..\Build")) +$ErrorActionPreference = "Stop" +$Build = (Resolve-Path $Build).Path +$Dir = Join-Path $Build "_bigtest" +Remove-Item -Recurse -Force $Dir -ErrorAction SilentlyContinue +New-Item -ItemType Directory $Dir | Out-Null +$Server = Join-Path $Build "Bench\BenchServer.exe" +$Fails = 0 + +# Same as Packets.pbi. +$MaxPacketSize = 16 * 1024 * 1024 +$MaxMessageSize = $MaxPacketSize - 4096 + +function New-KeyPair { + $L = & (Join-Path $Build "KeyGen.exe") + @{ Priv = $L[0] -replace "^PrivateKey = ", ""; Pub = $L[1] -replace "^PublicKey = ", "" } +} +function Test-Port($P) { + $C = New-Object System.Net.Sockets.TcpClient + try { $A = $C.BeginConnect("127.0.0.1", $P, $null, $null); $A.AsyncWaitHandle.WaitOne(200) -and $C.Connected } catch { $false } finally { $C.Close() } +} +function Tool([string]$Name, [string[]]$A) { + $O = & (Join-Path $Build $Name) @A 2>&1 + @{ Code = $LASTEXITCODE; Out = ($O -join " | ") } +} +function Check([string]$What, [bool]$Ok, [string]$Detail) { + if (-not $Ok) { $script:Fails++ } + "{0} {1}`n -> {2}" -f $(if ($Ok) { "PASS" } else { "FAIL" }), $What, $Detail +} +function Expect([string]$What, $Result, [string]$Pattern, [int]$Code = 0) { + $Out = $Result.Out + if ($Out.Length -gt 300) { $Out = $Out.Substring(0, 300) + "... (" + $Result.Out.Length + " chars)" } + Check $What (($Result.Code -eq $Code) -and ($Result.Out -match $Pattern)) ("[{0}] {1}" -f $Result.Code, $Out) +} +function Start-Srv($Name) { + $Stop = Join-Path $Dir "$Name.stop" + Remove-Item $Stop -ErrorAction SilentlyContinue + $P = Start-Process -FilePath $Server -ArgumentList "`"$(Join-Path $Dir "$Name.ini")`"", "`"$Stop`"" -WorkingDirectory $Dir ` + -RedirectStandardOutput (Join-Path $Dir "$Name.log") -WindowStyle Hidden -PassThru + $null = $P.Handle + @{ P = $P; Stop = $Stop; Name = $Name } +} +function Stop-Srv($S) { + Set-Content $S.Stop "x" + if (-not $S.P.WaitForExit(15000)) { Stop-Process -Id $S.P.Id -Force } +} +function Wait-Port($Port, $S) { + $D = (Get-Date).AddSeconds(15) + while (-not (Test-Port $Port)) { + if ($S.P.HasExited) { throw "$($S.Name) exited: $(Get-Content (Join-Path $Dir "$($S.Name).log") -Raw)" } + if ((Get-Date) -gt $D) { throw "$($S.Name) not listening" } + Start-Sleep -Milliseconds 100 + } +} +function Query($Sql, $Ini) { + $F = Join-Path $Dir "q.sql"; Set-Content $F -Encoding Ascii -Value $Sql + Tool "Query.exe" @("@$F", $Ini) +} +# Waits until Sql answers something matching Pattern, for up to Seconds. +function Wait-Query($Sql, $Ini, $Pattern, $Seconds = 30) { + $D = (Get-Date).AddSeconds($Seconds) + do { + $R = Query $Sql $Ini + if ($R.Code -eq 0 -and $R.Out -match $Pattern) { return $R } + Start-Sleep -Milliseconds 250 + } while ((Get-Date) -lt $D) + $R +} +# A JSON message of exactly Size bytes, in a file, as PushMessage's @File. +function New-Message($Name, [int]$Size) { + $P = Join-Path $Dir "$Name.json" + $Head = '{"n":"' + $Name + '","pad":"' + $Tail = '"}' + $Pad = $Size - $Head.Length - $Tail.Length + $B = New-Object System.Text.StringBuilder ($Size) + [void]$B.Append($Head) + [void]$B.Append(("0123456789abcdef" * [math]::Ceiling($Pad / 16)).Substring(0, $Pad)) + [void]$B.Append($Tail) + [IO.File]::WriteAllText($P, $B.ToString(), (New-Object System.Text.UTF8Encoding $false)) + "@$P" +} +# Connects, sends one frame header announcing Size bytes, then up to 64 KB of +# zeros, and tells whether the server closed (or reset) the connection +# within 3 s, rather than waiting for the rest. +function Test-RawFrame([int]$Port, [int]$Size) { + $C = New-Object System.Net.Sockets.TcpClient + $Start = Get-Date + try { + $C.Connect("127.0.0.1", $Port) + $S = $C.GetStream() + $S.ReadTimeout = 5000 + $S.Write([BitConverter]::GetBytes([int]$Size), 0, 4) + try { $S.Write((New-Object byte[] ([math]::Min($Size, 65536))), 0, [math]::Min($Size, 65536)) } catch { } + $Buffer = New-Object byte[] 16 + try { $Read = $S.Read($Buffer, 0, 16) } catch { $Read = -1 } + ($Read -le 0) -and (((Get-Date) - $Start).TotalSeconds -lt 3) + } catch { ((Get-Date) - $Start).TotalSeconds -lt 3 } finally { $C.Close() } +} + +$A = New-KeyPair; $B = New-KeyPair; $K = New-KeyPair + +# Same names on both, different ids. +Set-Content (Join-Path $Dir "a.ini") -Encoding Ascii -Value @" +[BakaShrot] +PrivateKey = $($A.Priv) +Topic = logs +Node = serverA + +[BakaShrot.Topics] +logs = 1 + +[BakaShrot.Nodes] +serverA = 10 +serverB = 11 +kitchen = 2 + +[BakaShrot.Server] +Host = 127.0.0.1 +Port = 12403 +ReplicatingTopics = logs +DatabasePath = $(Join-Path $Dir "a.sqlite") +PeerSyncInterval = 1 +PeerRetryDelay = 1 + +[BakaShrot.Peer.b] +Host = 127.0.0.1 +Port = 12404 +Topic = logs +Node = serverB +PublicKey = $($B.Pub) + +[BakaShrot.Client.b] +PublicKeys = $($B.Pub) +Identities = logs:serverB + +[BakaShrot.Client.kitchen] +PublicKeys = $($K.Pub) +Identities = logs:kitchen +ReadTopics = * +AllowQuery = 1 +"@ + +Set-Content (Join-Path $Dir "b.ini") -Encoding Ascii -Value @" +[BakaShrot] +PrivateKey = $($B.Priv) +Topic = logs +Node = serverB + +[BakaShrot.Topics] +logs = 300 + +[BakaShrot.Nodes] +serverA = 1 +serverB = 2 +kitchen = 30 + +[BakaShrot.Server] +Host = 127.0.0.1 +Port = 12404 +ReplicatingTopics = logs +DatabasePath = $(Join-Path $Dir "b.sqlite") +PeerSyncInterval = 1 +PeerRetryDelay = 1 + +[BakaShrot.Peer.a] +Host = 127.0.0.1 +Port = 12403 +Topic = logs +Node = serverA +PublicKey = $($A.Pub) + +[BakaShrot.Client.a] +PublicKeys = $($A.Pub) +Identities = logs:serverA + +[BakaShrot.Client.kitchen] +PublicKeys = $($K.Pub) +Identities = logs:kitchen +ReadTopics = * +AllowQuery = 1 +"@ + +$ServerKeys = @{ 12403 = $A.Pub; 12404 = $B.Pub } +function Client-Ini($Name, $Port) { + $P = Join-Path $Dir "$Name.ini" + Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($K.Priv)`r`nPublicKey = $($K.Pub)`r`nTopic = logs`r`nNode = kitchen`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($ServerKeys[$Port])" + $P +} +$OnA = Client-Ini "kitchen-a" 12403 +$OnB = Client-Ini "kitchen-b" 12404 + +$Sizes = [ordered]@{ "m100k" = 100 * 1024; "m1m" = 1024 * 1024; "mmax" = $MaxMessageSize } +$Files = @{} +foreach ($N in $Sizes.Keys) { $Files[$N] = New-Message $N $Sizes[$N] } +$Over = New-Message "over" ($MaxMessageSize + 1) +# Not JSON: 1 MB of it cut short, and plain text. Stored anyway, is_json = 0. +$Broken = Join-Path $Dir "broken.json" +[IO.File]::WriteAllText($Broken, ([IO.File]::ReadAllText($Files["m1m"].Substring(1))).Substring(0, 1000000)) +$Text = Join-Path $Dir "text.txt" +[IO.File]::WriteAllText($Text, "just some text, not JSON") +$Small = New-Message "small" 40 + +$SA = Start-Srv "a"; $SB = Start-Srv "b" +try { + Wait-Port 12403 $SA; Wait-Port 12404 $SB + + "--- Before authenticating" + Check "a frame over 4 KB is cut right away" (Test-RawFrame 12403 4097) "connection closed" + Check "a 16 MB frame too" (Test-RawFrame 12403 $MaxPacketSize) "connection closed" + Check "the server still serves after that" (Test-Port 12403) "listening" + + "--- Pushes" + $Id = 0 + foreach ($N in $Sizes.Keys) { + $Id++ + $T = Measure-Command { $R = Tool "PushMessage.exe" @($Files[$N], $OnA) } + Expect ("push of {0:N0} bytes ({1:N0} ms)" -f $Sizes[$N], $T.TotalMilliseconds) $R "message #$Id" + } + Expect "a push 1 byte over the cap is refused" (Tool "PushMessage.exe" @($Over, $OnA)) "too big" 1 + $Id++ + Expect "a small push after them" (Tool "PushMessage.exe" @($Small, $OnA)) "message #$Id" + + "--- Read back" + $T = Measure-Command { $O = & (Join-Path $Build "GetLatestMessage.exe") "logs" "kitchen" $OnA 2>&1 } + $Code = $LASTEXITCODE + Check "latest is the small one" ($Code -eq 0 -and ($O -join "") -match '"n":"small"') ($O -join " | ") + $R = Query "SELECT message_id, length(message_data) FROM data WHERE node_id = 2 ORDER BY message_id" $OnA + Expect "stored sizes on A" $R ('\[\["1","{0}"\],\["2","{1}"\],\["3","{2}"\],\["4","40"\]\]' -f $Sizes["m100k"], $Sizes["m1m"], $MaxMessageSize) + + "--- Replicated to B (same names, B's ids)" + $R = Wait-Query "SELECT message_id, length(message_data), topic_id, node_id FROM messages WHERE topic = 'logs' AND node = 'kitchen' ORDER BY message_id" $OnB '"4","40"' 60 + Expect "every one on B, under logs=300 kitchen=30" $R ('\[\["1","{0}","300","30"\],\["2","{1}","300","30"\],\["3","{2}","300","30"\],\["4","40","300","30"\]\]' -f $Sizes["m100k"], $Sizes["m1m"], $MaxMessageSize) + $R = Query "SELECT count(*) FROM data a WHERE node_id = 30 AND message_id = 3 AND substr(message_data, 1, 31) = '{`"n`":`"mmax`",`"pad`":`"0123456789ab' AND substr(message_data, -2) = '`"}' AND is_json = 1" $OnB + Expect "the biggest one is intact on B" $R '\[\["1"\]\]' + + "--- Read back the biggest, from B" + # Pushed after the small one, so it's the latest. + $Id++ + Expect "push the biggest again" (Tool "PushMessage.exe" @($Files["mmax"], $OnA)) "message #$Id" + $null = Wait-Query "SELECT max(message_id) FROM data WHERE node_id = 30" $OnB "`"$Id`"" 60 + $T = Measure-Command { $O = & (Join-Path $Build "GetLatestMessage.exe") "logs" "kitchen" $OnB 2>&1 } + $Code = $LASTEXITCODE + $Json = if ($O.Count -ge 2) { [string]$O[1] } else { "" } + Check ("GetLatestMessage of {0:N0} bytes from B ({1:N0} ms)" -f $MaxMessageSize, $T.TotalMilliseconds) ($Code -eq 0 -and $Json.Length -eq $MaxMessageSize -and $Json -eq [IO.File]::ReadAllText($Files["mmax"].Substring(1))) ("[$Code] " + [string]$O[0] + ", " + $Json.Length + " chars") + + "--- Many small ones still go in batches" + 1..30 | ForEach-Object { $null = Tool "PushMessage.exe" @($Small, $OnA) } + $R = Wait-Query "SELECT count(*) FROM data WHERE node_id = 30" $OnB '"35"' 30 + Expect "35 on B" $R '\[\["35"\]\]' + + "--- Not JSON: stored as is, flagged" + Expect "1 MB of broken JSON is stored" (Tool "PushMessage.exe" @("@$Broken", $OnA)) "message #36" + Expect "plain text is stored" (Tool "PushMessage.exe" @("@$Text", $OnA)) "message #37" + Expect "flagged is_json = 0 on A, the rest 1" (Query "SELECT message_id, is_json, length(message_data) FROM data WHERE node_id = 2 AND message_id >= 35 ORDER BY message_id" $OnA) '\[\["35","1","40"\],\["36","0","1000000"\],\["37","0","24"\]\]' + $R = Wait-Query "SELECT message_id, is_json, length(message_data) FROM data WHERE node_id = 30 AND message_id >= 35 ORDER BY message_id" $OnB '"37"' 30 + Expect "replicated and flagged the same on B" $R '\[\["35","1","40"\],\["36","0","1000000"\],\["37","0","24"\]\]' + $O = & (Join-Path $Build "GetLatestMessage.exe") "logs" "kitchen" $OnB 2>&1 + Check "read back as is from B" ($LASTEXITCODE -eq 0 -and [string]$O[1] -eq "just some text, not JSON") ($O -join " | ") + + "--- is_json for the edge cases (SQLite's json_valid(), RFC 8259)" + $Cases = @( + @("42", 1), @('"a string"', 1), @("null", 1), @("[1,2]", 1), @(' {"a":1} ', 1), + @("{a:1}", 0), @('{"a":1} x', 0), @("{'a':1}", 0), @('{"a":1', 0), @("", 0)) + $Id = 37 + foreach ($C in $Cases) { + $Id++ + $F = Join-Path $Dir "case$Id.txt" + [IO.File]::WriteAllText($F, $C[0]) + $R = Tool "PushMessage.exe" @("@$F", $OnA) + $Q = Query "SELECT is_json FROM data WHERE node_id = 2 AND message_id = $Id" $OnA + Check ("'{0}' stored, is_json = {1}" -f $C[0], $C[1]) ($R.Out -match "message #$Id" -and $Q.Out -match ('"rows":\[\["{0}"\]\]' -f $C[1])) ($R.Out + " / " + $Q.Out) + } + + "--- JSON queries over mixed rows" + Expect "with is_json = 1, ->> works" (Query "SELECT COUNT(*) FROM data WHERE is_json = 1 AND message_data ->> '$.n' = 'small'" $OnA) '\[\["31"\]\]' + Expect "in the select list too" (Query "SELECT COUNT(message_data ->> '$.n') FROM data WHERE is_json = 1" $OnA) '\[\["35"\]\]' + # SQLite fails these with "malformed JSON" on the first non-JSON row. + # PureBasic's NextDatabaseRow() can't tell that from the end of the rows, + # RunReadOnlyQuery() asks SQLite: refused, never a partial or empty answer. + Expect "without it, an aggregate is refused with SQLite's error, not answered with no rows" (Query "SELECT COUNT(*) FROM data WHERE message_data ->> '$.n' = 'small'" $OnA) 'Query failed: malformed JSON \(a row isn''t JSON: add is_json = 1 to the WHERE\)' 1 + Expect "rows read as they go are refused too, not cut short at the first non-JSON one" (Query "SELECT message_id, message_data ->> '$.n' FROM data WHERE node_id = 2 ORDER BY message_id" $OnA) 'Query failed: malformed JSON' 1 + Expect "non-JSON rows without JSON functions: every row" (Query "SELECT COUNT(*), SUM(is_json = 0) FROM data" $OnA) '\[\["\d+","\d+"\]\]' + Expect "JSON functions guarded by CASE WHEN is_json: every row" (Query "SELECT COUNT(*), COUNT(CASE WHEN is_json THEN message_data ->> '$.n' END) FROM data" $OnA) '\[\["\d+","35"\]\]' + Expect "a query with really no rows: still an empty answer" (Query "SELECT message_id FROM data WHERE message_id < 0" $OnA) '"rows":\[\]' + Expect "and a query error still refused as before" (Query "SELECT nope FROM data" $OnA) 'Query failed: .*nope' 1 +} finally { + Stop-Srv $SA; Stop-Srv $SB +} + +"--- Logs" +# Up to the last real activity: whichever stops first, the other loses its +# link to it. +function Read-Log($Name) { + $L = @(Get-Content (Join-Path $Dir "$Name.log")) + $End = [array]::IndexOf($L, "Stopping...") + if ($End -lt 0) { $End = $L.Count } + while ($End -gt 0 -and $L[$End - 1] -match "Lost the link|Retrying|disconnected|aborted|didn't answer") { $End-- } + ($L[0..([math]::Max($End - 1, 0))]) -join "`n" +} +$LogA = Read-Log "a" +$LogB = Read-Log "b" +# The raw frames are cut as an invalid frame, or as too much data when the +# zeros after the header filled the inbox before its size was checked: +# either way right away, which one is down to timing. +# Client ids get reused, so whether each one is authenticated is followed +# line by line, from its "connected". +$Authenticated = @{}; $Cut = 0; $CutAuthenticated = 0 +foreach ($Line in ($LogA -split "`n")) { + if ($Line -match "Client (\d+) connected") { $Authenticated[$Matches[1]] = $false } + elseif ($Line -match "Client (\d+) authenticated") { $Authenticated[$Matches[1]] = $true } + elseif ($Line -match "Client (\d+) sent (an invalid frame|too much data)") { + $Cut++ + if ($Authenticated[$Matches[1]]) { $CutAuthenticated++ } + } +} +Check "A cut both raw frames (invalid frame or too much data)" ($Cut -ge 2) "$Cut times" +Check "none of them from an authenticated client" ($CutAuthenticated -eq 0) "$CutAuthenticated" +# Without the refusals this test asks for ("Query failed: malformed JSON", ...). +$UnrefusedA = ($LogA -split "`n" | Where-Object { $_ -notmatch "Refused a request" }) -join "`n" +$UnrefusedB = ($LogB -split "`n" | Where-Object { $_ -notmatch "Refused a request" }) -join "`n" +foreach ($P in @("too big", "Lost the link", "Failed")) { + Check "no '$P' in A's or B's log" (-not ($UnrefusedA -match [regex]::Escape($P)) -and -not ($UnrefusedB -match [regex]::Escape($P))) "checked" +} +Check "no 'sent too much data' in B's log" (-not ($LogB -match "sent too much data")) "checked" + +"" +if ($Fails) { "$Fails FAILED"; exit 1 } else { "All passed" } diff --git a/Tests/CipherTest.pb b/Tests/CipherTest.pb new file mode 100644 index 0000000..5281f37 --- /dev/null +++ b/Tests/CipherTest.pb @@ -0,0 +1,387 @@ +; ============================================================================ +; Tests of Commons/Cryptography/Cipher.pbi, no sockets: round trips in both +; directions, and everything that must be refused (tampering, replay, +; reordering, reflection, wrong key), empty and 16 MB buffers. +; And of Session.pbi: the sealed Hello (only its server opens it, tampering +; refused) and the key exchange (both ends agree, a swapped half or another +; connection's keys don't work, the key pairs are wiped). +; Compile as a console program into Build\ (libsodium.dll is there), run it +; from there. Exits with 0 if every check passed, 1 otherwise. +; ============================================================================ + +EnableExplicit + +XIncludeFile "../Commons/Cryptography/Session.pbi" + +Global Fails.i = 0 + +Procedure Check(What.s, Ok.i, Detail.s = "") + If Ok + PrintN("PASS " + What) + Else + PrintN("FAIL " + What) + Fails + 1 + EndIf + If Detail <> "" + PrintN(" -> " + Detail) + EndIf +EndProcedure + +; Text as a UTF-8 buffer, its size in *Size\i. +Procedure.i ToUtf8(Text.s, *Size.Integer) + Protected *Buffer + *Size\i = StringByteLength(Text, #PB_UTF8) + *Buffer = AllocateMemory(*Size\i + 1) + PokeS(*Buffer, Text, -1, #PB_UTF8) + ProcedureReturn *Buffer +EndProcedure + +; Encrypts Text with *From, decrypts it with *To, returns what came out ("" and +; *Ok\i #False if refused). +Procedure.s RoundTrip(*From.BakaShrot_Cipher, *To.BakaShrot_Cipher, Text.s, *Ok.Integer) + Protected *Plain, PlainSize.Integer, *Sealed, SealedSize.Integer, *Opened, OpenedSize.Integer, Result.s + *Ok\i = #False + *Plain = ToUtf8(Text, @PlainSize) + *Sealed = BakaShrot_Cipher_Encrypt(*From, *Plain, PlainSize\i, @SealedSize) + FreeMemory(*Plain) + If Not *Sealed + ProcedureReturn "" + EndIf + *Opened = BakaShrot_Cipher_Decrypt(*To, *Sealed, SealedSize\i, @OpenedSize) + FreeMemory(*Sealed) + If Not *Opened + ProcedureReturn "" + EndIf + Result = PeekS(*Opened, OpenedSize\i, #PB_UTF8 | #PB_ByteLength) + FreeMemory(*Opened) + *Ok\i = #True + ProcedureReturn Result +EndProcedure + +; Whether Text's UTF-8 bytes appear anywhere in *Buffer (Size bytes). +Procedure.i ContainsText(*Buffer, Size.i, Text.s) + Protected *Needle, NeedleSize.Integer, i.i, Found.i + *Needle = ToUtf8(Text, @NeedleSize) + For i = 0 To Size - NeedleSize\i + If CompareMemory(*Buffer + i, *Needle, NeedleSize\i) + Found = #True + Break + EndIf + Next + FreeMemory(*Needle) + ProcedureReturn Found +EndProcedure + +; Whether *Sealed (Size bytes) is refused by *To, without changing it. +Procedure.i IsRefused(*To.BakaShrot_Cipher, *Sealed, Size.i) + Protected *Opened, OpenedSize.Integer + *Opened = BakaShrot_Cipher_Decrypt(*To, *Sealed, Size, @OpenedSize) + If *Opened + FreeMemory(*Opened) + ProcedureReturn #False + EndIf + ProcedureReturn #True +EndProcedure + +; A copy of Size bytes at *Source. +Procedure.i Copy(*Source, Size.i) + Protected *Copy = AllocateMemory(Size) + CopyMemory(*Source, *Copy, Size) + ProcedureReturn *Copy +EndProcedure + + +Define *Key, *OtherKey +Define Client.BakaShrot_Cipher, Server.BakaShrot_Cipher, Other.BakaShrot_Cipher, Uninitialized.BakaShrot_Cipher +Define Ok.Integer, Text.s, i.i, Zero.i +Define *Plain, PlainSize.Integer, *Sealed, SealedSize.Integer, *Sealed2, Sealed2Size.Integer, *Opened, OpenedSize.Integer +Define *Tampered, Offset.i, Refused.i, StartTime.q, Elapsed.q + +OpenConsole() + +If Not InitCryptography() + PrintN("FAIL libsodium couldn't initialize") + End 1 +EndIf + +*Key = AllocateMemory(#BakaShrot_Cipher_KeySize) +*OtherKey = AllocateMemory(#BakaShrot_Cipher_KeySize) +BakaShrot_Cipher_GenerateKey(*Key) +BakaShrot_Cipher_GenerateKey(*OtherKey) +Check("Two generated keys differ", Bool(Not CompareMemory(*Key, *OtherKey, #BakaShrot_Cipher_KeySize))) + +Check("Init as client", BakaShrot_Cipher_Init(@Client, *Key, #BakaShrot_Cipher_Client)) +Check("Init as server", BakaShrot_Cipher_Init(@Server, *Key, #BakaShrot_Cipher_Server)) +Check("Init with role 0 refused", Bool(Not BakaShrot_Cipher_Init(@Other, *Key, 0))) + +; --- Round trips --------------------------------------------------------------- + +Text = RoundTrip(@Client, @Server, "hello, server", @Ok) +Check("Client -> server", Bool(Ok\i And Text = "hello, server"), Text) +Text = RoundTrip(@Server, @Client, "hello, client", @Ok) +Check("Server -> client", Bool(Ok\i And Text = "hello, client"), Text) +For i = 1 To 100 + Text = RoundTrip(@Client, @Server, "message " + Str(i), @Ok) + If Not Ok\i Or Text <> "message " + Str(i) + Break + EndIf +Next +Check("100 more in order", Bool(i = 101), Str(i - 1) + " went through") +Text = RoundTrip(@Client, @Server, "héllo wörld, 🌍", @Ok) +Check("Non-ASCII data", Bool(Ok\i And Text = "héllo wörld, 🌍"), Text) + +; --- What a sealed buffer looks like ------------------------------------------ + +*Plain = ToUtf8("same text", @PlainSize) +*Sealed = BakaShrot_Cipher_Encrypt(@Client, *Plain, PlainSize\i, @SealedSize) +*Sealed2 = BakaShrot_Cipher_Encrypt(@Client, *Plain, PlainSize\i, @Sealed2Size) +Check("Sealed size is the data + " + Str(#BakaShrot_Cipher_Overhead), Bool(SealedSize\i = PlainSize\i + #BakaShrot_Cipher_Overhead), Str(SealedSize\i) + " bytes for " + Str(PlainSize\i)) +Check("The data doesn't appear in it", Bool(Not CompareMemory(*Sealed + #BakaShrot_Cipher_SequenceSize, *Plain, PlainSize\i))) +Check("The same data twice seals differently", Bool(Not CompareMemory(*Sealed + #BakaShrot_Cipher_SequenceSize, *Sealed2 + #BakaShrot_Cipher_SequenceSize, PlainSize\i))) +Check("Each carries its sequence number", Bool(PeekQ(*Sealed2) = PeekQ(*Sealed) + 1), Str(PeekQ(*Sealed)) + ", " + Str(PeekQ(*Sealed2))) + +; --- Refused --------------------------------------------------------------------- + +; Reordered: the second one first. +Check("The next-but-one first: refused (reordered)", IsRefused(@Server, *Sealed2, Sealed2Size\i)) + +; Tampered anywhere: the sequence number, the data, the tag. +Refused = 0 +For Offset = 0 To SealedSize\i - 1 + *Tampered = Copy(*Sealed, SealedSize\i) + PokeA(*Tampered + Offset, PeekA(*Tampered + Offset) ! $01) + If IsRefused(@Server, *Tampered, SealedSize\i) + Refused + 1 + EndIf + FreeMemory(*Tampered) +Next +Check("One bit flipped anywhere: refused, at every one of its " + Str(SealedSize\i) + " bytes", Bool(Refused = SealedSize\i), Str(Refused) + " refused") +Check("Cut short by one byte: refused", IsRefused(@Server, *Sealed, SealedSize\i - 1)) +Check("Shorter than the overhead: refused", IsRefused(@Server, *Sealed, #BakaShrot_Cipher_Overhead - 1)) + +; None of that moved the receiver on: the genuine ones still go through, in order. +*Opened = BakaShrot_Cipher_Decrypt(@Server, *Sealed, SealedSize\i, @OpenedSize) +Check("After all that, the genuine one still decrypts", Bool(*Opened And OpenedSize\i = PlainSize\i And CompareMemory(*Opened, *Plain, PlainSize\i))) +If *Opened : FreeMemory(*Opened) : EndIf +Check("Replayed: refused", IsRefused(@Server, *Sealed, SealedSize\i)) +*Opened = BakaShrot_Cipher_Decrypt(@Server, *Sealed2, Sealed2Size\i, @OpenedSize) +Check("Then the next one", Bool(*Opened <> 0)) +If *Opened : FreeMemory(*Opened) : EndIf + +; Reflected: sent back to its sender, or to another client with the same key. +*Sealed2 = BakaShrot_Cipher_Encrypt(@Client, *Plain, PlainSize\i, @Sealed2Size) +BakaShrot_Cipher_Init(@Other, *Key, #BakaShrot_Cipher_Client) +; Same sequence number, so only the direction differs. +Other\ReceiveSequence = PeekQ(*Sealed2) +Check("Reflected to a client with the same key, same sequence number: refused", IsRefused(@Other, *Sealed2, Sealed2Size\i)) + +; Another key. +BakaShrot_Cipher_Init(@Other, *OtherKey, #BakaShrot_Cipher_Server) +Other\ReceiveSequence = PeekQ(*Sealed2) +Check("Another key: refused", IsRefused(@Other, *Sealed2, Sealed2Size\i)) +FreeMemory(*Sealed) +FreeMemory(*Sealed2) +FreeMemory(*Plain) + +Check("Not set up: refuses to encrypt", Bool(BakaShrot_Cipher_Encrypt(@Uninitialized, @Zero, 4, @SealedSize) = 0)) + +; --- Sizes --------------------------------------------------------------------- + +BakaShrot_Cipher_Init(@Client, *Key, #BakaShrot_Cipher_Client) +BakaShrot_Cipher_Init(@Server, *Key, #BakaShrot_Cipher_Server) +*Sealed = BakaShrot_Cipher_Encrypt(@Client, 0, 0, @SealedSize) +*Opened = 0 +If *Sealed + *Opened = BakaShrot_Cipher_Decrypt(@Server, *Sealed, SealedSize\i, @OpenedSize) +EndIf +Check("Empty data: sealed in " + Str(#BakaShrot_Cipher_Overhead) + " bytes, opens to 0 bytes", Bool(*Sealed And SealedSize\i = #BakaShrot_Cipher_Overhead And *Opened And OpenedSize\i = 0)) +If *Sealed : FreeMemory(*Sealed) : EndIf +If *Opened : FreeMemory(*Opened) : EndIf + +PlainSize\i = 16 * 1024 * 1024 +*Plain = AllocateMemory(PlainSize\i) +RandomData(*Plain, PlainSize\i) +StartTime = ElapsedMilliseconds() +*Sealed = BakaShrot_Cipher_Encrypt(@Client, *Plain, PlainSize\i, @SealedSize) +*Opened = BakaShrot_Cipher_Decrypt(@Server, *Sealed, SealedSize\i, @OpenedSize) +Elapsed = ElapsedMilliseconds() - StartTime +Check("16 MB both ways, intact", Bool(*Opened And OpenedSize\i = PlainSize\i And CompareMemory(*Opened, *Plain, PlainSize\i)), Str(Elapsed) + " ms to encrypt and decrypt") +FreeMemory(*Plain) +If *Sealed : FreeMemory(*Sealed) : EndIf +If *Opened : FreeMemory(*Opened) : EndIf + +; --- A key per direction ----------------------------------------------------- + +Check("Two keys: the same one twice refused", Bool(Not BakaShrot_Cipher_InitWithKeys(@Client, *Key, *Key))) +Check("Two keys: client sends with A, receives with B", BakaShrot_Cipher_InitWithKeys(@Client, *Key, *OtherKey)) +Check("Two keys: server the other way around", BakaShrot_Cipher_InitWithKeys(@Server, *OtherKey, *Key)) +Text = RoundTrip(@Client, @Server, "with two keys", @Ok) +Check("Two keys: client -> server", Bool(Ok\i And Text = "with two keys"), Text) +Text = RoundTrip(@Server, @Client, "and back", @Ok) +Check("Two keys: server -> client", Bool(Ok\i And Text = "and back"), Text) +BakaShrot_Cipher_InitWithKeys(@Other, *Key, *OtherKey) +*Plain = ToUtf8("to myself", @PlainSize) +*Sealed = BakaShrot_Cipher_Encrypt(@Other, *Plain, PlainSize\i, @SealedSize) +Check("Two keys: reflected to its sender, refused", IsRefused(@Other, *Sealed, SealedSize\i)) +FreeMemory(*Sealed) +FreeMemory(*Plain) + +; --- Clear ------------------------------------------------------------------------- + +BakaShrot_Cipher_Clear(@Client) +Zero = #True +For i = 0 To #BakaShrot_Cipher_KeySize - 1 + If Client\SendKey[i] Or Client\ReceiveKey[i] + Zero = #False + EndIf +Next +Check("Clear wipes both keys", Zero) +Check("Cleared: refuses to encrypt", Bool(BakaShrot_Cipher_Encrypt(@Client, @Zero, 4, @SealedSize) = 0)) + +sodium_memzero(*Key, #BakaShrot_Cipher_KeySize) +sodium_memzero(*OtherKey, #BakaShrot_Cipher_KeySize) + + +; --- Into a given buffer --------------------------------------------------------- + +BakaShrot_Cipher_Init(@Client, *Key, #BakaShrot_Cipher_Client) +BakaShrot_Cipher_Init(@Server, *Key, #BakaShrot_Cipher_Server) +*Plain = ToUtf8("in place", @PlainSize) +*Sealed = AllocateMemory(PlainSize\i + #BakaShrot_Cipher_Overhead) +Check("EncryptTo writes a sealed buffer", BakaShrot_Cipher_EncryptTo(@Client, *Plain, PlainSize\i, *Sealed)) +*Opened = BakaShrot_Cipher_Decrypt(@Server, *Sealed, PlainSize\i + #BakaShrot_Cipher_Overhead, @OpenedSize) +Check("EncryptTo's buffer decrypts", Bool(*Opened And PeekS(*Opened, OpenedSize\i, #PB_UTF8 | #PB_ByteLength) = "in place")) +If *Opened : FreeMemory(*Opened) : EndIf +Check("EncryptTo refuses without a cipher", Bool(Not BakaShrot_Cipher_EncryptTo(@Uninitialized, *Plain, PlainSize\i, *Sealed))) +FreeMemory(*Sealed) +FreeMemory(*Plain) +BakaShrot_Cipher_Clear(@Client) +BakaShrot_Cipher_Clear(@Server) + + +; --- Session: the sealed Hello --------------------------------------------------- + +Define *ServerPublic = AllocateMemory(#BakaShrot_Ed25519_PublicKeySize) +Define *ServerPrivate = AllocateMemory(#BakaShrot_Ed25519_PrivateKeySize) +Define *OtherPublic = AllocateMemory(#BakaShrot_Ed25519_PublicKeySize) +Define *OtherPrivate = AllocateMemory(#BakaShrot_Ed25519_PrivateKeySize) +Define *ZeroKey = AllocateMemory(32) +Define HelloKeys.BakaShrot_HelloKeys, OtherHelloKeys.BakaShrot_HelloKeys +Define ClientPair.BakaShrot_SessionKeyPair, ServerPair.BakaShrot_SessionKeyPair, MiddlePair.BakaShrot_SessionKeyPair +Define ClientHalf.BakaShrot_SessionKey, ServerHalf.BakaShrot_SessionKey, MiddleHalf.BakaShrot_SessionKey + +GenerateKeyPair(*ServerPublic, *ServerPrivate) +GenerateKeyPair(*OtherPublic, *OtherPrivate) +Check("Hello keys from a server's private key", BakaShrot_Session_LoadHelloKeys(@HelloKeys, *ServerPrivate)) +BakaShrot_Session_LoadHelloKeys(@OtherHelloKeys, *OtherPrivate) + +*Plain = ToUtf8("hello, I'm logs:kitchen", @PlainSize) +*Sealed = BakaShrot_Session_SealHello(*ServerPublic, *Plain, PlainSize\i, @SealedSize) +Check("Hello sealed, 48 bytes more", Bool(*Sealed And SealedSize\i = PlainSize\i + #BakaShrot_SealedBoxOverhead)) +Check("The sealed hello doesn't show the identity", Bool(*Sealed And Not ContainsText(*Sealed, SealedSize\i, "kitchen"))) +*Opened = BakaShrot_Session_OpenHello(@HelloKeys, *Sealed, SealedSize\i, @OpenedSize) +Check("The server opens it", Bool(*Opened And PeekS(*Opened, OpenedSize\i, #PB_UTF8 | #PB_ByteLength) = "hello, I'm logs:kitchen")) +If *Opened : FreeMemory(*Opened) : EndIf +*Opened = BakaShrot_Session_OpenHello(@OtherHelloKeys, *Sealed, SealedSize\i, @OpenedSize) +Check("Another server can't open it", Bool(Not *Opened)) +If *Opened : FreeMemory(*Opened) : EndIf + +Refused = #True +For Offset = 0 To SealedSize\i - 1 Step 7 + *Tampered = Copy(*Sealed, SealedSize\i) + PokeA(*Tampered + Offset, PeekA(*Tampered + Offset) ! $01) + *Opened = BakaShrot_Session_OpenHello(@HelloKeys, *Tampered, SealedSize\i, @OpenedSize) + If *Opened + Refused = #False + FreeMemory(*Opened) + EndIf + FreeMemory(*Tampered) +Next +Check("A tampered hello isn't opened", Refused) +*Opened = BakaShrot_Session_OpenHello(@HelloKeys, *Sealed, #BakaShrot_SealedBoxOverhead, @OpenedSize) +Check("A hello cut short isn't opened", Bool(Not *Opened)) +FreeMemory(*Sealed) + +*Sealed = BakaShrot_Session_SealHello(*ZeroKey, *Plain, PlainSize\i, @SealedSize) +Check("Sealing for an invalid server key refused", Bool(Not *Sealed)) +If *Sealed : FreeMemory(*Sealed) : EndIf +FreeMemory(*Plain) + + +; --- Session: the key exchange --------------------------------------------------- + +BakaShrot_Session_NewKeyPair(@ClientPair) +BakaShrot_Session_NewKeyPair(@ServerPair) +CopyMemory(@ClientPair\PublicKey[0], @ClientHalf, 32) +CopyMemory(@ServerPair\PublicKey[0], @ServerHalf, 32) +Check("Server starts from the client's half", BakaShrot_Session_StartServer(@Server, @ServerPair, @ClientHalf)) +Check("Client starts from the server's half", BakaShrot_Session_StartClient(@Client, @ClientPair, @ServerHalf)) +Zero = #True +For i = 0 To #BakaShrot_X25519_SecretKeySize - 1 + If ClientPair\SecretKey[i] Or ServerPair\SecretKey[i] + Zero = #False + EndIf +Next +Check("Both key pairs wiped once started", Zero) + +Text = RoundTrip(@Client, @Server, "push over a session", @Ok) +Check("Session: client -> server", Bool(Ok\i And Text = "push over a session"), Text) +Text = RoundTrip(@Server, @Client, "answer over a session", @Ok) +Check("Session: server -> client", Bool(Ok\i And Text = "answer over a session"), Text) +Check("Session: a key per direction", Bool(Not CompareMemory(@Client\SendKey[0], @Client\ReceiveKey[0], #BakaShrot_Cipher_KeySize))) +Check("Session: the client's send key is the server's receive key", CompareMemory(@Client\SendKey[0], @Server\ReceiveKey[0], #BakaShrot_Cipher_KeySize)) + +*Plain = ToUtf8("back to me", @PlainSize) +*Sealed = BakaShrot_Cipher_Encrypt(@Client, *Plain, PlainSize\i, @SealedSize) +Check("Session: reflected to the client, refused", IsRefused(@Client, *Sealed, SealedSize\i)) +FreeMemory(*Sealed) + +; Someone in the middle swapping the server's half for theirs: the client +; ends up with keys the real server doesn't have. (The server's signature +; of the halves catches it first, in the handshake.) +BakaShrot_Session_NewKeyPair(@ClientPair) +BakaShrot_Session_NewKeyPair(@ServerPair) +BakaShrot_Session_NewKeyPair(@MiddlePair) +CopyMemory(@ClientPair\PublicKey[0], @ClientHalf, 32) +CopyMemory(@MiddlePair\PublicKey[0], @MiddleHalf, 32) +BakaShrot_Session_StartServer(@Server, @ServerPair, @ClientHalf) +BakaShrot_Session_StartClient(@Client, @ClientPair, @MiddleHalf) +*Sealed = BakaShrot_Cipher_Encrypt(@Client, *Plain, PlainSize\i, @SealedSize) +Check("Session: halves swapped, the server can't decrypt", IsRefused(@Server, *Sealed, SealedSize\i)) +FreeMemory(*Sealed) + +; Another connection of the same client gets other keys. +Define Server2.BakaShrot_Cipher +CopyMemory(@Server, @Other, SizeOf(BakaShrot_Cipher)) +BakaShrot_Session_NewKeyPair(@ClientPair) +BakaShrot_Session_NewKeyPair(@ServerPair) +CopyMemory(@ClientPair\PublicKey[0], @ClientHalf, 32) +CopyMemory(@ServerPair\PublicKey[0], @ServerHalf, 32) +BakaShrot_Session_StartServer(@Server2, @ServerPair, @ClientHalf) +BakaShrot_Session_StartClient(@Client, @ClientPair, @ServerHalf) +Check("Session: another connection, other keys", Bool(Not CompareMemory(@Server2\ReceiveKey[0], @Other\ReceiveKey[0], #BakaShrot_Cipher_KeySize))) +*Sealed = BakaShrot_Cipher_Encrypt(@Client, *Plain, PlainSize\i, @SealedSize) +Check("Session: replayed into another connection, refused", IsRefused(@Other, *Sealed, SealedSize\i)) +FreeMemory(*Sealed) +FreeMemory(*Plain) + +BakaShrot_Session_NewKeyPair(@ServerPair) +Check("Session: an all-zero half refused", Bool(Not BakaShrot_Session_StartServer(@Server, @ServerPair, *ZeroKey))) +Check("Session: refused, the cipher isn't usable", Bool(Not Server\IsReady)) + +BakaShrot_Session_ClearHelloKeys(@HelloKeys) +BakaShrot_Session_ClearHelloKeys(@OtherHelloKeys) +sodium_memzero(*ServerPrivate, #BakaShrot_Ed25519_PrivateKeySize) +sodium_memzero(*OtherPrivate, #BakaShrot_Ed25519_PrivateKeySize) +BakaShrot_Cipher_Clear(@Client) +BakaShrot_Cipher_Clear(@Server) +BakaShrot_Cipher_Clear(@Server2) +BakaShrot_Cipher_Clear(@Other) + +PrintN("") +If Fails + PrintN(Str(Fails) + " check(s) failed") + End 1 +EndIf +PrintN("All checks passed") +End 0 diff --git a/Tests/GetMessages-Test.ps1 b/Tests/GetMessages-Test.ps1 new file mode 100644 index 0000000..bb715be --- /dev/null +++ b/Tests/GetMessages-Test.ps1 @@ -0,0 +1,250 @@ +# End-to-end test of reading runs of messages: the GetMessages request +# (Commons/Networking/Packets/GetMessagesPacket.pbi), through the client DLL +# and Tools\GetMessages: from the start, after an id, after the latest one, +# with a limit, answers split at ~1 MB, data that isn't JSON or spans lines, +# refusals, and --follow picking up new pushes. +# Needs Build\ (Build.ps1) and Build\Bench\BenchServer.exe (Bench-Replication.ps1, +# or compile Tests\Bench\BenchServer.pb into it). Uses port 12405. +# Usage: powershell -ExecutionPolicy Bypass -File Tests\GetMessages-Test.ps1 +param([string]$Build = (Join-Path $PSScriptRoot "..\Build")) +$ErrorActionPreference = "Stop" +$Build = (Resolve-Path $Build).Path +$Dir = Join-Path $Build "_getmessagestest" +Remove-Item -Recurse -Force $Dir -ErrorAction SilentlyContinue +New-Item -ItemType Directory $Dir | Out-Null +$Server = Join-Path $Build "Bench\BenchServer.exe" +$Port = 12405 +$Fails = 0 + +function New-KeyPair { + $L = & (Join-Path $Build "KeyGen.exe") + @{ Priv = $L[0] -replace "^PrivateKey = ", ""; Pub = $L[1] -replace "^PublicKey = ", "" } +} +function Test-Port($P) { + $C = New-Object System.Net.Sockets.TcpClient + try { $A = $C.BeginConnect("127.0.0.1", $P, $null, $null); $A.AsyncWaitHandle.WaitOne(200) -and $C.Connected } catch { $false } finally { $C.Close() } +} +# Runs a tool, its output as lines (Lines) and joined (Out). +function Tool([string]$Name, [string[]]$A) { + $O = @(& (Join-Path $Build $Name) @A 2>&1 | ForEach-Object { "$_" }) + @{ Code = $LASTEXITCODE; Lines = $O; Out = ($O -join " | ") } +} +function Check([string]$What, [bool]$Ok, [string]$Detail) { + if (-not $Ok) { $script:Fails++ } + if ($Detail.Length -gt 300) { $Detail = $Detail.Substring(0, 300) + "... (" + $Detail.Length + " chars)" } + "{0} {1}`n -> {2}" -f $(if ($Ok) { "PASS" } else { "FAIL" }), $What, $Detail +} +function Expect([string]$What, $Result, [string]$Pattern, [int]$Code = 0) { + Check $What (($Result.Code -eq $Code) -and ($Result.Out -match $Pattern)) ("[{0}] {1}" -f $Result.Code, $Result.Out) +} +# The ids GetMessages printed, in order. +function Ids($Result) { + @($Result.Lines | Where-Object { $_ -match "^\d+`t" } | ForEach-Object { [long]($_ -split "`t", 2)[0] }) +} +# Whether Ids are exactly From..To. +function Is-Run($Ids, [long]$From, [long]$To) { + $Want = if ($To -ge $From) { @($From..$To) } else { @() } + ($Ids -join ",") -eq ($Want -join ",") +} +function Push($Data, $Ini, [string]$Topic = "") { + $F = Join-Path $Dir "push.txt" + [IO.File]::WriteAllText($F, $Data, (New-Object System.Text.UTF8Encoding $false)) + $A = @() + if ($Topic) { $A += @("-t", $Topic) } + Tool "PushMessage.exe" ($A + @("@$F", $Ini)) +} + +$S = New-KeyPair; $K = New-KeyPair; $L = New-KeyPair + +Set-Content (Join-Path $Dir "server.ini") -Encoding Ascii -Value @" +[BakaShrot] +PrivateKey = $($S.Priv) +Topic = logs +Node = server + +[BakaShrot.Topics] +logs = 1 +secret = 2 + +[BakaShrot.Nodes] +server = 1 +kitchen = 5 +lounge = 6 +empty = 7 + +[BakaShrot.Server] +Host = 127.0.0.1 +Port = $Port +DatabasePath = $(Join-Path $Dir "server.sqlite") + +[BakaShrot.Client.kitchen] +PublicKeys = $($K.Pub) +Identities = logs:kitchen +PushTopics = logs;secret +ReadTopics = * +AllowQuery = 1 + +[BakaShrot.Client.lounge] +PublicKeys = $($L.Pub) +Identities = logs:lounge +ReadTopics = logs +"@ + +function Client-Ini($Name, $Keys) { + $P = Join-Path $Dir "$Name.ini" + Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($Keys.Priv)`r`nPublicKey = $($Keys.Pub)`r`nTopic = logs`r`nNode = $Name`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($S.Pub)" + $P +} +$Kitchen = Client-Ini "kitchen" $K +$Lounge = Client-Ini "lounge" $L + +if (Test-Port $Port) { throw "Port $Port is already in use" } +$Stop = Join-Path $Dir "server.stop" +$P = Start-Process -FilePath $Server -ArgumentList "`"$(Join-Path $Dir "server.ini")`"", "`"$Stop`"" -WorkingDirectory $Dir ` + -RedirectStandardOutput (Join-Path $Dir "server.log") -WindowStyle Hidden -PassThru +$null = $P.Handle +$Follower = $null +try { + $D = (Get-Date).AddSeconds(15) + while (-not (Test-Port $Port)) { + if ($P.HasExited) { throw "The server exited: $(Get-Content (Join-Path $Dir "server.log") -Raw)" } + if ((Get-Date) -gt $D) { throw "The server isn't listening" } + Start-Sleep -Milliseconds 100 + } + + # --- Nothing yet ---------------------------------------------------------- + + $R = Tool "GetMessages.exe" @("logs", "kitchen", $Kitchen) + Check "No messages yet: nothing printed, not a failure" ($R.Code -eq 0 -and $R.Lines.Count -eq 0) ("[{0}] {1}" -f $R.Code, $R.Out) + + $R = Tool "GetMessages.exe" @("logs", "kitchen", "--after", "latest", $Kitchen) + Check "--after latest with no messages yet: nothing, not a failure" ($R.Code -eq 0 -and $R.Lines.Count -eq 0) ("[{0}] {1}" -f $R.Code, $R.Out) + + # --- 120 small ones ------------------------------------------------------- + + $Started = Get-Date + $Pushed = 0 + for ($i = 1; $i -le 120; $i++) { + $R = Push ('{"i":' + $i + '}') $Kitchen + if ($R.Code -eq 0) { $Pushed++ } + } + Check "120 pushes" ($Pushed -eq 120) ("{0} pushed in {1:N1} s" -f $Pushed, ((Get-Date) - $Started).TotalSeconds) + + $R = Tool "GetMessages.exe" @("logs", "kitchen", $Kitchen) + $Ids = Ids $R + Check "Default: the first 100, in order" ($R.Code -eq 0 -and (Is-Run $Ids 1 100)) ("[{0}] {1} ids, {2}..{3}" -f $R.Code, $Ids.Count, $Ids[0], $Ids[-1]) + Check "Each line is the id, a tab and the data as stored" ($R.Lines[0] -eq "1`t{`"i`":1}" -and $R.Lines[99] -eq "100`t{`"i`":100}") ("'{0}' / '{1}'" -f $R.Lines[0], $R.Lines[99]) + + $R = Tool "GetMessages.exe" @("logs", "kitchen", "--limit", "0", $Kitchen) + Check "--limit 0: all 120" ($R.Code -eq 0 -and (Is-Run (Ids $R) 1 120)) ("[{0}] {1} lines" -f $R.Code, $R.Lines.Count) + + $R = Tool "GetMessages.exe" @("logs", "kitchen", "--after", "115", $Kitchen) + Check "--after 115: 116-120" ($R.Code -eq 0 -and (Is-Run (Ids $R) 116 120)) ("[{0}] {1}" -f $R.Code, $R.Out) + + $R = Tool "GetMessages.exe" @("logs", "kitchen", "--after", "10", "--limit", "7", $Kitchen) + Check "--after 10 --limit 7: 11-17" ($R.Code -eq 0 -and (Is-Run (Ids $R) 11 17)) ("[{0}] {1}" -f $R.Code, $R.Out) + + $R = Tool "GetMessages.exe" @("logs", "kitchen", "--after", "120", $Kitchen) + Check "--after the last one: nothing, not a failure" ($R.Code -eq 0 -and $R.Lines.Count -eq 0) ("[{0}] {1}" -f $R.Code, $R.Out) + + $R = Tool "GetMessages.exe" @("logs", "kitchen", "--after", "latest", $Kitchen) + Check "--after latest: nothing" ($R.Code -eq 0 -and $R.Lines.Count -eq 0) ("[{0}] {1}" -f $R.Code, $R.Out) + + $R = Tool "GetMessages.exe" @("1", "5", "--after", "118", $Kitchen) + Check "By ids (1, 5): 119-120" ($R.Code -eq 0 -and (Is-Run (Ids $R) 119 120)) ("[{0}] {1}" -f $R.Code, $R.Out) + + $R = Tool "GetMessages.exe" @("logs", "kitchen", "--after", "100", $Lounge) + Check "Another client allowed to read logs: 101-120" ($R.Code -eq 0 -and (Is-Run (Ids $R) 101 120)) ("[{0}] {1} lines" -f $R.Code, $R.Lines.Count) + + # --- Refusals ------------------------------------------------------------- + + $null = Push '{"s":1}' $Kitchen "secret" + $R = Tool "GetMessages.exe" @("secret", "kitchen", $Kitchen) + Check "A topic in ReadTopics (*): read" ($R.Code -eq 0 -and (Is-Run (Ids $R) 1 1)) ("[{0}] {1}" -f $R.Code, $R.Out) + Expect "A topic not in ReadTopics: refused" (Tool "GetMessages.exe" @("secret", "kitchen", $Lounge)) "Not allowed to read topic 'secret'" 1 + Expect "Unknown node: refused" (Tool "GetMessages.exe" @("logs", "nobody", $Kitchen)) "Unknown node 'nobody'" 1 + Expect "Unknown topic: refused" (Tool "GetMessages.exe" @("nothing", "kitchen", $Kitchen)) "Unknown topic 'nothing'" 1 + $R = Tool "GetMessages.exe" @("logs", "empty", $Kitchen) + Check "A known node with no messages: nothing, not a failure" ($R.Code -eq 0 -and $R.Lines.Count -eq 0) ("[{0}] {1}" -f $R.Code, $R.Out) + Expect "Bad --after: refused by the tool" (Tool "GetMessages.exe" @("logs", "kitchen", "--after", "-3", $Kitchen)) "Invalid --after" 1 + Expect "Unknown option: refused by the tool" (Tool "GetMessages.exe" @("logs", "kitchen", "--nope", $Kitchen)) "Unknown option" 1 + + # --- Data that isn't one line of JSON ------------------------------------- + + $null = Push "plain text, not JSON" $Kitchen + $null = Push "two`nlines" $Kitchen + $R = Tool "GetMessages.exe" @("logs", "kitchen", "--after", "120", $Kitchen) + Check "Non-JSON data printed as stored, a line break spans lines" ( + $R.Code -eq 0 -and $R.Lines.Count -eq 3 -and $R.Lines[0] -eq "121`tplain text, not JSON" -and $R.Lines[1] -eq "122`ttwo" -and $R.Lines[2] -eq "lines" + ) ($R.Lines -join " / ") + + # --- Answers split at ~1 MB ----------------------------------------------- + + # 5 of 600 KB and one of 3 MB: one per answer, the big one alone. + $Sizes = @(600KB, 600KB, 600KB, 3MB, 600KB, 600KB) + $BigOk = 0 + foreach ($Size in $Sizes) { + $Data = '{"pad":"' + ("x" * ($Size - 10)) + '"}' + if ((Push $Data $Kitchen).Code -eq 0) { $BigOk++ } + } + Check "6 big pushes (5 x 600 KB, 3 MB)" ($BigOk -eq 6) "$BigOk pushed" + + $R = Tool "GetMessages.exe" @("logs", "kitchen", "--after", "122", $Kitchen) + $Ids = Ids $R + $Lengths = @($R.Lines | ForEach-Object { (($_ -split "`t", 2)[1]).Length }) + $WantLengths = @($Sizes | ForEach-Object { $_ }) + Check "All 6 read back whole, over several answers" ( + $R.Code -eq 0 -and (Is-Run $Ids 123 128) -and (($Lengths -join ",") -eq ($WantLengths -join ",")) + ) ("[{0}] ids {1}, lengths {2}" -f $R.Code, ($Ids -join ","), ($Lengths -join ",")) + + $R = Tool "GetMessages.exe" @("logs", "kitchen", "--after", "122", "--limit", "2", $Kitchen) + Check "--limit 2 over big ones: 123-124" ($R.Code -eq 0 -and (Is-Run (Ids $R) 123 124)) ("[{0}] {1} lines" -f $R.Code, $R.Lines.Count) + + # --- --follow --------------------------------------------------------------- + + $FollowOut = Join-Path $Dir "follow.out" + $Follower = Start-Process -FilePath (Join-Path $Build "GetMessages.exe") ` + -ArgumentList "logs", "kitchen", "--after", "latest", "--follow", "--interval", "100", "`"$Kitchen`"" ` + -WorkingDirectory $Build -RedirectStandardOutput $FollowOut -WindowStyle Hidden -PassThru + $null = $Follower.Handle + Start-Sleep -Milliseconds 1500 + Check "--follow keeps running once caught up" (-not $Follower.HasExited) $(if ($Follower.HasExited) { "exited with $($Follower.ExitCode)" } else { "running" }) + + $null = Push '{"f":1}' $Kitchen + $null = Push '{"f":2}' $Kitchen + $null = Push '{"f":3}' $Kitchen + $D = (Get-Date).AddSeconds(10) + do { + Start-Sleep -Milliseconds 200 + $Lines = @() + try { + $Fs = [IO.File]::Open($FollowOut, "Open", "Read", "ReadWrite") + $Text = (New-Object IO.StreamReader($Fs)).ReadToEnd(); $Fs.Close() + $Lines = @($Text -split "`r?`n" | Where-Object { $_ -ne "" }) + } catch { } + } while ($Lines.Count -lt 3 -and (Get-Date) -lt $D) + Check "--follow --after latest: only the 3 new ones" ( + $Lines.Count -eq 3 -and $Lines[0] -eq "129`t{`"f`":1}" -and $Lines[2] -eq "131`t{`"f`":3}" + ) ($Lines -join " / ") + + # The server going away ends it with a failure. + Set-Content $Stop "x" + if (-not $P.WaitForExit(15000)) { Stop-Process -Id $P.Id -Force } + $Ended = $Follower.WaitForExit(15000) + Check "--follow fails once the server is gone" ($Ended -and $Follower.ExitCode -eq 1) $(if ($Ended) { "exit code $($Follower.ExitCode)" } else { "still running" }) + + $Log = Get-Content (Join-Path $Dir "server.log") -Raw + $Bad = @($Log -split "`r?`n" | Where-Object { $_ -match "invalid|unexpected|Failed" }) + Check "Server log: no invalid or unexpected packets" ($Bad.Count -eq 0) $(if ($Bad.Count) { $Bad -join " / " } else { "clean" }) +} +finally { + if ($Follower -and -not $Follower.HasExited) { Stop-Process -Id $Follower.Id -Force } + if (-not $P.HasExited) { + Set-Content $Stop "x" + if (-not $P.WaitForExit(15000)) { Stop-Process -Id $P.Id -Force } + } +} + +"" +if ($Fails -eq 0) { "All checks passed" } else { "$Fails check(s) failed" } +exit $(if ($Fails -eq 0) { 0 } else { 1 }) diff --git a/Tests/HandshakeTest.pb b/Tests/HandshakeTest.pb new file mode 100644 index 0000000..ba85666 --- /dev/null +++ b/Tests/HandshakeTest.pb @@ -0,0 +1,162 @@ +; ============================================================================ +; Simulates the Hello -> ChallengeRequest -> ChallengeResponse handshake +; between a client and a server, without sockets. +; Each "send" is an encoded buffer, each "receive" decodes that same buffer. +; +; Compile as a console program, exits with 0 if everything passed, 1 otherwise. +; The keys and signatures are placeholders, only the packets and the nonce +; check are tested: the cryptography is Tests/CipherTest.pb's. +; ============================================================================ + +EnableExplicit + +XIncludeFile "../Commons/Networking/Packets/HelloPacket.pbi" +XIncludeFile "../Commons/Networking/Packets/ChallengeRequestPacket.pbi" +XIncludeFile "../Commons/Networking/Packets/ChallengeResponsePacket.pbi" + + +; Prints the result of a check, and stops the test on the first failure. +Procedure Check(Condition.b, Message.s) + If Condition + PrintN("[OK] " + Message) + ProcedureReturn + EndIf + + PrintN("[FAIL] " + Message) + End 1 +EndProcedure + + +Define *Wire, WireSize.Integer, *View.MsgPackData + +; Client side +Define ClientHello.BakaShrot_AuthHello +Define *ClientChallenge.BakaShrot_ChallengeRequest +Define ClientResponse.BakaShrot_ChallengeResponse + +; Server side +Define *ServerHello.BakaShrot_AuthHello +Define ServerChallenge.BakaShrot_ChallengeRequest +Define *ServerResponse.BakaShrot_ChallengeResponse +Define *ServerReplayed.BakaShrot_ChallengeResponse +Define *ServerWrongType.BakaShrot_ChallengeResponse + +; Nonce the server keeps for this connection, until the response arrives. +Define *ServerConnectionNonce = AllocateMemory(#BakaShrot_NonceSize) +; Nonce a second connection got, to test a replayed response. +Define *OtherConnectionNonce = AllocateMemory(#BakaShrot_NonceSize) + +OpenConsole() + +Check(Bool(*ServerConnectionNonce And *OtherConnectionNonce), "Allocated the server's nonce buffers") +Check(Bool(OpenCryptRandom()), "Opened the secure random generator") + + +; --- 1. Client -> Server: Hello --------------------------------------------- + +ClientHello\ClientTopic = "logs" +ClientHello\ClientNode = "34" +ClientHello\ClientPubKeyB64 = "Q2xpZW50UHViS2V5" +Check(Bool(CryptRandomData(@ClientHello\ClientSessionKey[0], #BakaShrot_SessionKeySize)), "Client made a session key") + +*Wire = BakaShrot_HelloPacket_Encode(@ClientHello, @WireSize) +Check(Bool(*Wire), "Client encoded its hello") + +*View = MsgPackWrapMsgBuffer(*Wire, WireSize\i) +Check(Bool(*View), "Server wrapped the hello") +*ServerHello = BakaShrot_HelloPacket_Decode(*View) +MsgPackFree(*View, #False) +FreeMemory(*Wire) + +Check(Bool(*ServerHello), "Server decoded the hello") +Check(Bool(*ServerHello\ClientTopic = "logs"), "Hello's ClientTopic survived") +Check(Bool(*ServerHello\ClientNode = "34"), "Hello's ClientNode survived") +Check(Bool(*ServerHello\ClientPubKeyB64 = "Q2xpZW50UHViS2V5"), "Hello's ClientPubKeyB64 survived") +Check(CompareMemory(@*ServerHello\ClientSessionKey[0], @ClientHello\ClientSessionKey[0], #BakaShrot_SessionKeySize), "Hello's ClientSessionKey survived") + + +; --- 2. Server -> Client: ChallengeRequest ---------------------------------- + +Check(Bool(CryptRandomData(@ServerChallenge\Nonce[0], #BakaShrot_NonceSize)), "Server generated a nonce") +CopyMemory(@ServerChallenge\Nonce[0], *ServerConnectionNonce, #BakaShrot_NonceSize) +ServerChallenge\ChallengeB64 = "U2VydmVyQ2hhbGxlbmdl" +Check(Bool(CryptRandomData(@ServerChallenge\ServerSessionKey[0], #BakaShrot_SessionKeySize)), "Server made a session key") +Check(Bool(CryptRandomData(@ServerChallenge\ServerSignature[0], #BakaShrot_HandshakeSignatureSize)), "Server made a placeholder signature") + +*Wire = BakaShrot_ChallengeRequestPacket_Encode(@ServerChallenge, @WireSize) +Check(Bool(*Wire), "Server encoded the challenge request") + +*View = MsgPackWrapMsgBuffer(*Wire, WireSize\i) +Check(Bool(*View), "Client wrapped the challenge request") +*ClientChallenge = BakaShrot_ChallengeRequestPacket_Decode(*View) +MsgPackFree(*View, #False) +FreeMemory(*Wire) + +Check(Bool(*ClientChallenge), "Client decoded the challenge request") +Check(Bool(*ClientChallenge\ChallengeB64 = "U2VydmVyQ2hhbGxlbmdl"), "Challenge's ChallengeB64 survived") +Check(CompareMemory(@*ClientChallenge\Nonce[0], *ServerConnectionNonce, #BakaShrot_NonceSize), "Challenge's nonce survived") +Check(CompareMemory(@*ClientChallenge\ServerSessionKey[0], @ServerChallenge\ServerSessionKey[0], #BakaShrot_SessionKeySize), "Challenge's ServerSessionKey survived") +Check(CompareMemory(@*ClientChallenge\ServerSignature[0], @ServerChallenge\ServerSignature[0], #BakaShrot_HandshakeSignatureSize), "Challenge's ServerSignature survived") + + +; --- 3. Client -> Server: ChallengeResponse --------------------------------- + +; Placeholder for the real signature of ChallengeB64 + Nonce. +ClientResponse\ChallengeResponseB64 = "U2lnbmVkOiAiU2VydmVyQ2hhbGxlbmdlIg==" +CopyMemory(@*ClientChallenge\Nonce[0], @ClientResponse\Nonce[0], #BakaShrot_NonceSize) + +*Wire = BakaShrot_ChallengeResponsePacket_Encode(@ClientResponse, @WireSize) +Check(Bool(*Wire), "Client encoded the challenge response") + +*View = MsgPackWrapMsgBuffer(*Wire, WireSize\i) +Check(Bool(*View), "Server wrapped the challenge response") +*ServerResponse = BakaShrot_ChallengeResponsePacket_Decode(*View) +MsgPackFree(*View, #False) + +Check(Bool(*ServerResponse), "Server decoded the challenge response") +Check(Bool(*ServerResponse\ChallengeResponseB64 = "U2lnbmVkOiAiU2VydmVyQ2hhbGxlbmdlIg=="), "Response's ChallengeResponseB64 survived") +Check(CompareMemory(@*ServerResponse\Nonce[0], *ServerConnectionNonce, #BakaShrot_NonceSize), "Server accepted the nonce it issued") + + +; --- 4. Replay: the same response sent on another connection ---------------- +; *Wire still holds the response captured in step 3. + +Check(Bool(CryptRandomData(*OtherConnectionNonce, #BakaShrot_NonceSize)), "Server generated a nonce for another connection") + +*View = MsgPackWrapMsgBuffer(*Wire, WireSize\i) +Check(Bool(*View), "Server wrapped the replayed response") +*ServerReplayed = BakaShrot_ChallengeResponsePacket_Decode(*View) +MsgPackFree(*View, #False) +FreeMemory(*Wire) + +Check(Bool(*ServerReplayed), "Replayed response is still a well-formed packet") +Check(Bool(Not CompareMemory(@*ServerReplayed\Nonce[0], *OtherConnectionNonce, #BakaShrot_NonceSize)), "Server rejected the replayed response's nonce") + + +; --- 5. A hello sent where a challenge response is expected ------------------ + +*Wire = BakaShrot_HelloPacket_Encode(@ClientHello, @WireSize) +Check(Bool(*Wire), "Client encoded a second hello") + +*View = MsgPackWrapMsgBuffer(*Wire, WireSize\i) +Check(Bool(*View), "Server wrapped the misplaced hello") +*ServerWrongType = BakaShrot_ChallengeResponsePacket_Decode(*View) +MsgPackFree(*View, #False) +FreeMemory(*Wire) + +Check(Bool(Not *ServerWrongType), "Challenge response decoder rejected a hello") + + +; --- Cleanup ----------------------------------------------------------------- + +FreeStructure(*ServerHello) +FreeStructure(*ClientChallenge) +FreeStructure(*ServerResponse) +FreeStructure(*ServerReplayed) +FreeMemory(*ServerConnectionNonce) +FreeMemory(*OtherConnectionNonce) +CloseCryptRandom() + +PrintN("") +PrintN("Handshake simulation passed.") +End 0 diff --git a/Tests/Names-Test.ps1 b/Tests/Names-Test.ps1 new file mode 100644 index 0000000..b03c014 --- /dev/null +++ b/Tests/Names-Test.ps1 @@ -0,0 +1,283 @@ +# End-to-end test of topic/node names, filters and replication by name: +# two servers with different ids for the same names, strict "named on both +# sides" replication, wildcards (taking undeclared names, filtering), +# old and new config keys, the list tool. +# Needs Build\ (Build.ps1) and Build\Bench\BenchServer.exe (Bench-Replication.ps1, +# or compile Tests\Bench\BenchServer.pb into it). Uses ports 12401-12402. +# Usage: powershell -ExecutionPolicy Bypass -File Tests\Names-Test.ps1 +param([string]$Build = (Join-Path $PSScriptRoot "..\Build")) +$ErrorActionPreference = "Stop" +$Dir = Join-Path $Build "_namestest" +Remove-Item -Recurse -Force $Dir -ErrorAction SilentlyContinue +New-Item -ItemType Directory $Dir | Out-Null +$Server = Join-Path $Build "Bench\BenchServer.exe" +$Fails = 0 + +function New-KeyPair { + $L = & (Join-Path $Build "KeyGen.exe") + @{ Priv = $L[0] -replace "^PrivateKey = ", ""; Pub = $L[1] -replace "^PublicKey = ", "" } +} +function Test-Port($P) { + $C = New-Object System.Net.Sockets.TcpClient + try { $A = $C.BeginConnect("127.0.0.1", $P, $null, $null); $A.AsyncWaitHandle.WaitOne(200) -and $C.Connected } catch { $false } finally { $C.Close() } +} +function Tool([string]$Name, [string[]]$A) { + $O = & (Join-Path $Build $Name) @A 2>&1 + @{ Code = $LASTEXITCODE; Out = ($O -join " | ") } +} +function Expect([string]$What, $Result, [string]$Pattern, [int]$Code = 0) { + $Ok = ($Result.Code -eq $Code) -and ($Result.Out -match $Pattern) + if (-not $Ok) { $script:Fails++ } + "{0} {1}`n -> [{2}] {3}" -f $(if ($Ok) { "PASS" } else { "FAIL" }), $What, $Result.Code, $Result.Out +} +function Start-Srv($Name) { + $Stop = Join-Path $Dir "$Name.stop" + Remove-Item $Stop -ErrorAction SilentlyContinue + $P = Start-Process -FilePath $Server -ArgumentList "`"$(Join-Path $Dir "$Name.ini")`"", "`"$Stop`"" -WorkingDirectory $Dir ` + -RedirectStandardOutput (Join-Path $Dir "$Name.log") -WindowStyle Hidden -PassThru + $null = $P.Handle + @{ P = $P; Stop = $Stop; Name = $Name } +} +function Stop-Srv($S) { + Set-Content $S.Stop "x" + if (-not $S.P.WaitForExit(15000)) { Stop-Process -Id $S.P.Id -Force } +} +function Wait-Port($Port, $S) { + $D = (Get-Date).AddSeconds(15) + while (-not (Test-Port $Port)) { + if ($S.P.HasExited) { throw "$($S.Name) exited: $(Get-Content (Join-Path $Dir "$($S.Name).log") -Raw)" } + if ((Get-Date) -gt $D) { throw "$($S.Name) not listening" } + Start-Sleep -Milliseconds 100 + } +} +function Query($Sql, $Ini) { + $F = Join-Path $Dir "q.sql"; Set-Content $F -Encoding Ascii -Value $Sql + Tool "Query.exe" @("@$F", $Ini) +} + +$A = New-KeyPair; $B = New-KeyPair; $K = New-KeyPair; $G = New-KeyPair; $BC = New-KeyPair; $K2 = New-KeyPair + +# --- Server A: new keys, logs = 1, sensors = 2 ----------------------------- +Set-Content (Join-Path $Dir "a.ini") -Encoding Ascii -Value @" +[BakaShrot] +PrivateKey = $($A.Priv) +Topic = logs +Node = serverA + +[BakaShrot.Topics] +logs = 1 +sensors = 2 +secret = 3 +sensors.temp = 4 + +[BakaShrot.Nodes] +serverA = 10 +serverB = 11 +kitchen = 2 +garage = 5 +kitchen-2 = 6 +blocal = 20 +bsecret = 21 + +[BakaShrot.Server] +Host = 127.0.0.1 +Port = 12401 +ReplicatingTopics = logs;sensors* +DatabasePath = $(Join-Path $Dir "a.sqlite") +PeerSyncInterval = 1 +PeerRetryDelay = 1 + +[BakaShrot.Peer.b] +Host = 127.0.0.1 +Port = 12402 +Topic = logs +Node = serverB +PublicKey = $($B.Pub) +AcceptTopics = logs + +[BakaShrot.Client.b] +PublicKeys = $($B.Pub) +Identities = logs:serverB + +[BakaShrot.Client.kitchen] +PublicKeys = $($K.Pub) +Identities = logs:kitchen +PushTopics = logs;sensors* +ReadTopics = * +AllowQuery = 1 + +[BakaShrot.Client.kitchen2] +PublicKeys = $($K2.Pub) +Identities = logs:kitchen-2 +PushTopics = logs;sensors.temp + +[BakaShrot.Client.garage] +PublicKeys = $($G.Pub) +Identities = logs:garage +"@ + +# --- Server B: the old key names, logs = 200, sensors = 201 ---------------- +# garage isn't named here (dropped from A), extra isn't named on A (dropped +# from B), node 9 isn't named anywhere (dropped both ways). sensors.temp and +# kitchen-2 aren't named here either, but taken by AcceptTopics/AcceptNodes +# patterns. bsecret is named on both, but held back by SendNodes. +function Write-B([string]$Kitchen) { +Set-Content (Join-Path $Dir "b.ini") -Encoding Ascii -Value @" +[BakaShrot] +PrivateKey = $($B.Priv) +TopicId = logs +NodeId = serverB + +[BakaShrot.Topics] +logs = 200 +sensors = 201 +extra = 202 + +[BakaShrot.Nodes] +serverA = 1 +serverB = 2 +kitchen = $Kitchen +blocal = 3 +bsecret = 4 + +[BakaShrot.Server] +Host = 127.0.0.1 +Port = 12402 +ReplicatingTopicIds = * +DatabasePath = $(Join-Path $Dir "b.sqlite") +PeerSyncInterval = 1 +PeerRetryDelay = 1 + +[BakaShrot.Peer.a] +Host = 127.0.0.1 +Port = 12401 +TopicId = logs +NodeId = serverA +PublicKey = $($A.Pub) +AcceptTopics = logs;sensors;sensors.* +AcceptNodes = kitchen;blocal;kitchen-* +SendNodes = blocal;9 + +[BakaShrot.Client.a] +PublicKeys = $($A.Pub) +Identities = logs:serverA + +[BakaShrot.Client.local] +PublicKeys = $($BC.Pub) +Identities = sensors:blocal;logs:9;logs:bsecret +PushTopics = sensors;logs;extra +ReadTopics = * +AllowQuery = 1 +"@ +} +Write-B "7" + +# New key names, except garage's (TopicId / NodeId, by ids). +$ServerKeys = @{ 12401 = $A.Pub; 12402 = $B.Pub } +function Client-Ini($Name, $Keys, $Topic, $Node, $Port, [switch]$OldKeys) { + $P = Join-Path $Dir "$Name.ini" + $TK = "Topic"; $NK = "Node" + if ($OldKeys) { $TK = "TopicId"; $NK = "NodeId" } + Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($Keys.Priv)`r`nPublicKey = $($Keys.Pub)`r`n$TK = $Topic`r`n$NK = $Node`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($ServerKeys[$Port])" + $P +} +$Kitchen = Client-Ini "kitchen" $K "logs" "kitchen" 12401 +$Garage = Client-Ini "garage" $G "1" "5" 12401 -OldKeys +$Local = Client-Ini "local" $BC "sensors" "blocal" 12402 +$Anon = Client-Ini "anon" $BC "logs" "9" 12402 +$BSecret = Client-Ini "bsecret" $BC "logs" "bsecret" 12402 +$Kitchen2 = Client-Ini "kitchen2" $K2 "logs" "kitchen-2" 12401 +Set-Content (Join-Path $Dir "m1.json") -Encoding Ascii -Value '{"temp":21}' +Set-Content (Join-Path $Dir "m2.json") -Encoding Ascii -Value '{"temp":22,"where":"kitchen"}' +Set-Content (Join-Path $Dir "m3.json") -Encoding Ascii -Value '{"from":"b-local"}' +$M1 = "@" + (Join-Path $Dir "m1.json"); $M2 = "@" + (Join-Path $Dir "m2.json"); $M3 = "@" + (Join-Path $Dir "m3.json") + +$SA = Start-Srv "a"; $SB = Start-Srv "b" +try { + Wait-Port 12401 $SA; Wait-Port 12402 $SB + "--- Server A: pushes and the push filter" + Expect "kitchen pushes into its own topic (logs)" (Tool "PushMessage.exe" @($M1, $Kitchen)) "message #1" + Expect "kitchen pushes into sensors by name" (Tool "PushMessage.exe" @("-t", "sensors", $M2, $Kitchen)) "message #1" + Expect "kitchen pushes into logs by id" (Tool "PushMessage.exe" @("-t", "1", $M2, $Kitchen)) "message #2" + Expect "kitchen can't push into secret" (Tool "PushMessage.exe" @("-t", "secret", $M1, $Kitchen)) "Not allowed to push to topic 'secret'" 1 + Expect "unknown topic refused" (Tool "PushMessage.exe" @("-t", "nope", $M1, $Kitchen)) "Unknown topic 'nope'" 1 + Expect "garage (old keys, by ids 1:5) pushes into logs" (Tool "PushMessage.exe" @($M1, $Garage)) "message #1" + Expect "kitchen pushes into sensors.temp (PushTopics sensors*)" (Tool "PushMessage.exe" @("-t", "sensors.temp", $M2, $Kitchen)) "message #1" + Expect "kitchen-2 pushes into logs" (Tool "PushMessage.exe" @($M1, $Kitchen2)) "message #1" + Expect "kitchen-2 pushes into sensors.temp" (Tool "PushMessage.exe" @("-t", "sensors.temp", $M1, $Kitchen2)) "message #1" + Expect "kitchen-2 can't push into sensors" (Tool "PushMessage.exe" @("-t", "sensors", $M1, $Kitchen2)) "Not allowed to push to topic 'sensors'" 1 + + "--- Server A: reads and the read filter" + Expect "garage reads logs:kitchen by name" (Tool "GetLatestMessage.exe" @("logs", "kitchen", $Garage)) "logs:kitchen#2 \(ids 1:2\)" + Expect "garage reads it by ids, case-insensitive name" (Tool "GetLatestMessage.exe" @("1", "KITCHEN", $Garage)) "logs:kitchen#2" + Expect "garage can't read sensors (default ReadTopics)" (Tool "GetLatestMessage.exe" @("sensors", "kitchen", $Garage)) "Not allowed to read topic 'sensors'" 1 + Expect "kitchen reads sensors (ReadTopics = *)" (Tool "GetLatestMessage.exe" @("sensors", "kitchen", $Kitchen)) "sensors:kitchen#1 \(ids 2:2\)" + + "--- Server A: resolving and listing" + Expect "kitchen resolves topic sensors" (Tool "Resolve.exe" @("topic", "sensors", $Kitchen)) "topic sensors = 2" + Expect "kitchen resolves topic id 1" (Tool "Resolve.exe" @("topic", "1", $Kitchen)) "topic logs = 1" + Expect "kitchen resolves node garage" (Tool "Resolve.exe" @("node", "garage", $Kitchen)) "node garage = 5" + Expect "garage can't resolve sensors (no access)" (Tool "Resolve.exe" @("topic", "sensors", $Garage)) "Unknown topic" 1 + Expect "kitchen can resolve secret (it may query)" (Tool "Resolve.exe" @("topic", "secret", $Kitchen)) "topic secret = 3" + Expect "kitchen lists every topic (it may query)" (Tool "ListNames.exe" @("topics", $Kitchen)) "Topics \(4\): \|\s+1 logs\s+config \|\s+2 sensors\s+config \|\s+3 secret\s+config \|\s+4 sensors.temp\s+config" + Expect "garage lists only the topics it can use" (Tool "ListNames.exe" @("topics", $Garage)) "Topics \(1\): \|\s+1 logs" + Expect "the nodes, as JSON" (Tool "ListNames.exe" @("nodes", "--json", $Kitchen)) '(?=.*"kind":"node")(?=.*\{[^}]*"name":"kitchen"[^}]*\})(?=.*\{[^}]*"id":2[,}])' + + "--- Server A: queries by name through the view" + Expect "messages view, by names" (Query "SELECT topic, node, message_id FROM messages WHERE topic = 'logs' AND node = 'kitchen' ORDER BY message_id" $Kitchen) '\[\["logs","kitchen","1"\],\["logs","kitchen","2"\]\]' + + "--- Replication, A -> B, translated (logs 1 -> 200, kitchen 2 -> 7)" + Start-Sleep -Seconds 4 + Expect "B has logs:kitchen, under its own ids" (Tool "GetLatestMessage.exe" @("logs", "kitchen", $Local)) "logs:kitchen#2 \(ids 200:7\)" + Expect "B has sensors:kitchen" (Tool "GetLatestMessage.exe" @("sensors", "kitchen", $Local)) "sensors:kitchen#1 \(ids 201:7\)" + Expect "B didn't get logs:garage (garage isn't named on B)" (Tool "GetLatestMessage.exe" @("logs", "garage", $Local)) "Unknown node 'garage'" 1 + Expect "B took sensors.temp by AcceptTopics sensors.* (new topic id 65535)" (Tool "GetLatestMessage.exe" @("sensors.temp", "kitchen", $Local)) "sensors.temp:kitchen#1 \(ids 65535:7\)" + Expect "B took kitchen-2 by AcceptNodes kitchen-* (new node id 65535)" (Tool "GetLatestMessage.exe" @("logs", "kitchen-2", $Local)) "logs:kitchen-2#1 \(ids 200:65535\)" + Expect "B: both new ones" (Tool "GetLatestMessage.exe" @("sensors.temp", "kitchen-2", $Local)) "sensors.temp:kitchen-2#1 \(ids 65535:65535\)" + Expect "B: added from the peer, nothing else" (Query "SELECT 'topic', name, topic_id FROM topics WHERE origin = 'peer' UNION ALL SELECT 'node', name, node_id FROM nodes WHERE origin = 'peer'" $Local) '\[\["topic","sensors.temp","65535"\],\["node","kitchen-2","65535"\]\]' + Expect "B's view: same messages by name" (Query "SELECT topic, node, message_id, topic_id, node_id FROM messages WHERE topic = 'sensors'" $Local) '\[\["sensors","kitchen","1","201","7"\]\]' + + "--- Replication, B -> A: only what A names and takes (AcceptTopics = logs)" + Expect "B's local pushes into sensors" (Tool "PushMessage.exe" @($M3, $Local)) "message #1" + Expect "B's local pushes into logs" (Tool "PushMessage.exe" @("-t", "logs", $M3, $Local)) "message #1" + Expect "B's local pushes into extra" (Tool "PushMessage.exe" @("-t", "extra", $M3, $Local)) "message #1" + Expect "B's unnamed node 9 pushes into logs" (Tool "PushMessage.exe" @($M3, $Anon)) "message #1" + Expect "B's bsecret pushes into logs" (Tool "PushMessage.exe" @($M3, $BSecret)) "message #1" + Start-Sleep -Seconds 4 + Expect "A got logs:blocal (ids 1:20)" (Tool "GetLatestMessage.exe" @("logs", "blocal", $Kitchen)) 'logs:blocal#1 \(ids 1:20\) \| \{"from":"b-local"\}' + Expect "A didn't get sensors:blocal (not accepted)" (Tool "GetLatestMessage.exe" @("sensors", "blocal", $Kitchen)) "No message" 1 + Expect "A didn't get logs:9 (unnamed)" (Tool "GetLatestMessage.exe" @("logs", "9", $Kitchen)) "No message" 1 + Expect "A didn't get logs:bsecret (B's SendNodes)" (Tool "GetLatestMessage.exe" @("logs", "bsecret", $Kitchen)) "No message" 1 + Expect "A's pairs, nothing more, nothing twice" (Query "SELECT topic, node, COUNT(*) FROM messages GROUP BY 1, 2 ORDER BY 1, 2" $Kitchen) '\[\["logs","blocal","1"\],\["logs","garage","1"\],\["logs","kitchen","2"\],\["logs","kitchen-2","1"\],\["sensors","kitchen","1"\],\["sensors.temp","kitchen","1"\],\["sensors.temp","kitchen-2","1"\]\]' +} finally { + Stop-Srv $SA; Stop-Srv $SB +} + +"--- No refusals: each side only sent what the other one knows" +$Refusals = @(Get-Content (Join-Path $Dir "a.log"), (Join-Path $Dir "b.log") | Select-String "replicated here|known here|refused:") +$Ok = $Refusals.Count -eq 0 +if (-not $Ok) { $Fails++ } +"{0} no replication refusals in either log`n -> {1}" -f $(if ($Ok) { "PASS" } else { "FAIL" }), $(if ($Ok) { "none" } else { $Refusals -join " | " }) +"A:"; Get-Content (Join-Path $Dir "a.log") | Select-String "\[Peer\] Sent|Names" | % { " $_" } +"B:"; Get-Content (Join-Path $Dir "b.log") | Select-String "\[Peer\] Sent|Names" | % { " $_" } + +"--- Conflict: B's config now says kitchen = 8, but its messages are under 7" +Write-B "8" +$SB = Start-Srv "b" +$SB.P.WaitForExit(15000) | Out-Null +$Log = Get-Content (Join-Path $Dir "b.log") -Raw +$Ok = $SB.P.HasExited -and $SB.P.ExitCode -eq 1 -and $Log -match "give it id 7" +if (-not $Ok) { $Fails++ } +"{0} B refuses to start`n -> [{1}] {2}" -f $(if ($Ok) { "PASS" } else { "FAIL" }), $SB.P.ExitCode, (($Log -split "`n") | Select-String "names don't match") +if (-not $SB.P.HasExited) { Stop-Srv $SB } + +"--- Conflict fixed: kitchen = 7 again" +Write-B "7" +$SB = Start-Srv "b" +try { + Wait-Port 12402 $SB + Expect "B starts, kitchen still 7" (Tool "ListNames.exe" @("nodes", $Local)) "\s+7 kitchen\s+config" +} finally { Stop-Srv $SB } + +"" +if ($Fails -eq 0) { "ALL PASSED" } else { "$Fails FAILED" } diff --git a/Tests/Python-Test.ps1 b/Tests/Python-Test.ps1 new file mode 100644 index 0000000..9ffde68 --- /dev/null +++ b/Tests/Python-Test.ps1 @@ -0,0 +1,116 @@ +# End-to-end test of the Python interactor (Interactors/Python/bakashrot.py): +# starts a server with an empty database and runs +# Interactors/Python/check_bakashrot.py against it, through Build\'s DLL, +# then Tests/wire_check.py: what goes over the wire is encrypted. +# Needs Build\ (Build.ps1), Build\Bench\BenchServer.exe (Bench-Replication.ps1, +# or compile Tests\Bench\BenchServer.pb into it) and a 64-bit Python 3.8+. +# Uses ports 12406 and 12407. +# Usage: powershell -ExecutionPolicy Bypass -File Tests\Python-Test.ps1 [-Python ] +param( + [string]$Build = (Join-Path $PSScriptRoot "..\Build"), + [string]$Python = "python" +) +$ErrorActionPreference = "Stop" +$Build = (Resolve-Path $Build).Path +$Dir = Join-Path $Build "_pythontest" +Remove-Item -Recurse -Force $Dir -ErrorAction SilentlyContinue +New-Item -ItemType Directory $Dir | Out-Null +$Server = Join-Path $Build "Bench\BenchServer.exe" +$Port = 12406 +$ProxyPort = 12407 + +function New-KeyPair { + $L = & (Join-Path $Build "KeyGen.exe") + @{ Priv = $L[0] -replace "^PrivateKey = ", ""; Pub = $L[1] -replace "^PublicKey = ", "" } +} +function Test-Port($P) { + $C = New-Object System.Net.Sockets.TcpClient + try { $A = $C.BeginConnect("127.0.0.1", $P, $null, $null); $A.AsyncWaitHandle.WaitOne(200) -and $C.Connected } catch { $false } finally { $C.Close() } +} + +$S = New-KeyPair; $K = New-KeyPair; $L = New-KeyPair + +Set-Content (Join-Path $Dir "server.ini") -Encoding Ascii -Value @" +[BakaShrot] +PrivateKey = $($S.Priv) +Topic = logs +Node = server + +[BakaShrot.Topics] +logs = 1 +secret = 2 + +[BakaShrot.Nodes] +server = 1 +kitchen = 5 +lounge = 6 + +[BakaShrot.Server] +Host = 127.0.0.1 +Port = $Port +DatabasePath = $(Join-Path $Dir "server.sqlite") + +[BakaShrot.Client.kitchen] +PublicKeys = $($K.Pub) +Identities = logs:kitchen +PushTopics = logs;secret +ReadTopics = * +AllowQuery = 1 + +[BakaShrot.Client.lounge] +PublicKeys = $($L.Pub) +Identities = logs:lounge +ReadTopics = logs +"@ + +function Client-Ini($Name, $Keys) { + $P = Join-Path $Dir "$Name.ini" + Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($Keys.Priv)`r`nPublicKey = $($Keys.Pub)`r`nTopic = logs`r`nNode = $Name`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($S.Pub)" + $P +} +$Kitchen = Client-Ini "kitchen" $K +$Lounge = Client-Ini "lounge" $L + +if (Test-Port $Port) { throw "Port $Port is already in use" } +$Stop = Join-Path $Dir "server.stop" +$P = Start-Process -FilePath $Server -ArgumentList "`"$(Join-Path $Dir "server.ini")`"", "`"$Stop`"" -WorkingDirectory $Dir ` + -RedirectStandardOutput (Join-Path $Dir "server.log") -WindowStyle Hidden -PassThru +$null = $P.Handle +$Code = 1 +try { + $D = (Get-Date).AddSeconds(15) + while (-not (Test-Port $Port)) { + if ($P.HasExited) { throw "The server exited: $(Get-Content (Join-Path $Dir "server.log") -Raw)" } + if ((Get-Date) -gt $D) { throw "The server isn't listening" } + Start-Sleep -Milliseconds 100 + } + + $env:PYTHONIOENCODING = "utf-8" + & $Python (Join-Path $PSScriptRoot "..\Interactors\Python\check_bakashrot.py") (Join-Path $Build "BakaShrot_Client.dll") $Kitchen $Lounge + $Code = $LASTEXITCODE + + $Bad = @(Get-Content (Join-Path $Dir "server.log") | Where-Object { $_ -match "invalid|unexpected|Failed|decrypt|sealed" }) + if ($Bad.Count) { "FAIL Server log: $($Bad -join ' / ')"; $Code = 1 } else { "PASS Server log: no invalid or unexpected packets" } + + # The wire: encrypted, tampering and a wrong server key refused. Another + # key pair's public key plays the wrong server's. + "" + & $Python -B (Join-Path $PSScriptRoot "wire_check.py") (Join-Path $Build "BakaShrot_Client.dll") $Kitchen $ProxyPort $L.Pub + if ($LASTEXITCODE) { $Code = 1 } + Start-Sleep -Milliseconds 300 + $Log = Get-Content (Join-Path $Dir "server.log") + $Checks = [ordered]@{ + "Server log: the tampered packet didn't decrypt" = "sent a packet that doesn't decrypt" + "Server log: the hello for another server wasn't opened" = "hello that isn't sealed for this server" + } + foreach ($Name in $Checks.Keys) { + if (@($Log | Where-Object { $_ -match [regex]::Escape($Checks[$Name]) }).Count) { "PASS $Name" } else { "FAIL $Name"; $Code = 1 } + } +} +finally { + if (-not $P.HasExited) { + Set-Content $Stop "x" + if (-not $P.WaitForExit(15000)) { Stop-Process -Id $P.Id -Force } + } +} +exit $Code diff --git a/Tests/wire_check.py b/Tests/wire_check.py new file mode 100644 index 0000000..2356e02 --- /dev/null +++ b/Tests/wire_check.py @@ -0,0 +1,144 @@ +"""What goes over the wire, run by Tests/Python-Test.ps1. + +Puts a TCP proxy between the client (BakaShrot_Client.dll, through +Interactors/Python/bakashrot.py) and the server, recording every byte, then +checks that: + - a pushed message, the client's identity and its topic never show up in + plain text, either way, handshake included; + - the message still makes it through and back; + - a byte flipped by the proxy after the handshake drops the connection; + - a client given another server's public key can't connect. + +Usage: wire_check.py +Exits with 0 if every check passed, 1 otherwise. +""" + +import os +import socket +import sys +import threading + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "Interactors", "Python")) +from bakashrot import BakaShrotError, Client # noqa: E402 + +dll_path, ini_path, proxy_port, other_key = sys.argv[1], sys.argv[2], int(sys.argv[3]), sys.argv[4] +fails = 0 + + +def check(what, ok, detail=""): + global fails + print(("PASS " if ok else "FAIL ") + what) + if detail: + print(" -> " + detail) + if not ok: + fails += 1 + + +class Proxy: + """Forwards one connection at a time to the server, keeping what passed. + tamper: flips a bit in the next chunk the client sends.""" + + def __init__(self, listen_port, server_host, server_port): + self.server = (server_host, server_port) + self.listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + self.listener.bind(("127.0.0.1", listen_port)) + self.listener.listen(4) + self.to_server = bytearray() + self.to_client = bytearray() + self.tamper = False + threading.Thread(target=self._accept, daemon=True).start() + + def _accept(self): + while True: + try: + client, _ = self.listener.accept() + except OSError: + return + upstream = socket.create_connection(self.server) + threading.Thread(target=self._pump, args=(client, upstream, True), daemon=True).start() + threading.Thread(target=self._pump, args=(upstream, client, False), daemon=True).start() + + def _pump(self, source, target, from_client): + try: + while True: + data = source.recv(65536) + if not data: + break + data = bytearray(data) + if from_client and self.tamper: + self.tamper = False + data[-1] ^= 0x01 + (self.to_server if from_client else self.to_client).extend(data) + target.sendall(data) + except OSError: + pass + for s in (source, target): + try: + s.shutdown(socket.SHUT_RDWR) + except OSError: + pass + s.close() + + +base = Client.from_ini(ini_path, dll_path) +proxy = Proxy(proxy_port, base.host, base.port) +marker = "wire-marker-7f3a91" + +client = Client(base.private_key, base.public_key, base.server_public_key, base.topic, base.node, + "127.0.0.1", proxy_port, dll_path) + +# Through the proxy, all of it recorded. +try: + client.connect() + message_id = client.push({"note": marker}) + latest = client.latest(base.topic, base.node) + check("Pushed and read back through the proxy", latest is not None and marker in latest.data, + latest.data if latest else "nothing") + pages = client.get_messages(base.topic, base.node, after=message_id - 1, limit=10) + check("Read as a run of messages too", any(marker in m.data for m in pages.messages)) + client.close() +except BakaShrotError as error: + check("Pushed and read back through the proxy", False, str(error)) + +wire_up, wire_down = bytes(proxy.to_server), bytes(proxy.to_client) +check("Something went through both ways", len(wire_up) > 200 and len(wire_down) > 200, + f"{len(wire_up)} bytes up, {len(wire_down)} down") +for needle in (marker, str(base.node), str(base.topic), base.public_key): + shown = needle.encode("utf-8") + check(f"'{needle[:20]}' never in plain text on the wire", shown not in wire_up and shown not in wire_down) + +# A bit flipped after the handshake: the server drops the connection. +try: + client.connect() + proxy.tamper = True + try: + client.push({"note": "tampered"}) + check("A tampered request drops the connection", False, "the push went through") + except BakaShrotError as error: + check("A tampered request drops the connection", not client.connected, str(error)) + client.close() +except BakaShrotError as error: + check("A tampered request drops the connection", False, "couldn't connect: " + str(error)) + +# Another server's key: the server can't open the Hello, nor sign for it. +impostor = Client(base.private_key, base.public_key, other_key, base.topic, base.node, + base.host, base.port, dll_path) +try: + impostor.connect() + check("Another server's public key can't connect", False, "it connected") + impostor.close() +except BakaShrotError as error: + check("Another server's public key can't connect", True, str(error)) + +# And the right one still can, straight to the server. +try: + base.connect() + check("The right key still connects", base.connected) + base.close() +except BakaShrotError as error: + check("The right key still connects", False, str(error)) + +print() +print("All checks passed" if not fails else f"{fails} check(s) failed") +sys.exit(1 if fails else 0) diff --git a/Tools/Common/ToolClient.pbi b/Tools/Common/ToolClient.pbi new file mode 100644 index 0000000..aa36e3f --- /dev/null +++ b/Tools/Common/ToolClient.pbi @@ -0,0 +1,133 @@ +; ============================================================================ +; BakaShrot Tools - Client connection +; +; Shared by the tools that talk to a server through BakaShrot_Client.dll. +; The DLL must be next to the tool, the identity and server come from an ini +; file laid out like the client.ini Build.ps1 writes: +; [BakaShrot] +; PrivateKey, PublicKey, Topic, Node, ServerHost, ServerPort, +; ServerPublicKey (the server's, it logs it when it starts) +; Topic and Node can be names or ids (Commons/Networking/Names.pbi). They +; were TopicId and NodeId before, still read when Topic and Node are missing. +; ============================================================================ + +XIncludeFile "../../Client/BakaShrot_Client_Prototypes.pbi" + + +; Loads the DLL, reads IniPath and connects to its server with its identity. +; Prints what failed and returns #False on failure, the DLL is then unloaded. +Procedure.i ToolClient_Connect(IniPath.s) + Protected PrivateKey.s, PublicKey.s, ServerPublicKey.s, Topic.s, Node.s, ServerHost.s, ServerPort.l + + If Not OpenPreferences(IniPath) + PrintN("Failed to open '" + IniPath + "'") + ProcedureReturn #False + EndIf + PreferenceGroup("BakaShrot") + PrivateKey = ReadPreferenceString("PrivateKey", "") + PublicKey = ReadPreferenceString("PublicKey", "") + ServerPublicKey = ReadPreferenceString("ServerPublicKey", "") + Topic = Trim(ReadPreferenceString("Topic", ReadPreferenceString("TopicId", ""))) + Node = Trim(ReadPreferenceString("Node", ReadPreferenceString("NodeId", ""))) + ServerHost = ReadPreferenceString("ServerHost", "") + ServerPort = ReadPreferenceLong("ServerPort", 0) + ClosePreferences() + + If Not BakaShrot_LoadClient(GetPathPart(ProgramFilename()) + "BakaShrot_Client.dll") + PrintN("Failed to load BakaShrot_Client.dll") + ProcedureReturn #False + EndIf + + If Not BakaShrot_SetPrivateKey(PrivateKey) + PrintN("Invalid PrivateKey in '" + IniPath + "'") + BakaShrot_UnloadClient() + ProcedureReturn #False + EndIf + + If Not BakaShrot_SetPublicKey(PublicKey) + PrintN("Invalid PublicKey in '" + IniPath + "'") + BakaShrot_UnloadClient() + ProcedureReturn #False + EndIf + + If Not BakaShrot_SetServerPublicKey(ServerPublicKey) + PrintN("Missing or invalid ServerPublicKey in '" + IniPath + "', the server logs it when it starts") + BakaShrot_UnloadClient() + ProcedureReturn #False + EndIf + + If Not BakaShrot_SetTopic(Topic) + PrintN("Invalid Topic '" + Topic + "' in '" + IniPath + "', expected a name or an id") + BakaShrot_UnloadClient() + ProcedureReturn #False + EndIf + + If Not BakaShrot_SetNode(Node) + PrintN("Invalid Node '" + Node + "' in '" + IniPath + "', expected a name or an id") + BakaShrot_UnloadClient() + ProcedureReturn #False + EndIf + + If Not BakaShrot_Connect(ServerHost, ServerPort) + PrintN("Failed to connect and authenticate to " + ServerHost + ":" + Str(ServerPort)) + BakaShrot_UnloadClient() + ProcedureReturn #False + EndIf + + ProcedureReturn #True +EndProcedure + + +; Disconnects and unloads the DLL. +Procedure ToolClient_Close() + BakaShrot_Disconnect() + BakaShrot_UnloadClient() +EndProcedure + + +; Prints why the last request failed. +Procedure ToolClient_PrintFailure() + If BakaShrot_IsConnected() + PrintN("Refused by the server: " + BakaShrot_GetRefusalReasonString()) + Else + PrintN("The connection to the server failed") + EndIf +EndProcedure + + +; Reads a whole UTF-8 text file (a byte order mark is skipped) into *Text. +; In one go: ReadString() with #PB_File_IgnoreEOL takes seconds on a 16 MB +; line. Prints why and returns #False if it can't be read. +Procedure.i ToolClient_ReadTextFile(Path.s, *Text.String) + Protected FileId.i, Size.q, *Data, Offset.i + + FileId = ReadFile(#PB_Any, Path) + If Not FileId + PrintN("Failed to open '" + Path + "'") + ProcedureReturn #False + EndIf + Size = Lof(FileId) + *Data = AllocateMemory(Size + 1) + If Not *Data + CloseFile(FileId) + PrintN("'" + Path + "' is too big to read") + ProcedureReturn #False + EndIf + If ReadData(FileId, *Data, Size) <> Size + FreeMemory(*Data) + CloseFile(FileId) + PrintN("Failed to read '" + Path + "'") + ProcedureReturn #False + EndIf + CloseFile(FileId) + + If Size >= 3 And PeekA(*Data) = $EF And PeekA(*Data + 1) = $BB And PeekA(*Data + 2) = $BF + Offset = 3 + EndIf + *Text\s = "" + If Size > Offset + *Text\s = PeekS(*Data + Offset, Size - Offset, #PB_UTF8 | #PB_ByteLength) + EndIf + FreeMemory(*Data) + ProcedureReturn #True +EndProcedure diff --git a/Tools/GetLatestMessage/GetLatestMessage.pb b/Tools/GetLatestMessage/GetLatestMessage.pb new file mode 100644 index 0000000..7d2a4c4 --- /dev/null +++ b/Tools/GetLatestMessage/GetLatestMessage.pb @@ -0,0 +1,62 @@ +; ============================================================================ +; BakaShrot GetLatestMessage +; +; Usage: GetLatestMessage [ClientIni] +; Topic, Node Whose latest message to get, each a name or an id. +; ClientIni Identity and server to use, defaults to "client.ini". +; +; Prints the latest message stored for that topic/node, the server refuses +; if the client's ReadTopics don't allow the topic, if either is unknown, or +; if there's no message. +; Compile as a console program, exits with 0 on success, 1 on failure. +; ============================================================================ + +EnableExplicit + +XIncludeFile "../Common/ToolClient.pbi" +XIncludeFile "../../Commons/Networking/Names.pbi" + + +Define Topic.s, Node.s, IniPath.s + +OpenConsole() + +If CountProgramParameters() < 2 + PrintN("Usage: GetLatestMessage [ClientIni]") + PrintN(" Topic and Node are names or ids.") + End 1 +EndIf + +Topic = ProgramParameter(0) +If Not BakaShrot_IsValidRef(Topic) + PrintN("Invalid topic '" + Topic + "', expected a name or an id 0-65535") + End 1 +EndIf + +Node = ProgramParameter(1) +If Not BakaShrot_IsValidRef(Node) + PrintN("Invalid node '" + Node + "', expected a name or an id 0-65535") + End 1 +EndIf + +IniPath = "client.ini" +If CountProgramParameters() > 2 + IniPath = ProgramParameter(2) +EndIf + +If Not ToolClient_Connect(IniPath) + End 1 +EndIf + +If Not BakaShrot_GetLatestMessageOf(Topic, Node) + ToolClient_PrintFailure() + ToolClient_Close() + End 1 +EndIf + +PrintN("Message " + BakaShrot_GetMessageTopicString() + ":" + BakaShrot_GetMessageNodeString() + "#" + Str(BakaShrot_GetMessageId()) + + " (ids " + Str(BakaShrot_GetMessageTopicId()) + ":" + Str(BakaShrot_GetMessageNodeId()) + ")") +PrintN(BakaShrot_GetMessageDataString()) + +ToolClient_Close() +End 0 diff --git a/Tools/GetMessages/GetMessages.pb b/Tools/GetMessages/GetMessages.pb new file mode 100644 index 0000000..8bb353d --- /dev/null +++ b/Tools/GetMessages/GetMessages.pb @@ -0,0 +1,180 @@ +; ============================================================================ +; BakaShrot GetMessages +; +; Usage: GetMessages [options] [ClientIni] +; Topic, Node Whose messages to get, each a name or an id. +; --after Starts after that message id, defaults to 0: from the +; first one. "latest" starts after the latest one, +; only new messages then (with --follow). +; --limit Stops after N messages, defaults to 100, or to no +; limit with --follow. 0 is no limit. +; --follow, -f Keeps going once caught up: checks for new messages +; every --interval ms, until stopped (Ctrl+C) or the +; connection fails. +; --interval How often --follow checks, defaults to 500. +; ClientIni Identity and server to use, defaults to "client.ini". +; +; Prints each message on its own line, in message id order, as its id, a +; tab, and its data as stored (JSON or not, a message with line breaks spans +; several lines). The server refuses if the client's ReadTopics don't allow +; the topic, or if either is unknown. +; Compile as a console program, exits with 0 on success, 1 on failure. +; ============================================================================ + +EnableExplicit + +XIncludeFile "../Common/ToolClient.pbi" +XIncludeFile "../../Commons/Networking/Names.pbi" + + +; Most messages asked for at once, the server's maximum. +#GetMessages_BatchLimit = 10000 + +Define Topic.s, Node.s, IniPath.s = "client.ini", AfterText.s = "0" +Define Limit.q = -1, Follow.i = #False, IntervalMs.i = 500 +Define i.i, Argument.s, Value.s, Positional.i +Define AfterMessageId.q, Printed.q, Asked.l, Count.l, n.l + +OpenConsole() + +; Prints the usage and exits. +Procedure Usage() + PrintN("Usage: GetMessages [--after ] [--limit ] [--follow] [--interval ] [ClientIni]") + PrintN(" Topic and Node are names or ids. Prints each message as its id, a tab, and its data.") + End 1 +EndProcedure + +; Whether Text is a whole number of digits, 0 or more. +Procedure.i IsNumber(Text.s) + Protected i.i + If Text = "" Or Len(Text) > 18 + ProcedureReturn #False + EndIf + For i = 1 To Len(Text) + If Mid(Text, i, 1) < "0" Or Mid(Text, i, 1) > "9" + ProcedureReturn #False + EndIf + Next + ProcedureReturn #True +EndProcedure + +i = 0 +While i < CountProgramParameters() + Argument = ProgramParameter(i) + Select LCase(Argument) + Case "--after", "--limit", "--interval" + If i + 1 >= CountProgramParameters() + PrintN("Missing the value of " + Argument) + End 1 + EndIf + i + 1 + Value = ProgramParameter(i) + Select LCase(Argument) + Case "--after" + If LCase(Value) <> "latest" And Not IsNumber(Value) + PrintN("Invalid --after '" + Value + "', expected a message id or 'latest'") + End 1 + EndIf + AfterText = LCase(Value) + Case "--limit" + If Not IsNumber(Value) + PrintN("Invalid --limit '" + Value + "', expected a number") + End 1 + EndIf + Limit = Val(Value) + Case "--interval" + If Not IsNumber(Value) Or Val(Value) < 10 Or Val(Value) > 3600000 + PrintN("Invalid --interval '" + Value + "', expected 10 to 3600000 ms") + End 1 + EndIf + IntervalMs = Val(Value) + EndSelect + Case "--follow", "-f" + Follow = #True + Default + If Left(Argument, 2) = "--" + PrintN("Unknown option '" + Argument + "'") + Usage() + EndIf + Select Positional + Case 0 : Topic = Argument + Case 1 : Node = Argument + Case 2 : IniPath = Argument + Default + Usage() + EndSelect + Positional + 1 + EndSelect + i + 1 +Wend + +If Positional < 2 + Usage() +EndIf +If Not BakaShrot_IsValidRef(Topic) + PrintN("Invalid topic '" + Topic + "', expected a name or an id 0-65535") + End 1 +EndIf +If Not BakaShrot_IsValidRef(Node) + PrintN("Invalid node '" + Node + "', expected a name or an id 0-65535") + End 1 +EndIf +If Limit < 0 + If Follow + Limit = 0 + Else + Limit = 100 + EndIf +EndIf + +If Not ToolClient_Connect(IniPath) + End 1 +EndIf + +; "latest": after the latest message, or from the start if there's none yet. +If AfterText = "latest" + If BakaShrot_GetLatestMessageOf(Topic, Node) + AfterMessageId = BakaShrot_GetMessageId() + ElseIf Not BakaShrot_IsConnected() + ToolClient_PrintFailure() + ToolClient_Close() + End 1 + EndIf +Else + AfterMessageId = Val(AfterText) +EndIf + +Printed = 0 +Repeat + Asked = #GetMessages_BatchLimit + If Limit > 0 And Limit - Printed < Asked + Asked = Limit - Printed + EndIf + + Count = BakaShrot_GetMessages(Topic, Node, AfterMessageId, Asked) + If Count < 0 + ToolClient_PrintFailure() + ToolClient_Close() + End 1 + EndIf + + For n = 0 To Count - 1 + BakaShrot_SelectMessage(n) + AfterMessageId = BakaShrot_GetMessageId() + PrintN(Str(AfterMessageId) + #TAB$ + BakaShrot_GetMessageDataString()) + Next + Printed + Count + + If Limit > 0 And Printed >= Limit + Break + EndIf + If Not BakaShrot_HasMoreMessages() + If Not Follow + Break + EndIf + Delay(IntervalMs) + EndIf +ForEver + +ToolClient_Close() +End 0 diff --git a/Tools/KeyGen/KeyGen.pb b/Tools/KeyGen/KeyGen.pb new file mode 100644 index 0000000..7ce6253 --- /dev/null +++ b/Tools/KeyGen/KeyGen.pb @@ -0,0 +1,50 @@ +; ============================================================================ +; BakaShrot KeyGen +; +; Generates a new Ed25519 keypair and prints it as two ini-style lines: +; PrivateKey = +; PublicKey = +; +; The private key goes in the node's own [BakaShrot] PrivateKey, the public +; key goes in the configs of whoever needs to trust that node. +; +; Compile as a console program, exits with 0 on success, 1 on failure. +; ============================================================================ + +EnableExplicit + +XIncludeFile "../../Commons/Cryptography/Libsodium.pbi" + + +Define *PublicKey, *PrivateKey + +OpenConsole() + +If Not InitCryptography() + PrintN("Failed to initialize libsodium") + End 1 +EndIf + +*PublicKey = AllocateMemory(#BakaShrot_Ed25519_PublicKeySize) +If Not *PublicKey + PrintN("Failed to allocate the public key") + End 1 +EndIf + +*PrivateKey = AllocateMemory(#BakaShrot_Ed25519_PrivateKeySize) +If Not *PrivateKey + PrintN("Failed to allocate the private key") + End 1 +EndIf + +GenerateKeyPair(*PublicKey, *PrivateKey) + +PrintN("PrivateKey = " + EncodeKeyToString(*PrivateKey, #BakaShrot_Ed25519_PrivateKeySize)) +PrintN("PublicKey = " + EncodeKeyToString(*PublicKey, #BakaShrot_Ed25519_PublicKeySize)) + +; Don't leave the private key lying around in freed memory. +FillMemory(*PrivateKey, #BakaShrot_Ed25519_PrivateKeySize, 0) +FreeMemory(*PrivateKey) +FreeMemory(*PublicKey) + +End 0 diff --git a/Tools/ListNames/ListNames.pb b/Tools/ListNames/ListNames.pb new file mode 100644 index 0000000..68b01ac --- /dev/null +++ b/Tools/ListNames/ListNames.pb @@ -0,0 +1,96 @@ +; ============================================================================ +; BakaShrot ListNames +; +; Usage: ListNames [topics|nodes|all] [ClientIni] [--json] +; topics|nodes|all What to list, defaults to all. +; ClientIni Identity and server to use, defaults to "client.ini". +; --json Prints the DLL's JSON instead of a table. +; +; Lists every topic and node the server has, with this server's id and its +; name: what the names in requests and queries stand for there. Unnamed ones +; aren't replicated. Topics: only those the client may push to or read, +; unless it may query. +; Compile as a console program, exits with 0 on success, 1 on failure. +; ============================================================================ + +EnableExplicit + +XIncludeFile "../Common/ToolClient.pbi" + + +Define What.s = "all", IniPath.s = "client.ini", AsJson.i = #False +Define i.i, Argument.s, Count.l, Json.i, Items.i, Item.i, n.i, Name.s, Failed.i + +OpenConsole() + +For i = 0 To CountProgramParameters() - 1 + Argument = ProgramParameter(i) + Select LCase(Argument) + Case "topics", "nodes", "all" + What = LCase(Argument) + Case "--json" + AsJson = #True + Default + IniPath = Argument + EndSelect +Next + +If Not ToolClient_Connect(IniPath) + End 1 +EndIf + +; Prints one list, from the DLL's JSON. +Procedure.i PrintList(Label.s, AsJson.i) + Protected Json.i, Items.i, Item.i, n.i, Name.s, Text.s + + Text = BakaShrot_GetNamesListString() + If AsJson + PrintN(Text) + ProcedureReturn #True + EndIf + + Json = ParseJSON(#PB_Any, Text) + If Not Json + PrintN("The server's list couldn't be read") + ProcedureReturn #False + EndIf + Items = GetJSONMember(JSONValue(Json), "items") + PrintN(Label + " (" + Str(JSONArraySize(Items)) + "):") + For n = 0 To JSONArraySize(Items) - 1 + Item = GetJSONElement(Items, n) + Name = GetJSONString(GetJSONMember(Item, "name")) + If Name = "" + Name = "(unnamed, not replicated)" + EndIf + PrintN(" " + RSet(Str(GetJSONInteger(GetJSONMember(Item, "id"))), 5) + " " + LSet(Name, 30) + " " + GetJSONString(GetJSONMember(Item, "origin"))) + Next + If GetJSONBoolean(GetJSONMember(JSONValue(Json), "truncated")) + PrintN(" ... more than fit in one answer") + EndIf + FreeJSON(Json) + ProcedureReturn #True +EndProcedure + +Failed = #False +If What = "topics" Or What = "all" + If BakaShrot_ListTopics() < 0 + ToolClient_PrintFailure() + Failed = #True + ElseIf Not PrintList("Topics", AsJson) + Failed = #True + EndIf +EndIf +If Not Failed And (What = "nodes" Or What = "all") + If BakaShrot_ListNodes() < 0 + ToolClient_PrintFailure() + Failed = #True + ElseIf Not PrintList("Nodes", AsJson) + Failed = #True + EndIf +EndIf + +ToolClient_Close() +If Failed + End 1 +EndIf +End 0 diff --git a/Tools/PushMessage/PushMessage.pb b/Tools/PushMessage/PushMessage.pb new file mode 100644 index 0000000..2b8136f --- /dev/null +++ b/Tools/PushMessage/PushMessage.pb @@ -0,0 +1,80 @@ +; ============================================================================ +; BakaShrot PushMessage +; +; Usage: PushMessage [-t ] [ClientIni] +; -t Topic The topic to push to, a name or an id. Defaults to the +; client's own topic (its TopicId). The client's PushTopics on +; the server must allow it. +; Json The message to push, or @ followed by a file holding it. +; Usually JSON, but anything goes: the server flags it in is_json. +; PureBasic's ProgramParameter() drops double quotes and +; doesn't understand \" escapes, so JSON with strings only +; gets through intact from a file: use @JsonFile. +; ClientIni Identity and server to use, defaults to "client.ini". +; +; Pushes one message under the client's node, and prints the message id the +; server stored it under. +; Compile as a console program, exits with 0 on success, 1 on failure. +; ============================================================================ + +EnableExplicit + +XIncludeFile "../Common/ToolClient.pbi" +XIncludeFile "../../Commons/Networking/Names.pbi" + + +Define JsonData.s, IniPath.s, Topic.s, FileText.String, MessageId.q, i.i, Argument.s +Define NewList Arguments.s() + +OpenConsole() + +For i = 0 To CountProgramParameters() - 1 + Argument = ProgramParameter(i) + If (Argument = "-t" Or Argument = "--topic") And i < CountProgramParameters() - 1 + i + 1 + Topic = ProgramParameter(i) + If Not BakaShrot_IsValidRef(Topic) + PrintN("Invalid topic '" + Topic + "', expected a name or an id 0-65535") + End 1 + EndIf + Else + AddElement(Arguments()) + Arguments() = Argument + EndIf +Next + +If ListSize(Arguments()) < 1 + PrintN("Usage: PushMessage [-t ] [ClientIni]") + PrintN(" Command-line arguments lose their double quotes, so use @JsonFile for JSON with strings.") + End 1 +EndIf + +FirstElement(Arguments()) +JsonData = Arguments() +If Left(JsonData, 1) = "@" + If Not ToolClient_ReadTextFile(Mid(JsonData, 2), @FileText) + End 1 + EndIf + JsonData = FileText\s +EndIf + +IniPath = "client.ini" +If NextElement(Arguments()) + IniPath = Arguments() +EndIf + +If Not ToolClient_Connect(IniPath) + End 1 +EndIf + +MessageId = BakaShrot_PushMessageTo(Topic, JsonData) +If MessageId < 1 + ToolClient_PrintFailure() + ToolClient_Close() + End 1 +EndIf + +PrintN("Pushed as message #" + Str(MessageId)) + +ToolClient_Close() +End 0 diff --git a/Tools/Query/Query.pb b/Tools/Query/Query.pb new file mode 100644 index 0000000..99a97a4 --- /dev/null +++ b/Tools/Query/Query.pb @@ -0,0 +1,58 @@ +; ============================================================================ +; BakaShrot Query +; +; Usage: Query [ClientIni] +; Sql A single read-only SELECT (or WITH ... SELECT), or @ followed +; by a file holding it. Command-line arguments lose their +; double quotes, use single quotes or @SqlFile. +; ClientIni Identity and server to use, defaults to "client.ini". +; +; Runs a raw SQL query on the server and prints its result as JSON: +; {"columns": ["name", ...], "rows": [["value", ...], ...]} +; The client must be allowed to query: AllowQuery = 1 in its server-side +; [BakaShrot.Client.]. +; Compile as a console program, exits with 0 on success, 1 on failure. +; ============================================================================ + +EnableExplicit + +XIncludeFile "../Common/ToolClient.pbi" + + +Define Sql.s, IniPath.s, FileText.String + +OpenConsole() + +If CountProgramParameters() < 1 + PrintN("Usage: Query [ClientIni]") + PrintN(" Command-line arguments lose their double quotes, use single quotes or @SqlFile.") + End 1 +EndIf + +Sql = ProgramParameter(0) +If Left(Sql, 1) = "@" + If Not ToolClient_ReadTextFile(Mid(Sql, 2), @FileText) + End 1 + EndIf + Sql = FileText\s +EndIf + +IniPath = "client.ini" +If CountProgramParameters() > 1 + IniPath = ProgramParameter(1) +EndIf + +If Not ToolClient_Connect(IniPath) + End 1 +EndIf + +If Not BakaShrot_Query(Sql) + ToolClient_PrintFailure() + ToolClient_Close() + End 1 +EndIf + +PrintN(BakaShrot_GetQueryResultString()) + +ToolClient_Close() +End 0 diff --git a/Tools/Resolve/Resolve.pb b/Tools/Resolve/Resolve.pb new file mode 100644 index 0000000..acc6103 --- /dev/null +++ b/Tools/Resolve/Resolve.pb @@ -0,0 +1,69 @@ +; ============================================================================ +; BakaShrot Resolve +; +; Usage: Resolve [ClientIni] +; topic|node What to look up. +; NameOrId A name, to get its id on the server, or an id, to get its name. +; ClientIni Identity and server to use, defaults to "client.ini". +; +; Prints the server's id and name for it, as "topic logs = 1". Each server +; can have different ids for the same names. The server only resolves the +; topics the client may push to or read, unless it may query. +; Compile as a console program, exits with 0 on success, 1 on failure. +; ============================================================================ + +EnableExplicit + +XIncludeFile "../Common/ToolClient.pbi" +XIncludeFile "../../Commons/Networking/Names.pbi" + + +Define Kind.s, Ref.s, IniPath.s, Id.l, Name.s + +OpenConsole() + +If CountProgramParameters() < 2 + PrintN("Usage: Resolve [ClientIni]") + End 1 +EndIf + +Kind = LCase(ProgramParameter(0)) +If Kind <> "topic" And Kind <> "node" + PrintN("Expected 'topic' or 'node', not '" + ProgramParameter(0) + "'") + End 1 +EndIf + +Ref = ProgramParameter(1) +If Not BakaShrot_IsValidRef(Ref) + PrintN("Invalid " + Kind + " '" + Ref + "', expected a name or an id 0-65535") + End 1 +EndIf + +IniPath = "client.ini" +If CountProgramParameters() > 2 + IniPath = ProgramParameter(2) +EndIf + +If Not ToolClient_Connect(IniPath) + End 1 +EndIf + +If Kind = "topic" + Id = BakaShrot_ResolveTopic(Ref) +Else + Id = BakaShrot_ResolveNode(Ref) +EndIf +If Id < 0 + ToolClient_PrintFailure() + ToolClient_Close() + End 1 +EndIf + +Name = BakaShrot_GetResolvedNameString() +If Name = "" + Name = "(unnamed)" +EndIf +PrintN(Kind + " " + Name + " = " + Str(Id)) + +ToolClient_Close() +End 0