mirror of
https://github.com/aziascreations/BakaShrot.git
synced 2026-11-23 20:58:46 +01:00
Got close to the final version
comitting Claude's code before the last mile improvements
This commit is contained in:
+11
@@ -5,8 +5,19 @@
|
|||||||
# Build Artifacts
|
# Build Artifacts
|
||||||
*.exe
|
*.exe
|
||||||
*.dll
|
*.dll
|
||||||
|
# ... except the runtime redistributables the release packages, see Libs/redist/README.md
|
||||||
|
!Libs/redist/**/*.dll
|
||||||
*.so
|
*.so
|
||||||
*.a
|
*.a
|
||||||
*.pdb
|
*.pdb
|
||||||
*.lib
|
*.lib
|
||||||
*.exp
|
*.exp
|
||||||
|
|
||||||
|
# Build output, holds generated private keys
|
||||||
|
Build/
|
||||||
|
|
||||||
|
# Release builds, see Release.ps1
|
||||||
|
Release/
|
||||||
|
|
||||||
|
# Python
|
||||||
|
__pycache__/
|
||||||
|
|||||||
@@ -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 <path>]
|
||||||
|
#
|
||||||
|
# Keys are regenerated on every run, ./Build is git-ignored since it holds
|
||||||
|
# private keys.
|
||||||
|
# ============================================================================
|
||||||
|
|
||||||
|
param(
|
||||||
|
[string]$Compiler = "C:\Program Files\PureBasic_573\Compilers\pbcompiler.exe"
|
||||||
|
)
|
||||||
|
|
||||||
|
$ErrorActionPreference = "Stop"
|
||||||
|
|
||||||
|
$Root = $PSScriptRoot
|
||||||
|
$Output = Join-Path $Root "Build"
|
||||||
|
|
||||||
|
# Where Commons/Cryptography/Libsodium.pbi imports it from, x64 since the
|
||||||
|
# compiler above is the x64 one.
|
||||||
|
$SodiumDir = Join-Path $Root "Libs\libsodium\x64"
|
||||||
|
|
||||||
|
# Where sqlite3.dll is extracted to, the server loads it instead of the
|
||||||
|
# SQLite bundled with PureBasic 5.73, which lacks the JSON functions.
|
||||||
|
$SqliteDir = Join-Path $Root "Libs\sqlite\x64"
|
||||||
|
|
||||||
|
$ServerHost = "127.0.0.1"
|
||||||
|
$ServerPort = 12345
|
||||||
|
$Server2Port = 12346
|
||||||
|
$PeerRetryDelay = 10
|
||||||
|
$PeerBatchSize = 100
|
||||||
|
|
||||||
|
# The same names on both servers, different ids, see the top of this file.
|
||||||
|
# Same client, through server2 as its own node (local2), so no topic/node is
|
||||||
|
# ever written to on both servers.
|
||||||
|
$Topics = @{ logs = 1; sensors = 2 }
|
||||||
|
$Nodes = @{ server1 = 1; local = 2; server2 = 3; local2 = 4 }
|
||||||
|
$Topics2 = @{ logs = 200; sensors = 201 }
|
||||||
|
$Nodes2 = @{ server1 = 11; local = 12; server2 = 13; local2 = 14 }
|
||||||
|
|
||||||
|
function Format-Names($Names) {
|
||||||
|
($Names.GetEnumerator() | Sort-Object Value | ForEach-Object { "$($_.Key) = $($_.Value)" }) -join "`r`n"
|
||||||
|
}
|
||||||
|
|
||||||
|
function Expand-Libsodium {
|
||||||
|
$Zip = Get-ChildItem (Join-Path $Root "Libs") -Filter "libsodium-*-msvc.zip" | Select-Object -First 1
|
||||||
|
if (-not $Zip) {
|
||||||
|
throw "Missing Libs\libsodium-*-msvc.zip, get it from https://download.libsodium.org/libsodium/releases/"
|
||||||
|
}
|
||||||
|
|
||||||
|
Write-Host "Extracting libsodium from $($Zip.Name)"
|
||||||
|
Add-Type -AssemblyName System.IO.Compression.FileSystem
|
||||||
|
$Archive = [IO.Compression.ZipFile]::OpenRead($Zip.FullName)
|
||||||
|
try {
|
||||||
|
# Zip folder -> Libs\libsodium folder
|
||||||
|
$Targets = @{ "x64" = "x64"; "Win32" = "x86" }
|
||||||
|
foreach ($Arch in $Targets.Keys) {
|
||||||
|
$Destination = Join-Path $Root "Libs\libsodium\$($Targets[$Arch])"
|
||||||
|
New-Item -ItemType Directory -Force $Destination | Out-Null
|
||||||
|
foreach ($Name in @("libsodium.dll", "libsodium.lib")) {
|
||||||
|
$Entry = $Archive.GetEntry("libsodium/$Arch/Release/v143/dynamic/$Name")
|
||||||
|
if (-not $Entry) {
|
||||||
|
throw "$($Zip.Name) has no $Arch dynamic $Name"
|
||||||
|
}
|
||||||
|
[IO.Compression.ZipFileExtensions]::ExtractToFile($Entry, (Join-Path $Destination $Name), $true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally {
|
||||||
|
$Archive.Dispose()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Expand-Sqlite {
|
||||||
|
Add-Type -AssemblyName System.IO.Compression.FileSystem
|
||||||
|
|
||||||
|
foreach ($Arch in @("x64", "x86")) {
|
||||||
|
# The version in the name is zero-padded, so the last one by name is the latest.
|
||||||
|
$Zip = Get-ChildItem (Join-Path $Root "Libs") -Filter "sqlite-dll-win-$Arch-*.zip" | Sort-Object Name | Select-Object -Last 1
|
||||||
|
if (-not $Zip) {
|
||||||
|
throw "Missing Libs\sqlite-dll-win-$Arch-*.zip, get it from https://www.sqlite.org/download.html"
|
||||||
|
}
|
||||||
|
|
||||||
|
Write-Host "Extracting SQLite from $($Zip.Name)"
|
||||||
|
$Destination = Join-Path $Root "Libs\sqlite\$Arch"
|
||||||
|
New-Item -ItemType Directory -Force $Destination | Out-Null
|
||||||
|
|
||||||
|
$Archive = [IO.Compression.ZipFile]::OpenRead($Zip.FullName)
|
||||||
|
try {
|
||||||
|
$Entry = $Archive.GetEntry("sqlite3.dll")
|
||||||
|
if (-not $Entry) {
|
||||||
|
throw "$($Zip.Name) has no sqlite3.dll"
|
||||||
|
}
|
||||||
|
[IO.Compression.ZipFileExtensions]::ExtractToFile($Entry, (Join-Path $Destination "sqlite3.dll"), $true)
|
||||||
|
}
|
||||||
|
finally {
|
||||||
|
$Archive.Dispose()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Invoke-Compiler($Source, $Executable, $Flags) {
|
||||||
|
Write-Host "Compiling $Source"
|
||||||
|
& $Compiler (Join-Path $Root $Source) @Flags /QUIET /EXE (Join-Path $Output $Executable)
|
||||||
|
if ($LASTEXITCODE -ne 0) {
|
||||||
|
throw "Failed to compile $Source"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function New-KeyPair {
|
||||||
|
# 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 <Topic>] <Json|@JsonFile> [ClientIni]
|
||||||
|
# GetLatestMessage <Topic> <Node> [ClientIni]
|
||||||
|
Invoke-Compiler "Tools\PushMessage\PushMessage.pb" "PushMessage.exe" @("/CONSOLE")
|
||||||
|
Invoke-Compiler "Tools\GetLatestMessage\GetLatestMessage.pb" "GetLatestMessage.exe" @("/CONSOLE")
|
||||||
|
# GetMessages <Topic> <Node> [--after <Id|latest>] [--limit <N>] [--follow] [ClientIni]
|
||||||
|
Invoke-Compiler "Tools\GetMessages\GetMessages.pb" "GetMessages.exe" @("/CONSOLE")
|
||||||
|
# Query <Sql|@SqlFile> [ClientIni]
|
||||||
|
Invoke-Compiler "Tools\Query\Query.pb" "Query.exe" @("/CONSOLE")
|
||||||
|
# Resolve <topic|node> <NameOrId> [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
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,7 @@
|
|||||||
|
IDE Options = PureBasic 6.41 beta 2 (Windows - x64)
|
||||||
|
CursorPosition = 4
|
||||||
|
EnableXP
|
||||||
|
DPIAware
|
||||||
|
CompileSourceDirectory
|
||||||
|
EnableCompileCount = 0
|
||||||
|
EnableBuildCount = 0
|
||||||
@@ -0,0 +1,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
|
||||||
@@ -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.
|
||||||
@@ -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
|
||||||
@@ -1,17 +1,18 @@
|
|||||||
; ============================================================================
|
; ============================================================================
|
||||||
; BakaShrot Cryptography
|
; BakaShrot Cryptography
|
||||||
;
|
;
|
||||||
; Authenticates packets using Ed25519 signatures (via libsodium - this does
|
; Ed25519 signatures via libsodium (this does NOT reimplement any
|
||||||
; NOT reimplement any cryptographic primitive).
|
; cryptographic primitive).
|
||||||
;
|
;
|
||||||
; EncodeData signs a buffer with the sending node's own private key.
|
; EncodeData signs a buffer with the sending node's own private key.
|
||||||
; DecodeData checks that signature against the claimed sender's public 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 signatures prove each end's identity in the handshake. The sealed
|
||||||
; the packet can still read it, but they cannot forge one or tamper with one
|
; boxes, key exchange and XChaCha20-Poly1305 below encrypt the connections:
|
||||||
; without the signature check failing. That matches BakaShrot's
|
; Session.pbi and Cipher.pbi use them, nothing else should.
|
||||||
; replication/broadcast model, where a message is meant to be read by every
|
; What's done, what isn't, and the plan to abstract it:
|
||||||
; peer in the group - encrypting it for a single recipient would defeat that.
|
; Design/Cryptography.md.
|
||||||
;
|
;
|
||||||
; Key material:
|
; Key material:
|
||||||
; - Public key: #BakaShrot_Ed25519_PublicKeySize (32) raw bytes.
|
; - Public key: #BakaShrot_Ed25519_PublicKeySize (32) raw bytes.
|
||||||
@@ -24,8 +25,9 @@
|
|||||||
; file - see EncodeKeyToString()/DecodeKeyFromString() below.
|
; file - see EncodeKeyToString()/DecodeKeyFromString() below.
|
||||||
;
|
;
|
||||||
; Setup required to build/run this:
|
; Setup required to build/run this:
|
||||||
; - Windows: the official libsodium release's "libsodium.lib" (import
|
; - Windows: the official libsodium MSVC release's dynamic build, extracted
|
||||||
; library) and "libsodium.dll" alongside the executable.
|
; to Libs/libsodium/<x64|x86>/ by Build.ps1, and "libsodium.dll"
|
||||||
|
; alongside the executable.
|
||||||
; - Linux: libsodium-dev (Debian/Ubuntu) or libsodium-devel (Fedora)
|
; - Linux: libsodium-dev (Debian/Ubuntu) or libsodium-devel (Fedora)
|
||||||
; installed, so "-lsodium" resolves at link time and
|
; installed, so "-lsodium" resolves at link time and
|
||||||
; libsodium.so.* is available at runtime.
|
; libsodium.so.* is available at runtime.
|
||||||
@@ -38,9 +40,27 @@
|
|||||||
#BakaShrot_Ed25519_PrivateKeySize = 64
|
#BakaShrot_Ed25519_PrivateKeySize = 64
|
||||||
#BakaShrot_Ed25519_SignatureSize = 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
|
; X25519 (crypto_box_seal, crypto_kx_*): sealed Hellos and the key exchange,
|
||||||
ImportC "libsodium.lib"
|
; 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
|
CompilerElse
|
||||||
ImportC "-lsodium"
|
ImportC "-lsodium"
|
||||||
CompilerEndIf
|
CompilerEndIf
|
||||||
@@ -63,6 +83,58 @@ CompilerEndIf
|
|||||||
; non-zero otherwise (forged, corrupted, or signed different data).
|
; non-zero otherwise (forged, corrupted, or signed different data).
|
||||||
crypto_sign_verify_detached.l(*Signature, *Message, MessageLength.q, *PublicKey)
|
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
|
EndImport
|
||||||
|
|
||||||
|
|
||||||
@@ -82,6 +154,14 @@ Procedure GenerateKeyPair(*PublicKey, *PrivateKey)
|
|||||||
EndProcedure
|
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
|
; Signs *Data (DataLength bytes) with *PrivateKey (this node's own private
|
||||||
; key, #BakaShrot_Ed25519_PrivateKeySize bytes).
|
; key, #BakaShrot_Ed25519_PrivateKeySize bytes).
|
||||||
; Writes the signature to *Signature, which must point to
|
; Writes the signature to *Signature, which must point to
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -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
|
Enumeration BakaShrot_ConnectionStatuses
|
||||||
|
; Connected, the Hello hasn't been sent/received yet.
|
||||||
#BakaShrot_ConnectionStatus_New
|
#BakaShrot_ConnectionStatus_New
|
||||||
|
; The challenge was issued, its response hasn't been sent/received yet.
|
||||||
|
#BakaShrot_ConnectionStatus_Challenged
|
||||||
#BakaShrot_ConnectionStatus_Authenticated
|
#BakaShrot_ConnectionStatus_Authenticated
|
||||||
#BakaShrot_ConnectionStatus_Idk
|
|
||||||
#BakaShrot_ConnectionStatus_Disconnected
|
#BakaShrot_ConnectionStatus_Disconnected
|
||||||
#BakaShrot_ConnectionStatus_Aborted
|
#BakaShrot_ConnectionStatus_Aborted
|
||||||
EndEnumeration
|
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
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -1,4 +1,7 @@
|
|||||||
|
|
||||||
|
XIncludeFile "../../Includes/PB-MessagePack/Includes/MessagePack.pbi"
|
||||||
|
XIncludeFile "Names.pbi"
|
||||||
|
|
||||||
|
|
||||||
; Represents the root of all BakaShrot packets.
|
; Represents the root of all BakaShrot packets.
|
||||||
; Any packets below this size MUST be thrown out.
|
; Any packets below this size MUST be thrown out.
|
||||||
@@ -8,19 +11,146 @@ Structure BakaShrot_PacketBase
|
|||||||
PacketType.l
|
PacketType.l
|
||||||
EndStructure
|
EndStructure
|
||||||
|
|
||||||
|
|
||||||
; Fixed values every BakaShrot_PacketBase must carry. Checked on decode so a
|
; Fixed values every BakaShrot_PacketBase must carry. Checked on decode so a
|
||||||
; packet from a different protocol/version is thrown out instead of being
|
; packet from a different protocol/version is thrown out instead of being
|
||||||
; misparsed.
|
; misparsed.
|
||||||
#BakaShrot_ProtocolMagic = $42534854 ; "BSHT"
|
#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
|
Enumeration BakaShrot_PacketTypes
|
||||||
; Safety fallback value, should be dropped when encountered
|
; Safety fallback value, should be dropped when encountered
|
||||||
#BakaShrot_PacketType_None = 0
|
#BakaShrot_PacketType_None = 0
|
||||||
|
|
||||||
#BakaShrot_PacketType_AuthenticationRequest = 1
|
; 1-3 were used by the removed AuthenticationPacket.pbi, don't reuse them.
|
||||||
#BakaShrot_PacketType_AuthenticationChallenge = 2
|
#BakaShrot_PacketType_ClientHello = 4
|
||||||
#BakaShrot_PacketType_AuthenticationResult = 3
|
#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
|
EndEnumeration
|
||||||
|
|
||||||
|
|
||||||
|
; Checks and reads the given MsgPack data into a packet structure's common fields.
|
||||||
|
; The caller can handle the MsgPack data validation however it see fit.
|
||||||
|
; On success, the structure's fields will be populated, and the MsgPack structure will be ready to ready the packet's remaining fields.
|
||||||
|
; On failure, all data should be discarded and be treated as tainted.
|
||||||
|
Procedure.b BakaShrot_ReadPacketBase(*PacketStruct.BakaShrot_PacketBase, *MsgPackData.MsgPackData)
|
||||||
|
; Returns true on success, false otherwise
|
||||||
|
; The caller will usually drop all data and tell the remote client to fuck off if this fails.
|
||||||
|
Protected TempValue.q
|
||||||
|
|
||||||
|
If Not *PacketStruct Or Not *MsgPackData
|
||||||
|
ProcedureReturn #False
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; Magic
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
|
||||||
|
ProcedureReturn #False
|
||||||
|
EndIf
|
||||||
|
TempValue = MsgPackReadInteger(*MsgPackData)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or TempValue <> #BakaShrot_ProtocolMagic
|
||||||
|
ProcedureReturn #False
|
||||||
|
EndIf
|
||||||
|
*PacketStruct\Magic = TempValue
|
||||||
|
|
||||||
|
; Version
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
|
||||||
|
ProcedureReturn #False
|
||||||
|
EndIf
|
||||||
|
TempValue = MsgPackReadInteger(*MsgPackData)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or TempValue <> #BakaShrot_ProtocolVersion
|
||||||
|
ProcedureReturn #False
|
||||||
|
EndIf
|
||||||
|
*PacketStruct\Version = TempValue
|
||||||
|
|
||||||
|
; PacketType
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
|
||||||
|
ProcedureReturn #False
|
||||||
|
EndIf
|
||||||
|
TempValue = MsgPackReadInteger(*MsgPackData)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or TempValue <= #BakaShrot_PacketType_None Or TempValue > 2147483647
|
||||||
|
ProcedureReturn #False
|
||||||
|
EndIf
|
||||||
|
*PacketStruct\PacketType = TempValue
|
||||||
|
|
||||||
|
ProcedureReturn #True
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
; Writes a packet structure's common fields into the given MsgPack data.
|
||||||
|
; On success, the MsgPack structure will be ready to write the packet's remaining fields.
|
||||||
|
; On failure, the MsgPack data should be discarded and be treated as tainted.
|
||||||
|
Procedure.b BakaShrot_WritePacketBase(*PacketStruct.BakaShrot_PacketBase, *MsgPackData.MsgPackData)
|
||||||
|
; Returns true on success, false otherwise
|
||||||
|
If MsgPackWriteInteger(*MsgPackData, *PacketStruct\Magic) <> #MsgPack_Error_Success
|
||||||
|
ProcedureReturn #False
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If MsgPackWriteInteger(*MsgPackData, *PacketStruct\Version) <> #MsgPack_Error_Success
|
||||||
|
ProcedureReturn #False
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If MsgPackWriteInteger(*MsgPackData, *PacketStruct\PacketType) <> #MsgPack_Error_Success
|
||||||
|
ProcedureReturn #False
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
ProcedureReturn #True
|
||||||
|
EndProcedure
|
||||||
|
|||||||
@@ -0,0 +1,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
|
||||||
@@ -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
|
|
||||||
|
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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.<name>] ReadTopics must allow the topic.
|
||||||
|
; Answered with a LatestMessage or a RequestRefused.
|
||||||
|
Structure BakaShrot_GetLatestMessage Extends BakaShrot_PacketBase
|
||||||
|
Topic.s
|
||||||
|
Node.s
|
||||||
|
EndStructure
|
||||||
|
|
||||||
|
|
||||||
|
; Encodes *Request into a freshly allocated buffer, its base fields are set by this procedure.
|
||||||
|
; *OutSize receives its size in bytes.
|
||||||
|
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
|
||||||
|
Procedure.i BakaShrot_GetLatestMessagePacket_Encode(*Request.BakaShrot_GetLatestMessage, *OutSize.Integer)
|
||||||
|
Protected *MsgPackData.MsgPackData, *Buffer
|
||||||
|
|
||||||
|
*Request\Magic = #BakaShrot_ProtocolMagic
|
||||||
|
*Request\Version = #BakaShrot_ProtocolVersion
|
||||||
|
*Request\PacketType = #BakaShrot_PacketType_GetLatestMessage
|
||||||
|
|
||||||
|
*MsgPackData = MsgPackCreate(64)
|
||||||
|
If Not *MsgPackData
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If Not BakaShrot_WritePacketBase(*Request, *MsgPackData)
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If MsgPackWriteString(*MsgPackData, *Request\Topic) <> #MsgPack_Error_Success
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If MsgPackWriteString(*MsgPackData, *Request\Node) <> #MsgPack_Error_Success
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; Frees *MsgPackData on success, leaves it untouched on failure.
|
||||||
|
*Buffer = MsgPackFinalize(*MsgPackData)
|
||||||
|
If Not *Buffer
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
*OutSize\i = MemorySize(*Buffer)
|
||||||
|
ProcedureReturn *Buffer
|
||||||
|
|
||||||
|
EncodeFailed:
|
||||||
|
MsgPackFree(*MsgPackData, #True)
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
|
||||||
|
; *MsgPackData stays owned by the caller, and should be discarded on failure.
|
||||||
|
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
|
||||||
|
Procedure.i BakaShrot_GetLatestMessagePacket_Decode(*MsgPackData.MsgPackData)
|
||||||
|
Protected *Request.BakaShrot_GetLatestMessage
|
||||||
|
|
||||||
|
*Request = AllocateStructure(BakaShrot_GetLatestMessage)
|
||||||
|
If Not *Request
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; The base parser doesn't check which packet it is, that's on us.
|
||||||
|
If Not BakaShrot_ReadPacketBase(*Request, *MsgPackData) Or *Request\PacketType <> #BakaShrot_PacketType_GetLatestMessage
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; Topic
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
*Request\Topic = MsgPackReadString(*MsgPackData)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; Node
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
*Request\Node = MsgPackReadString(*MsgPackData)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
ProcedureReturn *Request
|
||||||
|
|
||||||
|
; Everything read so far is tainted, drop it.
|
||||||
|
DecodeFailed:
|
||||||
|
FreeStructure(*Request)
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndProcedure
|
||||||
@@ -0,0 +1,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.<name>] ReadTopics must allow the topic.
|
||||||
|
; Answered with a Messages (maybe with none) or a RequestRefused.
|
||||||
|
Structure BakaShrot_GetMessages Extends BakaShrot_PacketBase
|
||||||
|
Topic.s
|
||||||
|
Node.s
|
||||||
|
AfterMessageId.q
|
||||||
|
Limit.l
|
||||||
|
EndStructure
|
||||||
|
|
||||||
|
|
||||||
|
; Encodes *Request into a freshly allocated buffer, its base fields are set by this procedure.
|
||||||
|
; *OutSize receives its size in bytes.
|
||||||
|
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
|
||||||
|
Procedure.i BakaShrot_GetMessagesPacket_Encode(*Request.BakaShrot_GetMessages, *OutSize.Integer)
|
||||||
|
Protected *MsgPackData.MsgPackData, *Buffer
|
||||||
|
|
||||||
|
*Request\Magic = #BakaShrot_ProtocolMagic
|
||||||
|
*Request\Version = #BakaShrot_ProtocolVersion
|
||||||
|
*Request\PacketType = #BakaShrot_PacketType_GetMessages
|
||||||
|
|
||||||
|
If *Request\AfterMessageId < 0 Or *Request\Limit < 1 Or *Request\Limit > #BakaShrot_MaxGetMessages
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
*MsgPackData = MsgPackCreate(64)
|
||||||
|
If Not *MsgPackData
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If Not BakaShrot_WritePacketBase(*Request, *MsgPackData)
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If MsgPackWriteString(*MsgPackData, *Request\Topic) <> #MsgPack_Error_Success
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If MsgPackWriteString(*MsgPackData, *Request\Node) <> #MsgPack_Error_Success
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If MsgPackWriteInteger(*MsgPackData, *Request\AfterMessageId) <> #MsgPack_Error_Success
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
If MsgPackWriteInteger(*MsgPackData, *Request\Limit) <> #MsgPack_Error_Success
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; Frees *MsgPackData on success, leaves it untouched on failure.
|
||||||
|
*Buffer = MsgPackFinalize(*MsgPackData)
|
||||||
|
If Not *Buffer
|
||||||
|
Goto EncodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
*OutSize\i = MemorySize(*Buffer)
|
||||||
|
ProcedureReturn *Buffer
|
||||||
|
|
||||||
|
EncodeFailed:
|
||||||
|
MsgPackFree(*MsgPackData, #True)
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
|
||||||
|
; *MsgPackData stays owned by the caller, and should be discarded on failure.
|
||||||
|
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
|
||||||
|
Procedure.i BakaShrot_GetMessagesPacket_Decode(*MsgPackData.MsgPackData)
|
||||||
|
Protected *Request.BakaShrot_GetMessages
|
||||||
|
Protected Value.q
|
||||||
|
|
||||||
|
*Request = AllocateStructure(BakaShrot_GetMessages)
|
||||||
|
If Not *Request
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; The base parser doesn't check which packet it is, that's on us.
|
||||||
|
If Not BakaShrot_ReadPacketBase(*Request, *MsgPackData) Or *Request\PacketType <> #BakaShrot_PacketType_GetMessages
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; Topic
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
*Request\Topic = MsgPackReadString(*MsgPackData)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; Node
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
*Request\Node = MsgPackReadString(*MsgPackData)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; AfterMessageId
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
*Request\AfterMessageId = MsgPackReadInteger(*MsgPackData)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Request\AfterMessageId < 0
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; Limit
|
||||||
|
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
Value = MsgPackReadInteger(*MsgPackData)
|
||||||
|
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 1 Or Value > #BakaShrot_MaxGetMessages
|
||||||
|
Goto DecodeFailed
|
||||||
|
EndIf
|
||||||
|
*Request\Limit = Value
|
||||||
|
|
||||||
|
ProcedureReturn *Request
|
||||||
|
|
||||||
|
; Everything read so far is tainted, drop it.
|
||||||
|
DecodeFailed:
|
||||||
|
FreeStructure(*Request)
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndProcedure
|
||||||
@@ -0,0 +1,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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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.<name>] 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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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.<name>] -> one BakaShrot_CoreConfig\Peers() entry per
|
|
||||||
; section; <name> is only a key for this file,
|
|
||||||
; it is never sent on the wire.
|
|
||||||
; ============================================================================
|
|
||||||
|
|
||||||
|
|
||||||
; Ini Section: [BakaShrot.Peer.<name>] (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.<name>] 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.<name>] 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.<name>] 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
|
|
||||||
@@ -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.<name>] section per peer this node talks to.
|
|
||||||
; <name> is only a key for this file; it is never sent on the wire.
|
|
||||||
[BakaShrot.Peer.example]
|
|
||||||
; Remote address of the peer. Can be a domain name, IPV4 or IPV6.
|
|
||||||
Host =
|
|
||||||
|
|
||||||
; Remote port of the peer (0-65535).
|
|
||||||
Port =
|
|
||||||
|
|
||||||
; 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 =
|
|
||||||
@@ -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
|
|
||||||
@@ -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.<name>] PublicKeys` and
|
||||||
|
`[BakaShrot.Peer.<name>] PublicKey`. The peer's is also the server it
|
||||||
|
expects at the other end of its link, so it's required.
|
||||||
|
- A client's: whatever the app passes to `BakaShrot_SetPrivateKey()`,
|
||||||
|
`BakaShrot_SetPublicKey()` and `BakaShrot_SetServerPublicKey()` (the
|
||||||
|
server's). The tools and `bakashrot.py` read them from `client.ini`:
|
||||||
|
`PrivateKey`, `PublicKey`, `ServerPublicKey`.
|
||||||
|
- **Connection keys: X25519**, made for each connection by both ends, the
|
||||||
|
secrets wiped once the cipher has its keys. So a recorded connection
|
||||||
|
can't be decrypted later, even with both identity keys (forward secrecy).
|
||||||
|
- **Generated** by `Tools/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.<name>]` 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.
|
||||||
@@ -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.<name>] 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.<name>]`, 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.<name>]`,
|
||||||
|
authenticates as itself (the peer must list it as a client), and retries
|
||||||
|
every `PeerRetryDelay` seconds when that fails or the link drops. On its own
|
||||||
|
link, every `PeerSyncInterval` seconds, starting right away:
|
||||||
|
|
||||||
|
```
|
||||||
|
P -> S SyncStateRequest
|
||||||
|
S -> P SyncState every name S takes from P (its AcceptTopics and
|
||||||
|
AcceptNodes for P), their wildcards, and
|
||||||
|
MAX(message_id) for each topic/node of those, in
|
||||||
|
S's ids
|
||||||
|
P: compares with its own state (GetSyncState()), matching by name,
|
||||||
|
drops what's unnamed on its side, or neither listed by S nor
|
||||||
|
matching one of S's wildcards (BakaShrot_Names_NoteDropped(), a
|
||||||
|
no-op for now), and for every pair in its SendTopics and
|
||||||
|
SendNodes for S that S is behind on (0 for a name S doesn't have
|
||||||
|
yet):
|
||||||
|
P -> S ReplicateMessages the topic and node names, the next missing messages
|
||||||
|
of that pair, in id order, with their original
|
||||||
|
message ids: 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_<Name>Packet_Encode(*Struct, *OutSize.Integer)` sets
|
||||||
|
the base fields itself, and returns a new buffer (the caller frees it with
|
||||||
|
`FreeMemory`) or 0.
|
||||||
|
- **Decode:** `BakaShrot_<Name>Packet_Decode(*MsgPackData)` returns a new
|
||||||
|
struct (the caller frees it with `FreeStructure`) or 0. It reads a view
|
||||||
|
made with `MsgPackWrapMsgBuffer()`, which the caller frees with
|
||||||
|
`MsgPackFree(*View, #False)`.
|
||||||
|
- **Linear code:** each field is written or read top to bottom: check its
|
||||||
|
type, read it, check the error, check its range. No loops, except for
|
||||||
|
lists such as SyncState's.
|
||||||
|
- **Which decoder to use:** `BakaShrot_GetPacketType()` reads a received
|
||||||
|
packet's type, so a handler can pick the right `_Decode`.
|
||||||
|
|
||||||
|
## Adding a packet
|
||||||
|
|
||||||
|
1. Add its id to `BakaShrot_PacketTypes` in `Commons/Networking/Packets.pbi`.
|
||||||
|
Never reuse an id.
|
||||||
|
2. Add `Commons/Networking/Packets/<Name>Packet.pbi`, with its structure
|
||||||
|
(`Extends BakaShrot_PacketBase`), `_Encode` and `_Decode`, following an
|
||||||
|
existing one.
|
||||||
|
3. Include it from `Commons/Networking/Connections.pbi`, and add it to the
|
||||||
|
flow comment at the top of that file.
|
||||||
|
4. **Server side:** handle it in `BakaShrot_NetClient_HandleRequest()`
|
||||||
|
(`Server/Networking/Networking.pbi`), checking the permission or role
|
||||||
|
first.
|
||||||
|
5. **Client side:** add a `<Name>String()` procedure to the DLL with its
|
||||||
|
`A`/`W` exports if it takes strings, a prototype in
|
||||||
|
`BakaShrot_Client_Prototypes.pbi`, and a tool if useful.
|
||||||
|
6. Update this document's packet table and flows.
|
||||||
@@ -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\<version>\` and zips it. `<version>` is `-Version`, or
|
||||||
|
`<date>-<commit>`, with `-dirty` if the tree has uncommitted changes (a
|
||||||
|
warning, not an error).
|
||||||
|
|
||||||
|
Its smoke test, from the release folder, on one server with a throwaway
|
||||||
|
database:
|
||||||
|
|
||||||
|
- generates keys with `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.
|
||||||
@@ -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.<name>]` section was never checked, so whatever answered on
|
||||||
|
the peer's address got this server's messages pushed to it.
|
||||||
|
|
||||||
|
Now a link's Hello is sealed for the peer section's `PublicKey`, and the
|
||||||
|
peer must sign the handshake with the matching private key, or the link
|
||||||
|
fails; the link is encrypted (`Design/Cryptography.md`). A missing or
|
||||||
|
invalid `PublicKey` stops the server at start. The section's `Topic` and
|
||||||
|
`Node` are still only checked when the peer links to here.
|
||||||
|
|
||||||
|
## 3. Peers are trusted completely
|
||||||
|
|
||||||
|
A connection that authenticated with a peer's identity and key can replicate
|
||||||
|
messages for any topic/node id the receiver replicates, with any content.
|
||||||
|
Messages carry no proof of who first wrote them, so a compromised or buggy
|
||||||
|
peer can inject or overwrite history for nodes it doesn't own. (Overwrite
|
||||||
|
only in the sense of issue 1: it can't replace an id that's already stored.)
|
||||||
|
|
||||||
|
**Fix:** sign each message with its originating node's key when it's first
|
||||||
|
stored, keep the signature with it, and verify it on replication. That needs
|
||||||
|
every server to know the public key of every node it replicates.
|
||||||
|
|
||||||
|
## 4. Database concurrency (fixed)
|
||||||
|
|
||||||
|
**Fixed 2026-11-06:** every link thread and client thread now has its own
|
||||||
|
database connection, see `Design/StorageConcurrency.md`. Kept below for the
|
||||||
|
record.
|
||||||
|
|
||||||
|
The link threads used to read the database with the same unlocked handle as
|
||||||
|
the client threads.
|
||||||
|
|
||||||
|
**Seen happening** (2026-11-06, benchmark with `PeerBatchSize = 1`):
|
||||||
|
1. Server 1's link thread was reading the messages to send.
|
||||||
|
2. At the same time, server 1's thread for server 2's incoming link was
|
||||||
|
reading the sync state for server 2's check-in.
|
||||||
|
3. Both went through the same handle, so a read came back empty while
|
||||||
|
messages were still left. Server 1 logged
|
||||||
|
`Sent 1424 messages ... it had up to #0` for a backlog of 5000, and the
|
||||||
|
check-in ended there.
|
||||||
|
|
||||||
|
The next check-in picked up where it stopped, so nothing was lost here. But
|
||||||
|
the same collision during a write could have stored wrong data.
|
||||||
|
|
||||||
|
## 5. Gaps aren't detected
|
||||||
|
|
||||||
|
Only `MAX(message_id)` is compared. If a server has `1, 2, 5` for a pair (say
|
||||||
|
`3` and `4` were refused midway through a check-in), it reports `5` and never
|
||||||
|
gets `3` and `4`. Messages are sent in order and the sending stops at the
|
||||||
|
first refusal, so this needs something unusual, but nothing repairs it.
|
||||||
|
|
||||||
|
**Fix:** send a count with the max (`COUNT(*) = MAX` means no gaps), and fall
|
||||||
|
back to comparing id ranges when they differ.
|
||||||
|
|
||||||
|
## 6. Speed: batched since, the per-batch overhead remains
|
||||||
|
|
||||||
|
**Benchmarks** (2026-11-06, both servers on localhost, PureBasic 5.73 x64,
|
||||||
|
SQLite 3.54.1). The same 5000 messages of ~28 bytes and 1000 of ~4 KB, sent
|
||||||
|
from scratch:
|
||||||
|
|
||||||
|
| Version | 5000 small | 1000 x 4 KB |
|
||||||
|
|---|---|---|
|
||||||
|
| One message per packet (before batching) | 63.6 s, ~79 msg/s | 12.2 s, ~82 msg/s |
|
||||||
|
| `PeerBatchSize = 1` | ~69-87 msg/s | 12.0 s, ~83 msg/s |
|
||||||
|
| `PeerBatchSize = 100` (default) | 0.67 s, ~7500 msg/s | 0.94 s, ~1070 msg/s, ~4.3 MB/s |
|
||||||
|
| `PeerBatchSize = 1000` | 0.11 s, ~45000 msg/s | 1.48 s, ~680 msg/s |
|
||||||
|
|
||||||
|
**Where the per-batch time goes,** measured before batching:
|
||||||
|
|
||||||
|
- **~3.8 ms is SQLite**, one transaction synced to disk. The same inserts
|
||||||
|
inside one transaction take 0.014 ms each (5000 in 71 ms). Hence one
|
||||||
|
transaction per batch.
|
||||||
|
- **The rest is polling.** Both ends wait for packets in `Delay(5)` loops
|
||||||
|
(5.5 ms each on Windows, `Delay(1)` is 1.6 ms), and each batch waits for
|
||||||
|
its acknowledgement before the next one, so it pays a few of those per
|
||||||
|
round trip.
|
||||||
|
|
||||||
|
**Big messages** don't gain from batch sizes over ~16: only that many 4 KB
|
||||||
|
messages fit in a ~64 KB batch (`#BakaShrot_ReplicateBatchBytes`). Since
|
||||||
|
2026-11-08 a batch stops reading rows once it has that much, so a big
|
||||||
|
`PeerBatchSize` no longer reads rows it then can't send.
|
||||||
|
|
||||||
|
**Further fixes, if needed:**
|
||||||
|
|
||||||
|
1. Keep the rows that didn't fit for the next batch instead of reading them
|
||||||
|
again.
|
||||||
|
2. ~~Wake the waiting thread when data arrives instead of polling with
|
||||||
|
`Delay(5)`.~~ Done 2026-11-07: client threads sleep on an event the
|
||||||
|
listener sets (`Commons/Threading/Signal.pbi`), the listener and the
|
||||||
|
outbound side sleep in `select()` (`Commons/Networking/SocketWait.pbi`).
|
||||||
|
3. Send the next batch before the previous one is acknowledged (a window).
|
||||||
|
4. ~~WAL mode~~ Done 2026-11-07, see `Design/StorageConcurrency.md`.
|
||||||
|
|
||||||
|
**Since then** (2026-11-07, `Tests/Bench/Bench-Replication.ps1`, 4 servers in
|
||||||
|
a Y): the hub relays up to ~5700 msg/s of pushes to its leaves without
|
||||||
|
falling behind, sending at ~38000 msg/s while a catch-up runs. The lag is
|
||||||
|
now just the check-in wait, 4-6 s of pushes at every load (two check-ins for
|
||||||
|
leaf to leaf). A shorter `PeerSyncInterval` is what would lower it.
|
||||||
|
|
||||||
|
~~**A message that's too big for a batch isn't replicated.**~~ Fixed
|
||||||
|
2026-11-08: pushes are capped at `#BakaShrot_MaxMessageSize`, 4 KB under the
|
||||||
|
16 MB packet limit, so one always fits in a batch of its own.
|
||||||
|
|
||||||
|
## 7. Sync state size limit
|
||||||
|
|
||||||
|
The whole sync state must fit in one packet: 16 MB since 2026-11-08 (was
|
||||||
|
64 KB, roughly 4000 topic/node pairs), so the counts are what limits it now,
|
||||||
|
65536 topics, nodes and pairs (`SyncStatePacket.pbi`). The replicated topics are also sent as a list, and
|
||||||
|
`ReplicatingTopicIds = 0-65535` expands to 65536 entries, which doesn't fit.
|
||||||
|
|
||||||
|
**Fix:** send ranges instead of expanded lists, and page the pairs (for
|
||||||
|
example per topic).
|
||||||
|
|
||||||
|
## 8. Two links per pair of servers
|
||||||
|
|
||||||
|
With two servers listing each other as peers, there are two connections, and
|
||||||
|
each one is only used by its opener to push. That's what makes both
|
||||||
|
directions work, but it doubles the connections and the check-ins. Fine for
|
||||||
|
now. If it ever matters, one link could carry both directions.
|
||||||
|
|
||||||
|
## 9. Messages for topics a server doesn't replicate
|
||||||
|
|
||||||
|
The receiver lists the topics it replicates, and the sender only sends
|
||||||
|
those, so they're never sent. But a batch that arrives for another topic
|
||||||
|
anyway is refused, and that stops the pair's catch-up for that check-in. It only happens if the two servers disagree about the list
|
||||||
|
mid-check-in, for example after a config change.
|
||||||
|
|
||||||
|
## 10. ~~Replicated messages aren't validated~~
|
||||||
|
|
||||||
|
Moot since 2026-11-08: pushed messages aren't checked to be JSON either,
|
||||||
|
both are stored as is and flagged by `is_json`.
|
||||||
@@ -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.
|
||||||
@@ -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.
|
||||||
@@ -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.<name>] 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"]]
|
||||||
@@ -0,0 +1,168 @@
|
|||||||
|
"""Checks bakashrot.py against a running server, run by Tests/Python-Test.ps1.
|
||||||
|
|
||||||
|
Usage: python check_bakashrot.py <DllPath> <KitchenIni> <LoungeIni>
|
||||||
|
KitchenIni logs:kitchen, may push to logs and secret, read everything, query.
|
||||||
|
LoungeIni logs:lounge, may read logs only.
|
||||||
|
Expects an empty database. Prints PASS/FAIL per check, exits 1 if any failed.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import 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)
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
"""Example app: catches up on a topic/node's messages, then follows new ones.
|
||||||
|
|
||||||
|
Usage: python example.py <ClientIni> <Topic> <Node> [--from-start]
|
||||||
|
Run it from Build\\ (Build.ps1) while BakaShrot_Server.exe runs, e.g.:
|
||||||
|
python ..\\Interactors\\Python\\example.py client.ini logs local
|
||||||
|
and push from another terminal:
|
||||||
|
.\\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)
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
This interactor should be able toquery a server via a client app.
|
||||||
|
The client should never parse the JSON, only the final app should.
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
# Runtime redistributables
|
||||||
|
|
||||||
|
DLLs the release needs next to its exes that Windows doesn't always have,
|
||||||
|
packaged by `Release.ps1`.
|
||||||
|
|
||||||
|
| File | Needed by | From | Version |
|
||||||
|
|---|---|---|---|
|
||||||
|
| `x64/vcruntime140.dll` | `libsodium.dll` (the official MSVC build) | Visual Studio 2026 (18) Community, `VC\Redist\MSVC\14.51.36231\x64\Microsoft.VC145.CRT\` | 14.51.36247.0 |
|
||||||
|
|
||||||
|
SHA-256 of `x64/vcruntime140.dll`:
|
||||||
|
`D1F4225DF2CD877DBF130D5668A021DCE3F94118455FF5EC952061C30AFC9CE7`
|
||||||
|
|
||||||
|
- **Why:** `libsodium.dll` imports `vcruntime140.dll` (the Visual C++
|
||||||
|
2015-2026 runtime). Without it, on a Windows without that runtime
|
||||||
|
installed, `BakaShrot_Server.exe`, `BakaShrot_Client.dll` and every tool
|
||||||
|
fail to load. Next to the exe, it's found before any installed one.
|
||||||
|
- **Not needed:** the other DLLs of that folder (`msvcp140.dll`,
|
||||||
|
`vcruntime140_1.dll`, ...): nothing imports them. The `api-ms-win-crt-*`
|
||||||
|
DLLs libsodium also imports are the Universal CRT, part of Windows 10 and
|
||||||
|
later, so the release needs Windows 10+.
|
||||||
|
- **Allowed:** files from Visual Studio's `VC\Redist` folder are the ones its
|
||||||
|
license lets you redistribute with an app.
|
||||||
|
- **Updating:** copy the newer one from that folder, update this table and
|
||||||
|
the hash. To check what a binary imports:
|
||||||
|
`grep -a -o -i -E "(vcruntime[0-9_]*|msvcp[0-9_]*|api-ms-win-crt-[a-z0-9-]+)\.dll" <file>`
|
||||||
|
- x86 isn't built, so there's no `x86/`.
|
||||||
Binary file not shown.
@@ -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\<date>-<commit>\` 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 <Topic> <Node> [--after <Id|latest>] [--limit <N>]
|
||||||
|
[--follow] [--interval <Ms>] [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.
|
||||||
+336
@@ -0,0 +1,336 @@
|
|||||||
|
# ============================================================================
|
||||||
|
# BakaShrot release build
|
||||||
|
#
|
||||||
|
# Builds everything with PureBasic 6.40's C backend and its optimizer into
|
||||||
|
# Release\<version>\, ready to copy to a server or hand to a client:
|
||||||
|
# BakaShrot_Server.exe the server
|
||||||
|
# BakaShrot_Client.dll the client DLL, with
|
||||||
|
# BakaShrot_Client_Prototypes.pbi its PureBasic prototypes
|
||||||
|
# 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-<version>.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 <date>-<commit>
|
||||||
|
# ... -Force replaces Release\<version>\ if it exists
|
||||||
|
# ... -Compiler <path> -NoOptimizer -SqliteDll <path> -SkipTest -NoZip
|
||||||
|
#
|
||||||
|
# Needs libsodium in Libs\libsodium\x64 and sqlite3.dll (3.38+, for the JSON
|
||||||
|
# functions) in Libs\sqlite\x64, Build.ps1 extracts both from Libs\*.zip.
|
||||||
|
# ============================================================================
|
||||||
|
|
||||||
|
param(
|
||||||
|
[string]$Version = "",
|
||||||
|
[string]$Compiler = "C:\Program Files\PureBasic_640\Compilers\pbcompilerc.exe",
|
||||||
|
[switch]$NoOptimizer,
|
||||||
|
[string]$SqliteDll = "",
|
||||||
|
[string]$OutRoot = "",
|
||||||
|
[switch]$Force,
|
||||||
|
[switch]$SkipTest,
|
||||||
|
[switch]$NoZip,
|
||||||
|
[int]$TestPort = 12399
|
||||||
|
)
|
||||||
|
|
||||||
|
$ErrorActionPreference = "Stop"
|
||||||
|
|
||||||
|
$Root = $PSScriptRoot
|
||||||
|
if (-not $OutRoot) { $OutRoot = Join-Path $Root "Release" }
|
||||||
|
|
||||||
|
|
||||||
|
# --- Checks -----------------------------------------------------------------
|
||||||
|
|
||||||
|
if (-not (Test-Path $Compiler)) { throw "Compiler not found: $Compiler, pass -Compiler" }
|
||||||
|
$CompilerName = ((& $Compiler /VERSION) | Select-Object -First 1) -replace " - \(c\).*$", ""
|
||||||
|
if ($CompilerName -notmatch "PureBasic 6\.") { throw "Expected PureBasic 6.x, got '$CompilerName'" }
|
||||||
|
if ($CompilerName -notmatch "C Backend") { Write-Warning "Not the C backend: $CompilerName" }
|
||||||
|
|
||||||
|
$Sodium = Join-Path $Root "Libs\libsodium\x64\libsodium.dll"
|
||||||
|
if (-not (Test-Path $Sodium) -or -not (Test-Path (Join-Path $Root "Libs\libsodium\x64\libsodium.lib"))) {
|
||||||
|
throw "Missing Libs\libsodium\x64\libsodium.dll/.lib, run Build.ps1 once to extract them"
|
||||||
|
}
|
||||||
|
if (-not $SqliteDll) { $SqliteDll = Join-Path $Root "Libs\sqlite\x64\sqlite3.dll" }
|
||||||
|
if (-not (Test-Path $SqliteDll)) { throw "Missing $SqliteDll, run Build.ps1 once to extract it, or pass -SqliteDll" }
|
||||||
|
$SqliteVersion = (Get-Item $SqliteDll).VersionInfo.ProductVersion
|
||||||
|
if ([version]$SqliteVersion -lt [version]"3.38") { throw "SQLite $SqliteVersion is too old, the JSON functions need 3.38+" }
|
||||||
|
$SodiumVersion = (Get-Item $Sodium).VersionInfo.ProductVersion
|
||||||
|
# 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 <Topic>] <Json|@JsonFile> [ClientIni]
|
||||||
|
GetLatestMessage <Topic> <Node> [ClientIni]
|
||||||
|
GetMessages <Topic> <Node> [--after <Id|latest>] [--limit <N>] [--follow] [--interval <Ms>] [ClientIni]
|
||||||
|
Resolve <topic|node> <NameOrId> [ClientIni]
|
||||||
|
ListNames [topics|nodes|all] [ClientIni] [--json]
|
||||||
|
Query <Sql|@SqlFile> [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 <ClientIni> <Topic> <Node>.
|
||||||
|
"@
|
||||||
|
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
|
||||||
@@ -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.<name>]. Then reads commands from the console:
|
||||||
|
; (empty), quit Stops the server.
|
||||||
|
; restart Stops every worker, reloads the config, starts again.
|
||||||
|
; vacuum Stops every worker, VACUUMs the database, starts again.
|
||||||
|
; names Lists every topic and node with its id and name.
|
||||||
|
; help Lists the commands.
|
||||||
|
; See Root.pbi for how the workers are stopped.
|
||||||
|
; Exits with 0 on success, 1 on failure.
|
||||||
|
;
|
||||||
|
; 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
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
IDE Options = PureBasic 6.41 beta 2 (Windows - x64)
|
||||||
|
CursorPosition = 15
|
||||||
|
FirstLine = 23
|
||||||
|
EnableXP
|
||||||
|
DPIAware
|
||||||
|
CompileSourceDirectory
|
||||||
|
EnableCompileCount = 1
|
||||||
|
EnableBuildCount = 0
|
||||||
@@ -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.<name>] -> one BakaShrot_CoreConfig\Peers() entry per
|
||||||
|
; section.
|
||||||
|
; [BakaShrot.Client.<name>] -> one BakaShrot_CoreConfig\Clients() entry per
|
||||||
|
; section.
|
||||||
|
;
|
||||||
|
; <name> 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.<name>] (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.<name>].
|
||||||
|
; 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.<name>], 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.<name>] (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.<name>] 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.<name>] entry per map key.
|
||||||
|
Map Peers.BakaShrot_PeerConfig()
|
||||||
|
|
||||||
|
; One [BakaShrot.Client.<name>] 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.<name>] 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.<name>] 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.<name>] and [BakaShrot.Client.<name>], 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
|
||||||
@@ -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.<name>] section per peer this node talks to.
|
||||||
|
; <name> is only a key for this file; it is never sent on the wire.
|
||||||
|
[BakaShrot.Peer.example]
|
||||||
|
; Remote address of the peer. Can be a domain name, IPV4 or IPV6.
|
||||||
|
Host =
|
||||||
|
|
||||||
|
; Remote port of the peer (0-65535).
|
||||||
|
Port =
|
||||||
|
|
||||||
|
; The server links to every peer on start, and retries every PeerRetryDelay.
|
||||||
|
; The peer must register this server in one of its [BakaShrot.Client.<name>].
|
||||||
|
; The link only goes through if the peer proves it holds the private key
|
||||||
|
; of PublicKey below, and it's encrypted.
|
||||||
|
|
||||||
|
; 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.<name>] section per client allowed to connect.
|
||||||
|
; <name> is only a key for this file; it is never sent on the wire.
|
||||||
|
[BakaShrot.Client.example]
|
||||||
|
; Ed25519 public keys (Base64) this client is allowed to authenticate with.
|
||||||
|
; Format: Key;Key;...
|
||||||
|
PublicKeys =
|
||||||
|
|
||||||
|
; 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
|
||||||
@@ -1,14 +1,14 @@
|
|||||||
|
|
||||||
[BakaShrot]
|
[BakaShrot]
|
||||||
PrivateKey =
|
PrivateKey =
|
||||||
GroupId = 0
|
TopicId = 0
|
||||||
NodeId = 0
|
NodeId = 0
|
||||||
[BakaShrot.Server]
|
[BakaShrot.Server]
|
||||||
Host =
|
Host =
|
||||||
Port = 0
|
Port = 0
|
||||||
ReplicatingGroupIds =
|
ReplicatingTopicIds =
|
||||||
[BakaShrot.Peer.example]
|
[BakaShrot.Peer.example]
|
||||||
Host =
|
Host =
|
||||||
Port = 0
|
Port = 0
|
||||||
GroupId = 0
|
TopicId = 0
|
||||||
NodeId = 0
|
NodeId = 0
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,7 @@
|
|||||||
|
IDE Options = PureBasic 6.41 beta 2 (Windows - x64)
|
||||||
|
EnableThread
|
||||||
|
EnableXP
|
||||||
|
DPIAware
|
||||||
|
CompileSourceDirectory
|
||||||
|
EnableCompileCount = 0
|
||||||
|
EnableBuildCount = 0
|
||||||
@@ -0,0 +1,568 @@
|
|||||||
|
; ============================================================================
|
||||||
|
; BakaShrot Server Peers
|
||||||
|
;
|
||||||
|
; Links this server to the other servers in its config's
|
||||||
|
; [BakaShrot.Peer.<name>] sections, one thread per peer. Each thread:
|
||||||
|
; 1. Connects to the peer and authenticates with this server's own identity
|
||||||
|
; ([BakaShrot] PrivateKey/TopicId/NodeId), like a client would. The peer
|
||||||
|
; must have it registered in one of its [BakaShrot.Client.<name>].
|
||||||
|
; 2. Stays connected until the link drops.
|
||||||
|
; 3. Waits [BakaShrot.Server] PeerRetryDelay seconds, then starts over.
|
||||||
|
; Same after a failed attempt.
|
||||||
|
;
|
||||||
|
; Once linked, it checks in with the peer every [BakaShrot.Server]
|
||||||
|
; PeerSyncInterval seconds, starting right away:
|
||||||
|
; 1. Asks the peer for its sync state: the topics it takes from this
|
||||||
|
; server, and the highest message id it has for each of their
|
||||||
|
; topic/node ids, in its own ids, with their names.
|
||||||
|
; 2. Compares it with this server's own (GetSyncState() in Storage.pbi),
|
||||||
|
; matching topics and nodes by name: each server has its own ids, see
|
||||||
|
; Server/Storage/Names.pbi. Only what's named on both sides replicates:
|
||||||
|
; an unnamed one, or one whose name the peer doesn't list, is dropped
|
||||||
|
; (BakaShrot_Names_NoteDropped()).
|
||||||
|
; 3. For every topic/node the peer takes, this server sends it
|
||||||
|
; (the peer section's SendTopics), and the peer is behind on, sends it
|
||||||
|
; the missing messages in order, in batches of up to
|
||||||
|
; [BakaShrot.Server] PeerBatchSize messages, about 64 KB at most (a
|
||||||
|
; bigger message goes alone, see ReplicateMessagesPacket.pbi), each
|
||||||
|
; batch stored in one transaction and answered before the next. The
|
||||||
|
; batches carry the names, the peer stores them under its own ids.
|
||||||
|
; The peer does the same over its own link to this server, which covers the
|
||||||
|
; other direction. Any packet from the peer outside of a check-in drops the
|
||||||
|
; link as unexpected.
|
||||||
|
; Known issues, like two servers drifting apart: Design/ReplicationIssues.md.
|
||||||
|
;
|
||||||
|
; Each link thread opens its own database connection when it starts, and
|
||||||
|
; closes it when it ends. See the top of Storage/Storage.pbi.
|
||||||
|
;
|
||||||
|
; The peer proves itself in the handshake: the Hello is sealed for the peer
|
||||||
|
; section's PublicKey and the peer must sign the handshake with the matching
|
||||||
|
; private key, so a link only reaches the real peer, and is encrypted
|
||||||
|
; (Commons/Networking/Connections.pbi).
|
||||||
|
;
|
||||||
|
; Logs with PrintN(), so the program must have a console open.
|
||||||
|
; Must be compiled with the thread-safe option enabled.
|
||||||
|
; ============================================================================
|
||||||
|
|
||||||
|
CompilerIf Not #PB_Compiler_Thread
|
||||||
|
CompilerError "Peers.pbi needs the thread-safe option (Compiler Options > Create threadsafe executable)."
|
||||||
|
CompilerEndIf
|
||||||
|
|
||||||
|
XIncludeFile "../../Commons/Networking/Outbound.pbi"
|
||||||
|
XIncludeFile "../Config/Config.pbi"
|
||||||
|
XIncludeFile "../Storage/Storage.pbi"
|
||||||
|
XIncludeFile "../Storage/Names.pbi"
|
||||||
|
|
||||||
|
|
||||||
|
Structure BakaShrot_PeerLink
|
||||||
|
*Links
|
||||||
|
|
||||||
|
; [BakaShrot.Peer.<name>]
|
||||||
|
Name.s
|
||||||
|
Host.s
|
||||||
|
Port.i
|
||||||
|
|
||||||
|
; The peer section's PublicKey: who the peer must prove to be.
|
||||||
|
ServerPublicKey.a[#BakaShrot_Ed25519_PublicKeySize]
|
||||||
|
|
||||||
|
ThreadId.i
|
||||||
|
|
||||||
|
; Only used by the link's thread.
|
||||||
|
Outbound.BakaShrot_Outbound
|
||||||
|
DbId.i
|
||||||
|
|
||||||
|
; The peer section's SendTopics and SendNodes, copied for the link's thread.
|
||||||
|
SendTopics.BakaShrot_NameSet
|
||||||
|
SendNodes.BakaShrot_NameSet
|
||||||
|
EndStructure
|
||||||
|
|
||||||
|
|
||||||
|
Structure BakaShrot_PeerLinks
|
||||||
|
; Set by BakaShrot_PeerLinks_Stop(), makes every link's thread return.
|
||||||
|
StopRequested.i
|
||||||
|
|
||||||
|
RetryDelayMs.i
|
||||||
|
SyncIntervalMs.i
|
||||||
|
|
||||||
|
; Most messages sent per ReplicateMessages packet.
|
||||||
|
BatchSize.i
|
||||||
|
|
||||||
|
; Every link's thread opens its own connection to it.
|
||||||
|
DatabasePath.s
|
||||||
|
|
||||||
|
; This server's identity, read by every link's thread.
|
||||||
|
Identity.BakaShrot_OutboundIdentity
|
||||||
|
PrivateKey.a[#BakaShrot_Ed25519_PrivateKeySize]
|
||||||
|
PublicKey.a[#BakaShrot_Ed25519_PublicKeySize]
|
||||||
|
|
||||||
|
List Links.BakaShrot_PeerLink()
|
||||||
|
EndStructure
|
||||||
|
|
||||||
|
|
||||||
|
; Waits the retry delay, returns early if stopping.
|
||||||
|
Procedure BakaShrot_PeerLink_WaitRetry(*Link.BakaShrot_PeerLink)
|
||||||
|
Protected *Links.BakaShrot_PeerLinks = *Link\Links
|
||||||
|
Protected StartTime.i
|
||||||
|
|
||||||
|
StartTime = ElapsedMilliseconds()
|
||||||
|
While Not *Links\StopRequested And ElapsedMilliseconds() - StartTime < *Links\RetryDelayMs
|
||||||
|
Delay(100)
|
||||||
|
Wend
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
|
||||||
|
; Sends a request to the peer and waits for its answer.
|
||||||
|
; Returns the answer (free it with FreeMemory) with its size in *OutSize\i,
|
||||||
|
; or 0 if the link failed.
|
||||||
|
Procedure.i BakaShrot_PeerLink_Request(*Link.BakaShrot_PeerLink, *Request, RequestSize.i, *OutSize.Integer)
|
||||||
|
If Not BakaShrot_Outbound_Send(@*Link\Outbound, *Request, RequestSize)
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
ProcedureReturn BakaShrot_Outbound_WaitPacket(@*Link\Outbound, *OutSize, #BakaShrot_Outbound_Timeout)
|
||||||
|
EndProcedure
|
||||||
|
|
||||||
|
|
||||||
|
; Logs a RequestRefused answer from the peer.
|
||||||
|
; Returns #False if it's malformed, the link must then be dropped.
|
||||||
|
Procedure.i BakaShrot_PeerLink_LogRefusal(*Link.BakaShrot_PeerLink, *Answer, AnswerSize.i)
|
||||||
|
Protected *View.MsgPackData, *Refused.BakaShrot_RequestRefused
|
||||||
|
|
||||||
|
*Refused = 0
|
||||||
|
*View = MsgPackWrapMsgBuffer(*Answer, AnswerSize)
|
||||||
|
If *View
|
||||||
|
*Refused = BakaShrot_RequestRefusedPacket_Decode(*View)
|
||||||
|
MsgPackFree(*View, #False)
|
||||||
|
EndIf
|
||||||
|
If Not *Refused
|
||||||
|
ProcedureReturn #False
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
PrintN("[Peer] '" + *Link\Name + "' refused: " + *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.<name>] in *Config, replicating
|
||||||
|
; the messages in its [BakaShrot.Server] DatabasePath. *Config must outlive
|
||||||
|
; the links.
|
||||||
|
; Returns 0 if *Config's PrivateKey is invalid or a thread couldn't start,
|
||||||
|
; stop the returned links with BakaShrot_PeerLinks_Stop().
|
||||||
|
Procedure.i BakaShrot_PeerLinks_Start(*Config.BakaShrot_CoreConfig)
|
||||||
|
Protected *Links.BakaShrot_PeerLinks
|
||||||
|
|
||||||
|
If Not InitCryptography()
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
*Links = AllocateStructure(BakaShrot_PeerLinks)
|
||||||
|
If Not *Links
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
|
||||||
|
; Identity
|
||||||
|
If Not DecodeKeyFromString(*Config\PrivateKey, @*Links\PrivateKey[0], #BakaShrot_Ed25519_PrivateKeySize)
|
||||||
|
FreeStructure(*Links)
|
||||||
|
ProcedureReturn 0
|
||||||
|
EndIf
|
||||||
|
GetPublicKeyFromPrivateKey(@*Links\PrivateKey[0], @*Links\PublicKey[0])
|
||||||
|
|
||||||
|
; By name: the peer has its own ids for them.
|
||||||
|
*Links\Identity\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
|
||||||
+207
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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\<timestamp>\: 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\<timestamp>\ 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"
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,181 @@
|
|||||||
|
; ============================================================================
|
||||||
|
; BakaShrot Bench Seed
|
||||||
|
;
|
||||||
|
; Usage: BenchSeed <TopicId> <Nodes> <RowsPerNode> <MessageSize> <Db> [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<Node>", 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 <TopicId> <Nodes> <RowsPerNode> <MessageSize> <Db> [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
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
; ============================================================================
|
||||||
|
; BakaShrot Bench Server
|
||||||
|
;
|
||||||
|
; Usage: BenchServer <ConfigFile> <StopFile>
|
||||||
|
;
|
||||||
|
; 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 <ConfigFile> <StopFile>")
|
||||||
|
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
|
||||||
@@ -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
|
||||||
@@ -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.
|
||||||
@@ -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
|
||||||
@@ -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'
|
||||||
@@ -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" }
|
||||||
@@ -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
|
||||||
@@ -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 })
|
||||||
@@ -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
|
||||||
@@ -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" }
|
||||||
@@ -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 <python.exe>]
|
||||||
|
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
|
||||||
@@ -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 <BakaShrot_Client.dll> <client.ini> <proxy port> <other public key>
|
||||||
|
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)
|
||||||
@@ -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
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
; ============================================================================
|
||||||
|
; BakaShrot GetLatestMessage
|
||||||
|
;
|
||||||
|
; Usage: GetLatestMessage <Topic> <Node> [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 <Topic> <Node> [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
|
||||||
@@ -0,0 +1,180 @@
|
|||||||
|
; ============================================================================
|
||||||
|
; BakaShrot GetMessages
|
||||||
|
;
|
||||||
|
; Usage: GetMessages <Topic> <Node> [options] [ClientIni]
|
||||||
|
; Topic, Node Whose messages to get, each a name or an id.
|
||||||
|
; --after <Id> 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 <N> 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 <Ms> 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 <Topic> <Node> [--after <Id|latest>] [--limit <N>] [--follow] [--interval <Ms>] [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
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
; ============================================================================
|
||||||
|
; BakaShrot KeyGen
|
||||||
|
;
|
||||||
|
; Generates a new Ed25519 keypair and prints it as two ini-style lines:
|
||||||
|
; PrivateKey = <Base64>
|
||||||
|
; PublicKey = <Base64>
|
||||||
|
;
|
||||||
|
; 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
|
||||||
@@ -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
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
; ============================================================================
|
||||||
|
; BakaShrot PushMessage
|
||||||
|
;
|
||||||
|
; Usage: PushMessage [-t <Topic>] <Json|@JsonFile> [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 <Topic>] <Json|@JsonFile> [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
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
; ============================================================================
|
||||||
|
; BakaShrot Query
|
||||||
|
;
|
||||||
|
; Usage: Query <Sql|@SqlFile> [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.<name>].
|
||||||
|
; 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 <Sql|@SqlFile> [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
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
; ============================================================================
|
||||||
|
; BakaShrot Resolve
|
||||||
|
;
|
||||||
|
; Usage: Resolve <topic|node> <NameOrId> [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 <topic|node> <NameOrId> [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
|
||||||
Reference in New Issue
Block a user