diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 0000000..4c36d2e --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,11 @@ +# The C runtime linked statically on Windows (MSVC): the DLL and the +# programs need no Visual C++ redistributable (../revamp.md, "Decided" 2). +[target.'cfg(all(windows, target_env = "msvc"))'] +rustflags = ["-C", "target-feature=+crt-static"] + +# aws-lc seeds its random generator from the OS's (and RDRAND), without CPU +# Jitter Entropy: that one takes about 25 ms in every process, at its first +# connection (every tool command, every script through the DLL). Decided +# 2026-11-14 (../revamp.md, "Randomness from the OS"; ../docs/certificates.md). +[env] +AWS_LC_SYS_NO_JITTER_ENTROPY = "1" diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..4520eba --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +# The new sources use LF everywhere, whatever the platform. +* text=auto eol=lf +*.ps1 text eol=crlf diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..9c5baa9 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,194 @@ +# On a version tag, or run by hand: the same checks as test.ps1 (Windows +# and Linux), then a release for each platform (release.py), its archive +# kept as the run's artifact, and the server's Docker image for amd64 and +# arm64, checked (docker/test.sh), pushed to ghcr.io on a tag only. Gitea +# Actions runs this file too. +# +# Safety: only people with write access can push a tag or run it by hand +# (no pull_request trigger, so nothing from a fork runs here); the token +# is read-only except where an image is pushed, after it was built and +# checked; checkouts don't keep the token on disk, so a build script (a +# crate's build.rs) can't read it; actions are pinned to their commits; +# cargo builds only what Cargo.lock says (--locked). +name: CI + +on: + push: + tags: ["v*"] + workflow_dispatch: + +permissions: + contents: read + +env: + IMAGE: ghcr.io/aziascreations/bakashrot-server + +jobs: + check: + strategy: + fail-fast: false + matrix: + os: [windows-latest, ubuntu-latest] + runs-on: ${{ matrix.os }} + timeout-minutes: 60 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + # Installs the toolchain rust-toolchain.toml pins. + - run: rustup toolchain install + - run: cargo fmt --all -- --check + - run: cargo clippy --locked --workspace --all-targets --all-features -- -D warnings + - run: cargo test --locked --workspace --all-features + - run: cargo doc --locked --workspace --no-deps --all-features + env: + RUSTDOCFLAGS: -D warnings + + release: + # Build, package, smoke test, each on its own kind of machine: no + # cross-compiling, and the smoke test runs where the release will. + # Linux builds in manylinux 2.28 (glibc 2.28): the programs, the .so + # and the wheel run on systems that old. + needs: check + strategy: + fail-fast: false + matrix: + include: + - platform: windows-x64 + os: windows-latest + arch: x64 + - platform: windows-arm64 + # aws-lc needs clang-cl there: Visual Studio's, on this image. + os: windows-11-arm + arch: arm64 + - platform: linux-x64 + os: ubuntu-latest + container: quay.io/pypa/manylinux_2_28_x86_64 + - platform: linux-arm64 + os: ubuntu-24.04-arm + container: quay.io/pypa/manylinux_2_28_aarch64 + runs-on: ${{ matrix.os }} + container: ${{ matrix.container }} + timeout-minutes: 60 + defaults: + run: + shell: bash + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + # Windows: a Python of the machine's architecture (the smoke test + # loads the DLL into it). Linux: the container's. + - if: ${{ !matrix.container }} + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: "3.12" + architecture: ${{ matrix.arch }} + - if: ${{ matrix.container }} + run: echo "/opt/python/cp312-cp312/bin" >> "$GITHUB_PATH" + # rustup, where the image has none (windows-11-arm, the containers). + - run: | + if ! command -v rustup; then + if [ "$RUNNER_OS" = Windows ]; then + case "$RUNNER_ARCH" in ARM64) host=aarch64-pc-windows-msvc ;; *) host=x86_64-pc-windows-msvc ;; esac + curl --proto '=https' --tlsv1.2 -sSfo rustup-init.exe "https://static.rust-lang.org/rustup/dist/$host/rustup-init.exe" + ./rustup-init.exe -y --default-toolchain none + rm rustup-init.exe + echo "$USERPROFILE/.cargo/bin" >> "$GITHUB_PATH" + else + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain none + echo "$HOME/.cargo/bin" >> "$GITHUB_PATH" + fi + fi + - run: rustup toolchain install + # Builds with --locked; the archive holds no keys (the smoke test's + # are in _test/, deleted before archiving). + - run: python release.py + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: bakashrot-${{ matrix.platform }} + path: | + target/dist/*.zip + target/dist/*.tar.gz + if-no-files-found: error + + docker: + # The server's image, each architecture built on its own kind of + # machine (no emulation), checked, then pushed as - on a + # tag. Run by hand, it's built and checked only. The token can push + # packages here, but it's only given to `docker login`, after the build + # and the check (the build runs inside Docker, without it). + needs: check + strategy: + fail-fast: false + matrix: + include: + - arch: amd64 + os: ubuntu-latest + - arch: arm64 + os: ubuntu-24.04-arm + runs-on: ${{ matrix.os }} + timeout-minutes: 60 + permissions: + contents: read + packages: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Image tag + env: + ARCH: ${{ matrix.arch }} + run: | + if [ "$GITHUB_REF_TYPE" = tag ]; then version=${GITHUB_REF_NAME#v}; else version=manual; fi + # What a Docker tag may hold; anything else stops here. + case "$version" in + "" | *[!0-9A-Za-z._-]* | [.-]*) echo "Not a usable image tag: $version"; exit 1 ;; + esac + echo "TAG=$IMAGE:$version-$ARCH" >> "$GITHUB_ENV" + - run: docker build -f docker/Dockerfile -t "$TAG" . + - run: sh docker/test.sh "$TAG" + - name: Log in to ghcr.io + if: github.ref_type == 'tag' + env: + TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: echo "$TOKEN" | docker login ghcr.io -u "$GITHUB_ACTOR" --password-stdin + # A package first pushed by hand (with a personal token) only takes + # this workflow's pushes once the repository has write access in the + # package's settings ("Manage Actions access"). + - name: Push + if: github.ref_type == 'tag' + run: docker push "$TAG" + - name: Log out + if: always() && github.ref_type == 'tag' + run: docker logout ghcr.io + + docker-index: + # One image for both architectures: an index of the two as , + # once the releases passed too, and as latest unless it's a + # pre-release (a version with a "-": v0.2.0-test2). GitHub reads the + # source label on an index from its annotations. + if: github.ref_type == 'tag' + needs: [docker, release] + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + packages: write + steps: + - env: + TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + version=${GITHUB_REF_NAME#v} + case "$version" in + "" | *[!0-9A-Za-z._-]* | [.-]*) echo "Not a usable image tag: $version"; exit 1 ;; + esac + tags="-t $IMAGE:$version" + case "$version" in *-*) ;; *) tags="$tags -t $IMAGE:latest" ;; esac + echo "$TOKEN" | docker login ghcr.io -u "$GITHUB_ACTOR" --password-stdin + # $tags unquoted on purpose: two words each, checked above. + docker buildx imagetools create $tags \ + --annotation "index:org.opencontainers.image.source=https://github.com/aziascreations/BakaShrot" \ + --annotation "index:org.opencontainers.image.description=BakaShrot server" \ + --annotation "index:org.opencontainers.image.licenses=CC0-1.0" \ + "$IMAGE:$version-amd64" "$IMAGE:$version-arm64" + docker logout ghcr.io diff --git a/.gitignore b/.gitignore index 4b71ce2..704996d 100644 --- a/.gitignore +++ b/.gitignore @@ -5,24 +5,17 @@ # Build Artifacts *.exe *.dll -# ... except the runtime redistributables the release packages, see Libs/redist/README.md -!Libs/redist/**/*.dll *.so *.a *.pdb *.lib *.exp -# Build output, holds generated private keys -Build/ - -# Release builds, see Release.ps1 -Release/ - # Python __pycache__/ -# The examples run their server in their own folder: its database, and -# what their client scripts write -Examples/**/*.sqlite* -Examples/**/out/ +# Rust +target/ + +# The compose example's config (keys) +docker/config/ diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index e8a3d2b..0000000 --- a/.gitmodules +++ /dev/null @@ -1,3 +0,0 @@ -[submodule "Includes/PB-MessagePack"] - path = Includes/PB-MessagePack - url = https://github.com/aziascreations/PB-MessagePack.git diff --git a/Build.ps1 b/Build.ps1 deleted file mode 100644 index 557b9fc..0000000 --- a/Build.ps1 +++ /dev/null @@ -1,333 +0,0 @@ -# ============================================================================ -# BakaShrot build & run script -# -# 0. Extracts libsodium's dynamic build from Libs/libsodium-*-msvc.zip, and -# sqlite3.dll from the latest Libs/sqlite-dll-win-*.zip, if not done yet. -# Delete Libs/libsodium/x64 or Libs/sqlite/x64 to extract them again. -# 1. Compiles BakaShrotGenerateKeyPairs, the server, the client DLL, its -# example app and the tools (BakaShrotPushMessage, -# BakaShrotGetLatestMessage, BakaShrotGetMessages, BakaShrotGetAttachment, -# BakaShrotQuery, BakaShrotResolveIds, BakaShrotList) into ./Build, next to copies of -# libsodium.dll and sqlite3.dll -# 2. Generates a keypair for two servers and one for a client -# 3. Writes the servers' configs and the client's keys. Topics and nodes -# have names, and each server its own ids for them, to show names being -# translated (logs is 1 on server, 200 on server2): -# server.ini logs:server1 on port 12345, registers the client, peer -# of server2, database ./server.sqlite -# server2.ini logs:server2 on port 12346, peer of server, database -# ./server2.sqlite -# client.ini logs:local through server, for the tools and the example -# app, may push to logs and sensors, read every topic, and -# run raw queries -# client2.ini logs:local2 through server2, same client key, may not query -# Both servers replicate logs and sensors to each other, e.g.: -# .\BakaShrotPushMessage.exe -t sensors @msg.json client.ini -# .\BakaShrotGetLatestMessage.exe sensors local client2.ini -# .\BakaShrotGetMessages.exe logs local --follow client2.ini -# .\BakaShrotResolveIds.exe topic sensors client2.ini (201 there, 2 on server) -# .\BakaShrotQuery.exe "SELECT topic, node, message_id FROM messages" client.ini -# 4. Runs the first server, type "quit" or an empty line to stop it, or -# "restart" / "vacuum" / "help". Run the second one in -# another terminal to see them link: .\BakaShrot_Server.exe server2.ini -# -# Usage: powershell -ExecutionPolicy Bypass -File Build.ps1 [-Compiler ] -# -# Keys are regenerated on every run, ./Build is git-ignored since it holds -# private keys. -# ============================================================================ - -param( - [string]$Compiler = "C:\Program Files\PureBasic_573\Compilers\pbcompiler.exe" -) - -$ErrorActionPreference = "Stop" - -$Root = $PSScriptRoot -$Output = Join-Path $Root "Build" - -# Where Commons/Cryptography/Libsodium.pbi imports it from, x64 since the -# compiler above is the x64 one. -$SodiumDir = Join-Path $Root "Libs\libsodium\x64" - -# Where sqlite3.dll is extracted to, the server loads it instead of the -# SQLite bundled with PureBasic 5.73, which lacks the JSON functions. -$SqliteDir = Join-Path $Root "Libs\sqlite\x64" - -$ServerHost = "127.0.0.1" -$ServerPort = 12345 -$Server2Port = 12346 -$PeerRetryDelay = 10 -$PeerBatchSize = 100 - -# The same names on both servers, different ids, see the top of this file. -# Same client, through server2 as its own node (local2), so no topic/node is -# ever written to on both servers. -$Topics = @{ logs = 1; sensors = 2 } -$Nodes = @{ server1 = 1; local = 2; server2 = 3; local2 = 4 } -$Topics2 = @{ logs = 200; sensors = 201 } -$Nodes2 = @{ server1 = 11; local = 12; server2 = 13; local2 = 14 } - -function Format-Names($Names) { - ($Names.GetEnumerator() | Sort-Object Value | ForEach-Object { "$($_.Key) = $($_.Value)" }) -join "`r`n" -} - -function Expand-Libsodium { - $Zip = Get-ChildItem (Join-Path $Root "Libs") -Filter "libsodium-*-msvc.zip" | Select-Object -First 1 - if (-not $Zip) { - throw "Missing Libs\libsodium-*-msvc.zip, get it from https://download.libsodium.org/libsodium/releases/" - } - - Write-Host "Extracting libsodium from $($Zip.Name)" - Add-Type -AssemblyName System.IO.Compression.FileSystem - $Archive = [IO.Compression.ZipFile]::OpenRead($Zip.FullName) - try { - # Zip folder -> Libs\libsodium folder - $Targets = @{ "x64" = "x64"; "Win32" = "x86" } - foreach ($Arch in $Targets.Keys) { - $Destination = Join-Path $Root "Libs\libsodium\$($Targets[$Arch])" - New-Item -ItemType Directory -Force $Destination | Out-Null - foreach ($Name in @("libsodium.dll", "libsodium.lib")) { - $Entry = $Archive.GetEntry("libsodium/$Arch/Release/v143/dynamic/$Name") - if (-not $Entry) { - throw "$($Zip.Name) has no $Arch dynamic $Name" - } - [IO.Compression.ZipFileExtensions]::ExtractToFile($Entry, (Join-Path $Destination $Name), $true) - } - } - } - finally { - $Archive.Dispose() - } -} - -function Expand-Sqlite { - Add-Type -AssemblyName System.IO.Compression.FileSystem - - foreach ($Arch in @("x64", "x86")) { - # The version in the name is zero-padded, so the last one by name is the latest. - $Zip = Get-ChildItem (Join-Path $Root "Libs") -Filter "sqlite-dll-win-$Arch-*.zip" | Sort-Object Name | Select-Object -Last 1 - if (-not $Zip) { - throw "Missing Libs\sqlite-dll-win-$Arch-*.zip, get it from https://www.sqlite.org/download.html" - } - - Write-Host "Extracting SQLite from $($Zip.Name)" - $Destination = Join-Path $Root "Libs\sqlite\$Arch" - New-Item -ItemType Directory -Force $Destination | Out-Null - - $Archive = [IO.Compression.ZipFile]::OpenRead($Zip.FullName) - try { - $Entry = $Archive.GetEntry("sqlite3.dll") - if (-not $Entry) { - throw "$($Zip.Name) has no sqlite3.dll" - } - [IO.Compression.ZipFileExtensions]::ExtractToFile($Entry, (Join-Path $Destination "sqlite3.dll"), $true) - } - finally { - $Archive.Dispose() - } - } -} - -function Invoke-Compiler($Source, $Executable, $Flags) { - Write-Host "Compiling $Source" - & $Compiler (Join-Path $Root $Source) @Flags /QUIET /EXE (Join-Path $Output $Executable) - if ($LASTEXITCODE -ne 0) { - throw "Failed to compile $Source" - } -} - -function New-KeyPair { - # BakaShrotGenerateKeyPairs prints "PrivateKey = ..." then "PublicKey = ...". - $Lines = & (Join-Path $Output "BakaShrotGenerateKeyPairs.exe") - if ($LASTEXITCODE -ne 0) { - throw "BakaShrotGenerateKeyPairs failed: $Lines" - } - return @{ - PrivateKey = $Lines[0] -replace "^PrivateKey = ", "" - PublicKey = $Lines[1] -replace "^PublicKey = ", "" - } -} - - -Push-Location $Root -try { - New-Item -ItemType Directory -Force $Output | Out-Null - - # 0. libsodium - if (-not (Test-Path (Join-Path $SodiumDir "libsodium.lib"))) { - Expand-Libsodium - } - Copy-Item (Join-Path $SodiumDir "libsodium.dll") $Output -Force - - # 0. SQLite - if (-not (Test-Path (Join-Path $SqliteDir "sqlite3.dll"))) { - Expand-Sqlite - } - Copy-Item (Join-Path $SqliteDir "sqlite3.dll") $Output -Force - - # 1. Compile - Invoke-Compiler "Tools\BakaShrotGenerateKeyPairs\BakaShrotGenerateKeyPairs.pb" "BakaShrotGenerateKeyPairs.exe" @("/CONSOLE") - Invoke-Compiler "Server\BakaShrot_Server.pb" "BakaShrot_Server.exe" @("/CONSOLE", "/THREAD") - Invoke-Compiler "Client\BakaShrot_Client.pbi" "BakaShrot_Client.dll" @("/DLL", "/THREAD") - # Example app using the DLL, run it from ./Build while the server runs. - Invoke-Compiler "Client\BakaShrot_Client_Prototypes.pbi" "ClientExample.exe" @("/CONSOLE") - # Tools using the DLL, same as the example: - # BakaShrotPushMessage [-t ] [-a ] [ClientIni] - Invoke-Compiler "Tools\BakaShrotPushMessage\BakaShrotPushMessage.pb" "BakaShrotPushMessage.exe" @("/CONSOLE") - # BakaShrotGetLatestMessage [ClientIni] - Invoke-Compiler "Tools\BakaShrotGetLatestMessage\BakaShrotGetLatestMessage.pb" "BakaShrotGetLatestMessage.exe" @("/CONSOLE") - # BakaShrotGetMessages [--after ] [--limit ] [--follow] [ClientIni] - Invoke-Compiler "Tools\BakaShrotGetMessages\BakaShrotGetMessages.pb" "BakaShrotGetMessages.exe" @("/CONSOLE") - # BakaShrotGetAttachment [ClientIni] - Invoke-Compiler "Tools\BakaShrotGetAttachment\BakaShrotGetAttachment.pb" "BakaShrotGetAttachment.exe" @("/CONSOLE") - # BakaShrotQuery [ClientIni] - Invoke-Compiler "Tools\BakaShrotQuery\BakaShrotQuery.pb" "BakaShrotQuery.exe" @("/CONSOLE") - # BakaShrotResolveIds [ClientIni] - Invoke-Compiler "Tools\BakaShrotResolveIds\BakaShrotResolveIds.pb" "BakaShrotResolveIds.exe" @("/CONSOLE") - # BakaShrotList [topics|nodes|all] [ClientIni] [--json] - Invoke-Compiler "Tools\BakaShrotList\BakaShrotList.pb" "BakaShrotList.exe" @("/CONSOLE") - - # 2. Keys - Write-Host "Generating keys" - $ServerKeys = New-KeyPair - $Server2Keys = New-KeyPair - $ClientKeys = New-KeyPair - - # 3. Configs - # Both servers are each other's peer, and register each other as a client - # so the links can authenticate. - $ServerConfig = @" -[BakaShrot] -PrivateKey = $($ServerKeys.PrivateKey) -Node = server1 - -; This server's ids for the names every server shares. -[BakaShrot.Topics] -$(Format-Names $Topics) - -[BakaShrot.Nodes] -$(Format-Names $Nodes) - -[BakaShrot.Server] -Host = $ServerHost -Port = $ServerPort -ReplicatingTopics = logs;sensors -NetThreadPoolSize = 4 -DatabasePath = ./server.sqlite -PeerRetryDelay = $PeerRetryDelay -PeerBatchSize = $PeerBatchSize - -[BakaShrot.Peer.server2] -Host = $ServerHost -Port = $Server2Port -Node = server2 -PublicKey = $($Server2Keys.PublicKey) - -[BakaShrot.Client.local] -PublicKeys = $($ClientKeys.PublicKey) -Node = local -DefaultTopic = logs -PushTopics = logs;sensors -ReadTopics = * -AllowRead = 1 -AllowWrite = 1 -AllowQuery = 1 - -; The peer only replicates, it has no business reading or writing as a client. -[BakaShrot.Client.server2] -PublicKeys = $($Server2Keys.PublicKey) -Node = server2 -AllowRead = 0 -AllowWrite = 0 -AllowQuery = 0 -"@ - Set-Content -Path (Join-Path $Output "server.ini") -Value $ServerConfig -Encoding Ascii - - $Server2Config = @" -[BakaShrot] -PrivateKey = $($Server2Keys.PrivateKey) -Node = server2 - -; Other ids than server's, same names: replication goes by name. -[BakaShrot.Topics] -$(Format-Names $Topics2) - -[BakaShrot.Nodes] -$(Format-Names $Nodes2) - -[BakaShrot.Server] -Host = $ServerHost -Port = $Server2Port -ReplicatingTopics = logs;sensors -NetThreadPoolSize = 4 -DatabasePath = ./server2.sqlite -PeerRetryDelay = $PeerRetryDelay -PeerBatchSize = $PeerBatchSize - -[BakaShrot.Peer.server] -Host = $ServerHost -Port = $ServerPort -Node = server1 -PublicKey = $($ServerKeys.PublicKey) - -; The peer only replicates, it has no business reading or writing as a client. -[BakaShrot.Client.server] -PublicKeys = $($ServerKeys.PublicKey) -Node = server1 -AllowRead = 0 -AllowWrite = 0 -AllowQuery = 0 - -; No raw queries through this server. -[BakaShrot.Client.local] -PublicKeys = $($ClientKeys.PublicKey) -Node = local2 -DefaultTopic = logs -PushTopics = logs;sensors -ReadTopics = * -AllowRead = 1 -AllowWrite = 1 -AllowQuery = 0 -"@ - Set-Content -Path (Join-Path $Output "server2.ini") -Value $Server2Config -Encoding Ascii - - $Client2Config = @" -[BakaShrot] -PrivateKey = $($ClientKeys.PrivateKey) -PublicKey = $($ClientKeys.PublicKey) -Node = local2 -ServerHost = $ServerHost -ServerPort = $Server2Port -ServerPublicKey = $($Server2Keys.PublicKey) -"@ - Set-Content -Path (Join-Path $Output "client2.ini") -Value $Client2Config -Encoding Ascii - - # Read by ClientExample.exe. - $ClientConfig = @" -[BakaShrot] -PrivateKey = $($ClientKeys.PrivateKey) -PublicKey = $($ClientKeys.PublicKey) -Node = local -ServerHost = $ServerHost -ServerPort = $ServerPort -ServerPublicKey = $($ServerKeys.PublicKey) -"@ - Set-Content -Path (Join-Path $Output "client.ini") -Value $ClientConfig -Encoding Ascii - - Write-Host "Wrote Build\server.ini, Build\server2.ini, Build\client.ini and Build\client2.ini" - - # 4. Run, from ./Build so ./test.sqlite ends up there too. - Write-Host "Start the second server in another terminal to see them link:" - Write-Host " cd Build; .\BakaShrot_Server.exe server2.ini" - Push-Location $Output - try { - & ".\BakaShrot_Server.exe" "server.ini" - } - finally { - Pop-Location - } -} -finally { - Pop-Location -} diff --git a/CLAUDE.md b/CLAUDE.md index ea671b2..80502f5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,116 +1,45 @@ # BakaShrot - start here -A message store with replication, in PureBasic: servers take JSON (or any) -messages per topic/node from authenticated clients, store them in SQLite, -and replicate them between peers by name. Clients: a DLL, CLI tools, a -Python module. An **internal tool on trusted machines**: correctness and -operations come before security hardening (`Notes.md`, "Threat model"). +A message store with replication: servers take messages per topic/node +from authenticated clients, store them in SQLite, and replicate them +between peers by name. Clients: a C DLL, CLI tools, a Python module. An +**internal tool on trusted machines**. -## Read first +**Rewritten in Rust** (since 2026-11-13): -1. `Notes.md`: "Right now" (what's committed, what's next), where things - stand, "Open items, by importance" (the to-do list), "Testing tips". -2. `Design/`, by topic: `Packets.md` (the protocol, where every file lives, - code conventions), `Attachments.md`, `Cryptography.md`, - `StorageConcurrency.md`, `ReplicationIssues.md`, `Release.md`, - `Suggestions.md`. -3. `git log --oneline` and `git status`: what's committed. Work happens on - branches off `master` (`timestamps-retention` at this writing). +- `revamp.md`: why, what's decided, what's proposed and open, the plan and + its status. Read it first. +- The implementation is the Cargo workspace at the root (`readme.md`: + layout, scripts, conventions; `docs/`: designs, `protocol.md` first, + `known-issues.md` for what's left). +- The old PureBasic implementation was removed on 2026-11-15: it's in git + history, `OldSource/` up to commit `68966a8`. Paths starting with + `OldSource/` in the code and docs point there. -## Build +## Toolchain -- Dev compiler, PureBasic 5.73: `C:\Program Files\PureBasic_573\Compilers\pbcompiler.exe /EXE [flags]`. - Release compiler, 6.40 C backend: `C:\Program Files\PureBasic_640\Compilers\pbcompilerc.exe /OUTPUT /OPTIMIZER`. - Code must compile with both (`Release.ps1` checks the 6.40 side). -- `Build.ps1` builds everything into `Build\`, **regenerates keys and - configs, then runs a server waiting on its console**: don't run it from - an automated shell. To rebuild after a change, compile what changed: - -| Source | Output | Flags | -|---|---|---| -| `Server\BakaShrot_Server.pb` | `Build\BakaShrot_Server.exe` | `/CONSOLE /THREAD` | -| `Client\BakaShrot_Client.pbi` | `Build\BakaShrot_Client.dll` | `/DLL /THREAD` | -| `Tools\\.pb` (BakaShrot + PushMessage, GetLatestMessage, GetMessages, GetAttachment, Query, ResolveIds, List, GenerateKeyPairs) | `Build\.exe` | `/CONSOLE` | -| `Client\BakaShrot_Client_Prototypes.pbi` | `Build\ClientExample.exe` | `/CONSOLE` | -| `Tests\Bench\BenchServer.pb` (the server with a stop file, used by every test) | `Build\Bench\BenchServer.exe` | `/CONSOLE /THREAD` | -| `Tests\Bench\BenchClient.pb`, `BenchSeed.pb` | `Build\Bench\` | `/CONSOLE /THREAD` | -| `Tests\HandshakeTest.pb`, `Tests\CipherTest.pb` | `Build\` | `/CONSOLE` | -| `Tests\AttachmentEdgeClient.pb` | `Build\AttachmentEdgeClient.exe` | `/CONSOLE /THREAD` | - -- `Release.ps1 [-Force]` builds the release with 6.40 into `Release\` and - smoke-tests it (`-Force` replaces an existing folder of the same name). -- Linux: same sources and flags (`-t`, `-e`, `-so` for the DLL), with - `libsodium-dev`. `Docker/Server/` builds the server image, on the - PureBasic image `git.nibblepoker.lu/packages/purebasic` (6.41, linux3; - needs a `docker login`), see its Dockerfile. - -## Test - -Each suite starts its own servers (`BenchServer.exe`) on fixed ports, in a -fresh folder under `Build\`, and prints PASS/FAIL lines; exit code 0 means -all passed. `powershell -ExecutionPolicy Bypass -File Tests\.ps1`: - -| Suite | Ports | Covers | -|---|---|---| -| `Names-Test.ps1` | 12401-12402 | names/ids, filters, wildcards, replication by name | -| `BigMessages-Test.ps1` | 12403-12404 | 16 MB messages, handshake frame limit, `is_json`, query errors | -| `GetMessages-Test.ps1` | 12405 | runs of messages, `--follow` | -| `Python-Test.ps1` | 12406-12407 | `bakashrot.py` (`check_bakashrot.py`), the wire is encrypted (`wire_check.py`) | -| `Retention-Test.ps1` | 12408-12409 | `pushed_at`, retention, schema upgrade (Python) | -| `Attachments-Test.ps1` | 12410-12411 | attachments through the tools, replication, limits | -| `AttachmentEdges-Test.ps1` | 12413-12414 | raw-protocol edge cases, expiry, resuming, corruption (Python) | -| `Restart-Test.ps1` | 12415-12416 | servers killed mid-traffic and mid-catch-up: nothing acknowledged lost, ids carry on, both catch up (Python pushers) | - -Plus `Build\HandshakeTest.exe` and `Build\CipherTest.exe` (no server), and -the release's smoke test. Speed: `Tests\Bench\Bench-Replication.ps1 -Ramp 10x0 -Parts Ramp` -(push ceiling for 4 servers: ~17,000 msg/s with the default `Synchronous = -FULL`, ~34,000-40,000 with `-Synchronous NORMAL`). After a change, run every -suite: they take a few minutes in all. - -## Traps - -- **Run exes from `Build\`**: the antivirus blocks them in temp folders. -- **`Build\` holds private keys**: git-ignored, never publish it. The one - exception: `Examples/*/` commit their configs, keys included, on purpose - (public, example-only, marked so); don't copy those keys anywhere else. -- **PureBasic is single pass**: constants, structures and procedures must - be declared before use, so include order matters (e.g. `Config.pbi` - includes `Packets.pbi` for its constants). -- **`SetDatabase*()` binds the next statement run on that connection**, not - a specific one: set them right before their `DatabaseUpdate/Query`. -- **Never `Goto` out of a `Select`**: 5.73's ASM backend keeps the value on - the stack, the jump corrupts it (a config error crashed the server with - 0xC0000005). Set the error, leave the `Select`, then jump. Out of - `For`/`ForEach`/`While` loops is fine (checked on both compilers). -- **PureBasic lists aren't safe to walk from several threads** (`ForEach` - moves the shared current element): give each thread its own copy. -- **Files mix CRLF and LF**: edits must keep each file's line endings. -- **PowerShell 5**: JSON passed as an argument loses its double quotes - (tests write it to a file, `@file`), and `@()` can't be passed through - `-File`. -- **Bash tool heredocs collapse `\\`**, and PureBasic uses `\` for fields: - write edit scripts to files, or use the Edit tool. -- **The real server needs a console on Windows** (it stops at once without - input): tests use `BenchServer.exe` and its stop file instead. On Linux - it runs on without one, SIGTERM/SIGINT stop it. +- Rust via rustup, in `%USERPROFILE%\.cargo\bin`, which **isn't on every + shell's PATH**: prepend it (`export PATH="$HOME/.cargo/bin:$PATH"` in + bash; the `.ps1` scripts and `release.py` do it themselves). The toolchain is pinned + (`rust-toolchain.toml`, 1.100.0, MSVC; Visual Studio 18 has the + linker). +- `test.ps1` runs what CI runs; it must pass before a step is done + (`build.ps1`, `release.ps1`, `clean.ps1` beside it, see `readme.md`). + Run them by absolute path (`-File \test.ps1`): a relative one + fails when the shell's folder differs. ## Working rules -- **Commit only when the owner asks**, on a branch, not `master`. -- **Wire changes bump `#BakaShrot_ProtocolVersion`** (`Packets.pbi`, 6 at - this writing); any difference refuses the connection. -- **Schema changes** add a `Server/Storage/db_schema_vN.dbml` (v8 at this - writing) and a migration in `SetupStorageDatabase()` (`Storage.pbi`), - existing databases must keep working. -- **Packets** follow `Design/Packets.md` "Code conventions": one file per - packet in `Commons/Networking/Packets/`, `_Encode` / `_Decode` (and - `_Free` when it holds data), every field validated on decode. -- **Every write goes through the writer** (`Server/Storage/Writer.pbi`, - under its mutex); reads use the thread's own connection. -- **Every `.pb`/`.pbi` starts with a code header** (`;{- Code Header`, - like PB-MessagePack's): name, version (0.0.1 at this writing), tested - compilers. A release bumps the version in all of them; only list a - compiler/platform once every suite passed with it. -- **Docs follow the code**: a finished piece gets a "Done: ... (date)" - section in `Notes.md`, what's left goes to its open items, and the - `Design/` doc of that area is updated with it. +- **Commit only when the owner asks**, on a branch (`revamp`), not `master`. +- **Follow the plan's order** (`revamp.md`, "Plan"); a step is done when its + tests pass and its docs are updated, then its status goes in the table. +- **Decisions go in `revamp.md`**: moved to "Decided" only when the owner + decides, with the date. +- **Use existing crates** rather than reimplementing (MessagePack is `rmp-serde`). +- **Line endings:** LF everywhere, `.ps1` CRLF (`.gitattributes`); edits + must keep them. +- **Bash tool heredocs collapse `\\`:** write edit scripts to files, or use + the Edit tool. +- **Run exes from a build folder** (`target\`): + the antivirus blocks them in temp folders. +- **Generated keys and certificates never go in git** (`target/`). diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..39c7a06 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,1424 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "asn1-rs" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f43a50ac4fdca5df8e885c21b835997f0a1cdee65494a6847694a98652d9d8" +dependencies = [ + "asn1-rs-derive", + "asn1-rs-impl", + "displaydoc", + "nom", + "num-traits", + "rusticata-macros", + "thiserror", + "time", +] + +[[package]] +name = "asn1-rs-derive" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure", +] + +[[package]] +name = "asn1-rs-impl" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "aws-lc-rs" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "048006790404103c488e6c5616b3e7e702a71292aadda08e8f7698a9e0d2eb53" +dependencies = [ + "aws-lc-sys", + "untrusted 0.7.1", + "zeroize", +] + +[[package]] +name = "aws-lc-sys" +version = "0.47.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8bfbe32ac36b3c428696ce315464181bc4029d689fd58e3f2a4e58c252242f52" +dependencies = [ + "cc", + "cmake", + "dunce", + "fs_extra", + "pkg-config", +] + +[[package]] +name = "bakashrot-capi" +version = "0.2.0" +dependencies = [ + "bakashrot-client", + "bakashrot-config", + "bakashrot-pki", + "bakashrot-proto", + "bakashrot-server", + "cbindgen", + "serde_json", + "tokio", +] + +[[package]] +name = "bakashrot-client" +version = "0.2.0" +dependencies = [ + "aws-lc-rs", + "bakashrot-pki", + "bakashrot-proto", + "rustls", +] + +[[package]] +name = "bakashrot-config" +version = "0.2.0" +dependencies = [ + "bakashrot-proto", + "indexmap", + "serde", + "toml 1.2.1+spec-1.1.0", +] + +[[package]] +name = "bakashrot-pki" +version = "0.2.0" +dependencies = [ + "bakashrot-proto", + "rcgen", + "rustls", + "time", + "x509-parser", + "yasna", +] + +[[package]] +name = "bakashrot-proto" +version = "0.2.0" +dependencies = [ + "bytes", + "rmp-serde", + "serde", + "serde_bytes", + "tokio-util", +] + +[[package]] +name = "bakashrot-server" +version = "0.2.0" +dependencies = [ + "aws-lc-rs", + "bakashrot-client", + "bakashrot-config", + "bakashrot-pki", + "bakashrot-proto", + "bakashrot-storage", + "bytes", + "futures-util", + "rusqlite", + "tokio", + "tokio-rustls", + "tokio-util", + "tracing", + "tracing-subscriber", +] + +[[package]] +name = "bakashrot-storage" +version = "0.2.0" +dependencies = [ + "bakashrot-config", + "bakashrot-proto", + "rusqlite", + "serde_json", +] + +[[package]] +name = "bakashrot-tools" +version = "0.2.0" +dependencies = [ + "bakashrot-client", + "bakashrot-config", + "bakashrot-pki", + "bakashrot-proto", + "bakashrot-server", + "clap", + "serde", + "serde_json", + "time", + "tokio", + "toml 1.2.1+spec-1.1.0", +] + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bit-vec" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" +dependencies = [ + "serde", +] + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cbindgen" +version = "0.29.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ecb53484c9c167ba674026b656d8a27d7657a58e6066aa902bfb1a4aa00ae20" +dependencies = [ + "heck", + "indexmap", + "log", + "proc-macro2", + "quote", + "serde", + "serde_json", + "syn 2.0.119", + "tempfile", + "toml 0.9.12+spec-1.1.0", +] + +[[package]] +name = "cc" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ff2a8126fff0f8c839080d619675a585e61720bb12d2baceae45769fd66f155" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "clap" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "clap_lex" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" + +[[package]] +name = "cmake" +version = "0.1.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" +dependencies = [ + "cc", +] + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + +[[package]] +name = "der-parser" +version = "10.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6" +dependencies = [ + "asn1-rs", + "displaydoc", + "nom", + "num-bigint", + "num-traits", + "rusticata-macros", +] + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-sink", + "futures-task", + "pin-project-lite", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hashlink" +version = "0.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a596f1b20ed2cc5ecac41a164aaebc7258057060f06c0cf7a2ba3991ee7990fb" +dependencies = [ + "hashbrown", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", + "serde", + "serde_core", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libsqlite3-sys" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b06e69070b7e12262b0cd90832f0a7396f142a2b330181255562decf9f0c6215" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "oid-registry" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7" +dependencies = [ + "asn1-rs", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "pem" +version = "4.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d354a98a3d1251555de99e8fdd8afda05573c31b82f59063a7b0a29b5527f120" +dependencies = [ + "base64", + "serde_core", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rcgen" +version = "0.14.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8774e05a7d0de114588e6a28fe7e71694b82614ed569d86d8b389dfbc98b8ad8" +dependencies = [ + "aws-lc-rs", + "pem", + "rustls-pki-types", + "time", + "x509-parser", + "yasna", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted 0.9.0", + "windows-sys 0.52.0", +] + +[[package]] +name = "rmp" +version = "0.8.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ba8be72d372b2c9b35542551678538b562e7cf86c3315773cae48dfbfe7790c" +dependencies = [ + "num-traits", +] + +[[package]] +name = "rmp-serde" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f81bee8c8ef9b577d1681a70ebbc962c232461e397b22c208c43c04b67a155" +dependencies = [ + "rmp", + "serde", +] + +[[package]] +name = "rsqlite-vfs" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "353b74f9810d5b085b6c42c9d86a5f0fdb795553235cdd48753b32e3809d18a7" +dependencies = [ + "thiserror", +] + +[[package]] +name = "rusqlite" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4edff0039f148731aee2fd80f76dbfeb12d204ab3d1c544838d34e02151049b" +dependencies = [ + "bitflags", + "fallible-iterator", + "fallible-streaming-iterator", + "hashlink", + "libsqlite3-sys", + "smallvec", + "sqlite-wasm-rs", +] + +[[package]] +name = "rusticata-macros" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632" +dependencies = [ + "nom", +] + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "aws-lc-rs", + "once_cell", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "aws-lc-rs", + "ring", + "rustls-pki-types", + "untrusted 0.9.0", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_bytes" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8" +dependencies = [ + "serde", + "serde_core", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_spanned" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782" +dependencies = [ + "serde_core", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "smallvec" +version = "1.16.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "sqlite-wasm-rs" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cd504cecbfe7eef649988840f9a6cb768d11085efec138f8e99f160632d867" +dependencies = [ + "cc", + "rsqlite-vfs", +] + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "toml" +version = "0.9.12+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime 0.7.5+spec-1.1.0", + "toml_parser", + "toml_writer", + "winnow 0.7.15", +] + +[[package]] +name = "toml" +version = "1.2.1+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime 1.1.3+spec-1.1.0", + "toml_parser", + "toml_writer", + "winnow 1.0.5", +] + +[[package]] +name = "toml_datetime" +version = "0.7.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_datetime" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow 1.0.5", +] + +[[package]] +name = "toml_writer" +version = "1.2.0+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "nu-ansi-term", + "sharded-slab", + "thread_local", + "tracing-core", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "untrusted" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" + +[[package]] +name = "winnow" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" + +[[package]] +name = "x509-parser" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202" +dependencies = [ + "asn1-rs", + "aws-lc-rs", + "data-encoding", + "der-parser", + "lazy_static", + "nom", + "oid-registry", + "rusticata-macros", + "thiserror", + "time", +] + +[[package]] +name = "yasna" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5f6765e852b9b4dc8e2a76843e4d64d1cea8e79bcde0b6901aea8e7c7f08282" +dependencies = [ + "bit-vec", + "time", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..d9d045f --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,38 @@ +# The BakaShrot workspace: every crate is in crates/, see readme.md for the +# layout and revamp.md for the plan. + +[workspace] +resolver = "3" +members = ["crates/*"] + +[workspace.package] +version = "0.2.0" +edition = "2024" +rust-version = "1.100" +license = "CC0-1.0" +authors = ["Herwin Bozet (NibblePoker)"] +repository = "https://github.com/aziascreations/BakaShrot" +publish = false + +# Every crate takes these with `[lints] workspace = true`. `unsafe_code` is +# "deny", not "forbid", so the C API crate can allow it at its root. +[workspace.lints.rust] +unsafe_code = "deny" +missing_docs = "warn" + +[workspace.lints.clippy] +all = { level = "warn", priority = -1 } + +[profile.release] +# Optimized for size: 25-31% smaller programs and DLL (the server 6.6 MB +# to 4.7 MB), about 5% fewer pushes with `normal` (none with `full`, the +# disk's), the same handshakes and attachments. Measured 2026-11-14; +# "z" is barely smaller, the C (aws-lc, SQLite) kept at 3 adds 1.2 MB for +# nothing measurable. +opt-level = "s" +lto = true +codegen-units = 1 +strip = true +# Kept on purpose: the C DLL catches panics at every export (catch_unwind), +# which "abort" would make impossible. +panic = "unwind" diff --git a/Client/BakaShrot_Client.pbi b/Client/BakaShrot_Client.pbi deleted file mode 100644 index d666be4..0000000 --- a/Client/BakaShrot_Client.pbi +++ /dev/null @@ -1,1627 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: BakaShrot_Client.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; BakaShrot Client DLL -; -; Lets an app connect to a BakaShrot server, one step at a time: -; 1. BakaShrot_SetPrivateKey(), BakaShrot_SetPublicKey(), -; BakaShrot_SetServerPublicKey() (the server's, from its log or its -; BakaShrotGenerateKeyPairs output), and BakaShrot_SetNode() (a name -; or an id) or BakaShrot_SetNodeId(): the node it writes as, which the -; server must allow for its key. Its default topic is the server's to -; say (DefaultTopic in its client section). -; 2. BakaShrot_Connect(Host, Port), connects and authenticates, see the -; handshake in Commons/Networking/Connections.pbi: only to the server -; holding the private key of BakaShrot_SetServerPublicKey()'s, and -; everything is encrypted -; 3. Requests, once connected: -; BakaShrot_PushMessage(JsonData), into the client's default topic, or -; BakaShrot_PushMessageTo(Topic, JsonData), returns the new -; message's id -; BakaShrot_GetLatestMessageOf(Topic, Node), or -; BakaShrot_GetLatestMessage(TopicId, NodeId), then -; BakaShrot_GetMessageId(), BakaShrot_GetMessageData(), -; BakaShrot_GetMessagePushedAt() (ms since 1970 UTC), -; BakaShrot_GetMessageAttachmentSize() (0 for none) and -; BakaShrot_IsMessageAttachmentReady(), -; BakaShrot_GetMessageTopic() / BakaShrot_GetMessageNode() (names) -; and BakaShrot_GetMessageTopicId() / BakaShrot_GetMessageNodeId() -; BakaShrot_GetMessages(Topic, Node, AfterMessageId, Limit): the -; messages after an id, returns how many came, then -; BakaShrot_SelectMessage(Index) (0 is selected already) and the -; same getters for each, BakaShrot_HasMoreMessages() if more -; follow the last one -; BakaShrot_ResolveTopic(Ref), BakaShrot_ResolveNode(Ref): the -; server's id for a name (or the other way), then -; BakaShrot_GetResolvedName() -; BakaShrot_ListTopics(), BakaShrot_ListNodes(): every one with its -; id and name, then BakaShrot_GetNamesList() as JSON -; BakaShrot_Query(Sql), raw read-only SQL, then -; BakaShrot_GetQueryResult() -; Attachments, one per message at most (Design/Attachments.md): -; BakaShrot_PushMessageWithFile(Topic, JsonData, FilePath) or -; BakaShrot_PushMessageWithData(Topic, JsonData, *Data, Size): the -; attachment is uploaded first, the message stored once it all is -; BakaShrot_SaveAttachment(Topic, Node, MessageId, FilePath), or -; BakaShrot_LoadAttachment(Topic, Node, MessageId) then -; BakaShrot_GetAttachmentData(*Buffer, Size): checked with its SHA-256 -; If the server refuses a request, the connection stays open and -; BakaShrot_GetRefusalReason() tells why. -; 4. BakaShrot_IsConnected(), BakaShrot_Disconnect() -; -; After a failed call, BakaShrot_GetLastError() tells what failed: a -; refusal's code (1-99, the connection still open), or the client's own -; (100+: not connected, the connection lost, a bad argument...), see -; BakaShrot_ErrorCodes.pbi for each and what to do about it. 0 after a call -; that succeeded. Nothing reconnects by itself: on NotConnected, -; ConnectionLost or ProtocolError, call BakaShrot_Connect() again. -; A push whose answer was lost (ConnectionLost) may have been stored all -; the same: pushed again, it's stored twice. Delivery is at least once. -; -; Topics and nodes are "refs": a name, or an id in digits, see -; Commons/Networking/Names.pbi. Ids are the server's own, each server can -; have different ones for the same names. -; -; The DLL holds a single connection. -; Every function returns #True (1) on success, #False (0) on failure, unless -; said otherwise. -; -; String getters copy into a caller-provided buffer of BufferSize bytes, and -; return the size in bytes needed for it, terminator included. Call them -; with a null *Buffer to get that size first. Nothing is copied if it -; doesn't fit. -; -; Functions taking strings come in two exported variants, like the Win32 API: -; A takes a null-terminated UTF-8 string (plain ASCII works too). -; W takes a null-terminated UTF-16 string (wchar_t* on Windows). -; Both only receive a pointer and read it with PeekS(), so apps built with -; any compiler or PureBasic version can call them. -; -; Apps should include BakaShrot_Client_Prototypes.pbi instead of this file. -; Compile as a shared DLL. -; ============================================================================ - -EnableExplicit - -XIncludeFile "../Commons/Networking/Outbound.pbi" - - -Structure BakaShrot_ClientPrivateKey - Bytes.a[#BakaShrot_Ed25519_PrivateKeySize] -EndStructure - - -Structure BakaShrot_ClientServerKey - Bytes.a[#BakaShrot_Ed25519_PublicKeySize] -EndStructure - - -Global BakaShrot_PrivateKey.BakaShrot_ClientPrivateKey -Global BakaShrot_HasPrivateKey.i = #False -Global BakaShrot_PublicKey.s = "" -Global BakaShrot_ServerPublicKey.BakaShrot_ClientServerKey -Global BakaShrot_HasServerPublicKey.i = #False -Global BakaShrot_Node.s = "" - -; The connection, see Commons/Networking/Outbound.pbi. -Global BakaShrot_Outbound.BakaShrot_Outbound - -; Filled by the requests, see BakaShrot_GetLatestMessage() and BakaShrot_GetRefusalReasonA/W(). -Global BakaShrot_MessageId.q = 0 -Global BakaShrot_MessagePushedAt.q = 0 -Global BakaShrot_MessageAttachmentSize.q = 0 -Global BakaShrot_MessageAttachmentReady.i = #False -Global BakaShrot_MessageData.s = "" -Global BakaShrot_MessageTopicId.l = -1 -Global BakaShrot_MessageNodeId.l = -1 -Global BakaShrot_MessageTopic.s = "" -Global BakaShrot_MessageNode.s = "" -Global BakaShrot_RefusalReason.s = "" -Global BakaShrot_QueryResult.s = "" -Global BakaShrot_ResolvedName.s = "" -Global BakaShrot_NamesList.s = "" - -; Every message of the last answer, BakaShrot_GetMessages() or -; BakaShrot_GetLatestMessage(). The BakaShrot_Message* globals above are the -; selected one, see BakaShrot_SelectMessage(). -Global NewList BakaShrot_Messages.BakaShrot_MessagesEntry() -Global BakaShrot_MessagesMore.i = #False - -; Why the last call failed, a code of BakaShrot_ErrorCodes.pbi, 0 if it -; succeeded. See BakaShrot_GetLastError(). -Global BakaShrot_LastError.l = #BakaShrot_Error_None - - -; Sets BakaShrot_LastError to Code and returns Value, for the failures: -; ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False). -Procedure.q BakaShrot_Fail(Code.l, Value.q) - BakaShrot_LastError = Code - ProcedureReturn Value -EndProcedure - -; At the start of every call that can fail: no error, no refusal yet. -Procedure BakaShrot_ResetError() - BakaShrot_LastError = #BakaShrot_Error_None - BakaShrot_RefusalReason = "" -EndProcedure - -; The code of what made the last call fail, 0 if it succeeded, see -; BakaShrot_ErrorCodes.pbi. Only the calls that can fail set it (not the -; getters of a message). -ProcedureCDLL.l BakaShrot_GetLastError() - ProcedureReturn BakaShrot_LastError -EndProcedure - - -; Sets the Ed25519 private key (Base64) used to answer the server's challenge. -; Must be done before connecting. -Procedure.i BakaShrot_SetPrivateKeyString(PrivateKey.s) - BakaShrot_ResetError() - If BakaShrot_Outbound\ConnectionId - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_AlreadyConnected, #False) - EndIf - - If Not DecodeKeyFromString(PrivateKey, @BakaShrot_PrivateKey\Bytes[0], #BakaShrot_Ed25519_PrivateKeySize) - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) - EndIf - - BakaShrot_HasPrivateKey = #True - ProcedureReturn #True -EndProcedure - -ProcedureCDLL.i BakaShrot_SetPrivateKeyA(*PrivateKey) - If Not *PrivateKey - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) - EndIf - ProcedureReturn BakaShrot_SetPrivateKeyString(PeekS(*PrivateKey, -1, #PB_UTF8)) -EndProcedure - -ProcedureCDLL.i BakaShrot_SetPrivateKeyW(*PrivateKey) - If Not *PrivateKey - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) - EndIf - ProcedureReturn BakaShrot_SetPrivateKeyString(PeekS(*PrivateKey, -1, #PB_Unicode)) -EndProcedure - - -; Sets the Ed25519 public key (Base64) sent to the server in the Hello. -; Must be done before connecting. -Procedure.i BakaShrot_SetPublicKeyString(PublicKey.s) - BakaShrot_ResetError() - If BakaShrot_Outbound\ConnectionId - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_AlreadyConnected, #False) - EndIf - - If PublicKey = "" - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) - EndIf - - BakaShrot_PublicKey = PublicKey - ProcedureReturn #True -EndProcedure - -ProcedureCDLL.i BakaShrot_SetPublicKeyA(*PublicKey) - If Not *PublicKey - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) - EndIf - ProcedureReturn BakaShrot_SetPublicKeyString(PeekS(*PublicKey, -1, #PB_UTF8)) -EndProcedure - -ProcedureCDLL.i BakaShrot_SetPublicKeyW(*PublicKey) - If Not *PublicKey - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) - EndIf - ProcedureReturn BakaShrot_SetPublicKeyString(PeekS(*PublicKey, -1, #PB_Unicode)) -EndProcedure - - -; Sets the server's Ed25519 public key (Base64): the Hello is sealed for it, -; and the server must prove it holds the matching private key. -; Must be done before connecting. -Procedure.i BakaShrot_SetServerPublicKeyString(PublicKey.s) - BakaShrot_ResetError() - If BakaShrot_Outbound\ConnectionId - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_AlreadyConnected, #False) - EndIf - - If Not DecodeKeyFromString(PublicKey, @BakaShrot_ServerPublicKey\Bytes[0], #BakaShrot_Ed25519_PublicKeySize) - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) - EndIf - - BakaShrot_HasServerPublicKey = #True - ProcedureReturn #True -EndProcedure - -ProcedureCDLL.i BakaShrot_SetServerPublicKeyA(*PublicKey) - If Not *PublicKey - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) - EndIf - ProcedureReturn BakaShrot_SetServerPublicKeyString(PeekS(*PublicKey, -1, #PB_UTF8)) -EndProcedure - -ProcedureCDLL.i BakaShrot_SetServerPublicKeyW(*PublicKey) - If Not *PublicKey - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) - EndIf - ProcedureReturn BakaShrot_SetServerPublicKeyString(PeekS(*PublicKey, -1, #PB_Unicode)) -EndProcedure - - -; Sets the node the client identifies as, a name or an id in digits. -; Must be done before connecting. -Procedure.i BakaShrot_SetNodeString(Node.s) - BakaShrot_ResetError() - If BakaShrot_Outbound\ConnectionId - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_AlreadyConnected, #False) - EndIf - If Not BakaShrot_IsValidRef(Node) - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) - EndIf - BakaShrot_Node = Node - ProcedureReturn #True -EndProcedure - -ProcedureCDLL.i BakaShrot_SetNodeA(*Node) - If Not *Node - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) - EndIf - ProcedureReturn BakaShrot_SetNodeString(PeekS(*Node, -1, #PB_UTF8)) -EndProcedure - -ProcedureCDLL.i BakaShrot_SetNodeW(*Node) - If Not *Node - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) - EndIf - ProcedureReturn BakaShrot_SetNodeString(PeekS(*Node, -1, #PB_Unicode)) -EndProcedure - -; Same, by id, 0-65535. -ProcedureCDLL.i BakaShrot_SetNodeId(NodeId.l) - If NodeId < 0 Or NodeId > 65535 - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) - EndIf - ProcedureReturn BakaShrot_SetNodeString(Str(NodeId)) -EndProcedure - - -; Connects to Host:Port and authenticates with the settings above, see -; BakaShrot_Outbound_Connect() in Commons/Networking/Outbound.pbi. -; Fails if already connected, if a setting is missing, or if anything in the -; handshake is out of order or unexpected, in which case the connection is -; closed. -Procedure.i BakaShrot_ConnectString(Host.s, Port.l) - Protected Identity.BakaShrot_OutboundIdentity, Connected.i - - BakaShrot_ResetError() - If BakaShrot_Outbound\ConnectionId - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_AlreadyConnected, #False) - EndIf - - If Not BakaShrot_HasPrivateKey Or BakaShrot_PublicKey = "" Or Not BakaShrot_HasServerPublicKey Or BakaShrot_Node = "" - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) - EndIf - - Identity\Node = BakaShrot_Node - Identity\PublicKey = BakaShrot_PublicKey - Identity\PrivateKey = @BakaShrot_PrivateKey\Bytes[0] - - Connected = BakaShrot_Outbound_Connect(@BakaShrot_Outbound, Host, Port, @Identity, @BakaShrot_ServerPublicKey\Bytes[0]) - BakaShrot_LastError = BakaShrot_Outbound\LastError - ProcedureReturn Connected -EndProcedure - -ProcedureCDLL.i BakaShrot_ConnectA(*Host, Port.l) - If Not *Host - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) - EndIf - ProcedureReturn BakaShrot_ConnectString(PeekS(*Host, -1, #PB_UTF8), Port) -EndProcedure - -ProcedureCDLL.i BakaShrot_ConnectW(*Host, Port.l) - If Not *Host - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) - EndIf - ProcedureReturn BakaShrot_ConnectString(PeekS(*Host, -1, #PB_Unicode), Port) -EndProcedure - - -; Returns #True while the connection is open and authenticated. -; Notices when the server closed it. -ProcedureCDLL.i BakaShrot_IsConnected() - ProcedureReturn BakaShrot_Outbound_IsConnected(@BakaShrot_Outbound) -EndProcedure - - -; Closes the connection, if any. The settings are kept. -ProcedureCDLL.i BakaShrot_Disconnect() - If Not BakaShrot_Outbound\ConnectionId - ProcedureReturn #False - EndIf - - BakaShrot_Outbound_Close(@BakaShrot_Outbound, #BakaShrot_ConnectionStatus_Disconnected) - ProcedureReturn #True -EndProcedure - - -; --- Requests ---------------------------------------------------------------- - -; Closes the connection after something went wrong in a request: an -; unexpected or malformed answer, unless the caller said otherwise first. -Procedure BakaShrot_AbortConnection() - If BakaShrot_LastError = #BakaShrot_Error_None - BakaShrot_LastError = #BakaShrot_Error_ProtocolError - EndIf - BakaShrot_Outbound_Close(@BakaShrot_Outbound, #BakaShrot_ConnectionStatus_Aborted) -EndProcedure - - -; Sends a request and waits for its answer. -; Returns the answer (free it with FreeMemory) with its size in *OutSize\i, -; or 0 if the connection failed, in which case it's closed. -; A refusal is returned like any other answer. -Procedure.i BakaShrot_SendRequest(*Request, RequestSize.i, *OutSize.Integer) - Protected *Answer - - If Not BakaShrot_Outbound_Send(@BakaShrot_Outbound, *Request, RequestSize) - BakaShrot_LastError = #BakaShrot_Error_ConnectionLost - BakaShrot_AbortConnection() - ProcedureReturn 0 - EndIf - - *Answer = BakaShrot_Outbound_WaitPacket(@BakaShrot_Outbound, *OutSize, #BakaShrot_Outbound_Timeout) - If Not *Answer - BakaShrot_LastError = #BakaShrot_Error_ConnectionLost - BakaShrot_AbortConnection() - ProcedureReturn 0 - EndIf - - ProcedureReturn *Answer -EndProcedure - - -; Reads a RequestRefused answer into BakaShrot_RefusalReason. -; Returns #False if it's malformed, the connection must then be aborted. -Procedure.i BakaShrot_ReadRefusal(*Answer, AnswerSize.i) - Protected *View.MsgPackData, *Refused.BakaShrot_RequestRefused - - *Refused = 0 - *View = MsgPackWrapMsgBuffer(*Answer, AnswerSize) - If *View - *Refused = BakaShrot_RequestRefusedPacket_Decode(*View) - MsgPackFree(*View, #False) - EndIf - If Not *Refused - ProcedureReturn #False - EndIf - - BakaShrot_RefusalReason = *Refused\Reason - BakaShrot_LastError = *Refused\Code - FreeStructure(*Refused) - ProcedureReturn #True -EndProcedure - - -; Copies Text into *Buffer as a null-terminated string in Format -; (#PB_UTF8 or #PB_Unicode), if it fits in BufferSize bytes. -; Returns the size in bytes needed for it, terminator included. -Procedure.i BakaShrot_CopyString(Text.s, *Buffer, BufferSize.i, Format.i) - Protected NeededSize.i - - If Format = #PB_UTF8 - NeededSize = StringByteLength(Text, #PB_UTF8) + 1 - Else - NeededSize = StringByteLength(Text, #PB_Unicode) + 2 - EndIf - - If *Buffer And BufferSize >= NeededSize - PokeS(*Buffer, Text, -1, Format) - EndIf - - ProcedureReturn NeededSize -EndProcedure - - -; Pushes a message (JSON or anything else, the server flags which in its -; is_json column) into Topic (a name or an id, "" for the client's default -; topic, its server config's DefaultTopic), the server stores it under that topic and this client's node, with -; the next message id. The client's PushTopics on the server must allow it. -; UploadId: its attachment, uploaded with BakaShrot_Upload(), 0 for none. -; Returns the new message's id (1 or more), or -1 on failure. -; On -1, BakaShrot_IsConnected() tells if the server refused it (still -; connected, see BakaShrot_GetRefusalReason()) or if the connection failed. -Procedure.q BakaShrot_PushMessageToString(Topic.s, JsonData.s, UploadId.q = 0) - Protected Push.BakaShrot_PushMessage - Protected *Pushed.BakaShrot_MessagePushed - Protected *Request, RequestSize.Integer, *Answer, AnswerSize.Integer - Protected *View.MsgPackData, IsRefusal.i, MessageId.q - - BakaShrot_ResetError() - - If Not BakaShrot_Outbound\ConnectionId Or BakaShrot_Outbound\Metadata\Status <> #BakaShrot_ConnectionStatus_Authenticated - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_NotConnected, -1) - EndIf - - If Topic <> "" And Not BakaShrot_IsValidRef(Topic) - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1) - EndIf - - ; Refused here rather than sent for nothing, same reason as the server's. - If StringByteLength(JsonData, #PB_UTF8) > #BakaShrot_MaxMessageSize - BakaShrot_RefusalReason = "The message is too big: " + Str(StringByteLength(JsonData, #PB_UTF8)) + " bytes, at most " + Str(#BakaShrot_MaxMessageSize) - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1) - EndIf - - Push\Topic = Topic - Push\JsonData = JsonData - Push\UploadId = UploadId - *Request = BakaShrot_PushMessagePacket_Encode(@Push, @RequestSize) - If Not *Request - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_Internal, -1) - EndIf - *Answer = BakaShrot_SendRequest(*Request, RequestSize\i, @AnswerSize) - FreeMemory(*Request) - If Not *Answer - ProcedureReturn -1 - EndIf - - If BakaShrot_GetPacketType(*Answer, AnswerSize\i) = #BakaShrot_PacketType_RequestRefused - IsRefusal = BakaShrot_ReadRefusal(*Answer, AnswerSize\i) - FreeMemory(*Answer) - If Not IsRefusal - BakaShrot_AbortConnection() - EndIf - ProcedureReturn -1 - EndIf - - *Pushed = 0 - *View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i) - If *View - *Pushed = BakaShrot_MessagePushedPacket_Decode(*View) - MsgPackFree(*View, #False) - EndIf - FreeMemory(*Answer) - If Not *Pushed - BakaShrot_AbortConnection() - ProcedureReturn -1 - EndIf - - MessageId = *Pushed\MessageId - FreeStructure(*Pushed) - ProcedureReturn MessageId -EndProcedure - -; A null *JsonData is an empty message (stored, is_json = 0): PureBasic -; passes empty strings to a DLL as null pointers. -ProcedureCDLL.q BakaShrot_PushMessageA(*JsonData) - If Not *JsonData - ProcedureReturn BakaShrot_PushMessageToString("", "") - EndIf - ProcedureReturn BakaShrot_PushMessageToString("", PeekS(*JsonData, -1, #PB_UTF8)) -EndProcedure - -ProcedureCDLL.q BakaShrot_PushMessageW(*JsonData) - If Not *JsonData - ProcedureReturn BakaShrot_PushMessageToString("", "") - EndIf - ProcedureReturn BakaShrot_PushMessageToString("", PeekS(*JsonData, -1, #PB_Unicode)) -EndProcedure - -; A null *Topic is the client's default topic, like "", and a null *JsonData an -; empty message: PureBasic passes empty strings to a DLL as null pointers. -ProcedureCDLL.q BakaShrot_PushMessageToA(*Topic, *JsonData) - Protected Topic.s, JsonData.s - If *Topic - Topic = PeekS(*Topic, -1, #PB_UTF8) - EndIf - If *JsonData - JsonData = PeekS(*JsonData, -1, #PB_UTF8) - EndIf - ProcedureReturn BakaShrot_PushMessageToString(Topic, JsonData) -EndProcedure - -ProcedureCDLL.q BakaShrot_PushMessageToW(*Topic, *JsonData) - Protected Topic.s, JsonData.s - If *Topic - Topic = PeekS(*Topic, -1, #PB_Unicode) - EndIf - If *JsonData - JsonData = PeekS(*JsonData, -1, #PB_Unicode) - EndIf - ProcedureReturn BakaShrot_PushMessageToString(Topic, JsonData) -EndProcedure - - -; Asks for the latest message of a topic/node, each a name or an id. The -; server refuses if the client's ReadTopics don't allow the topic, if -; either is unknown, or if there's no message. -; On success, read it with BakaShrot_GetMessageId(), BakaShrot_GetMessageData(), -; BakaShrot_GetMessageTopic/Node() and BakaShrot_GetMessageTopicId/NodeId(). -; On failure, BakaShrot_IsConnected() tells if it was refused (see -; BakaShrot_GetRefusalReason()) or if the connection failed. -Procedure.i BakaShrot_GetLatestMessageOfString(Topic.s, Node.s) - Protected Request.BakaShrot_GetLatestMessage - Protected *Latest.BakaShrot_LatestMessage - Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer - Protected *View.MsgPackData, IsRefusal.i, IsExpected.i - - BakaShrot_ResetError() - BakaShrot_MessageId = 0 - BakaShrot_MessagePushedAt = 0 - BakaShrot_MessageAttachmentSize = 0 - BakaShrot_MessageAttachmentReady = #False - BakaShrot_MessageData = "" - BakaShrot_MessageTopicId = -1 - BakaShrot_MessageNodeId = -1 - BakaShrot_MessageTopic = "" - BakaShrot_MessageNode = "" - ClearList(BakaShrot_Messages()) - BakaShrot_MessagesMore = #False - - If Not BakaShrot_Outbound\ConnectionId Or BakaShrot_Outbound\Metadata\Status <> #BakaShrot_ConnectionStatus_Authenticated - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_NotConnected, #False) - EndIf - - If Not BakaShrot_IsValidRef(Topic) Or Not BakaShrot_IsValidRef(Node) - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) - EndIf - - Request\Topic = Topic - Request\Node = Node - *Packet = BakaShrot_GetLatestMessagePacket_Encode(@Request, @PacketSize) - If Not *Packet - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_Internal, #False) - EndIf - *Answer = BakaShrot_SendRequest(*Packet, PacketSize\i, @AnswerSize) - FreeMemory(*Packet) - If Not *Answer - ProcedureReturn #False - EndIf - - If BakaShrot_GetPacketType(*Answer, AnswerSize\i) = #BakaShrot_PacketType_RequestRefused - IsRefusal = BakaShrot_ReadRefusal(*Answer, AnswerSize\i) - FreeMemory(*Answer) - If Not IsRefusal - BakaShrot_AbortConnection() - EndIf - ProcedureReturn #False - EndIf - - *Latest = 0 - *View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i) - If *View - *Latest = BakaShrot_LatestMessagePacket_Decode(*View) - MsgPackFree(*View, #False) - EndIf - FreeMemory(*Answer) - If Not *Latest - BakaShrot_AbortConnection() - ProcedureReturn #False - EndIf - - ; An answer about another topic/node is out of order. - IsExpected = Bool(BakaShrot_RefMatches(Topic, *Latest\TopicId, *Latest\TopicName) And BakaShrot_RefMatches(Node, *Latest\NodeId, *Latest\NodeName)) - If IsExpected - BakaShrot_MessageId = *Latest\MessageId - BakaShrot_MessagePushedAt = *Latest\PushedAt - BakaShrot_MessageAttachmentSize = *Latest\AttachmentSize - BakaShrot_MessageAttachmentReady = *Latest\AttachmentReady - BakaShrot_MessageData = *Latest\JsonData - BakaShrot_MessageTopicId = *Latest\TopicId - BakaShrot_MessageNodeId = *Latest\NodeId - BakaShrot_MessageTopic = *Latest\TopicName - BakaShrot_MessageNode = *Latest\NodeName - AddElement(BakaShrot_Messages()) - BakaShrot_Messages()\MessageId = *Latest\MessageId - BakaShrot_Messages()\PushedAt = *Latest\PushedAt - BakaShrot_Messages()\AttachmentSize = *Latest\AttachmentSize - BakaShrot_Messages()\AttachmentReady = *Latest\AttachmentReady - BakaShrot_Messages()\JsonData = *Latest\JsonData - EndIf - FreeStructure(*Latest) - If Not IsExpected - BakaShrot_AbortConnection() - ProcedureReturn #False - EndIf - - ProcedureReturn #True -EndProcedure - - -ProcedureCDLL.i BakaShrot_GetLatestMessageOfA(*Topic, *Node) - If Not *Topic Or Not *Node - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) - EndIf - ProcedureReturn BakaShrot_GetLatestMessageOfString(PeekS(*Topic, -1, #PB_UTF8), PeekS(*Node, -1, #PB_UTF8)) -EndProcedure - -ProcedureCDLL.i BakaShrot_GetLatestMessageOfW(*Topic, *Node) - If Not *Topic Or Not *Node - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) - EndIf - ProcedureReturn BakaShrot_GetLatestMessageOfString(PeekS(*Topic, -1, #PB_Unicode), PeekS(*Node, -1, #PB_Unicode)) -EndProcedure - -; Same, by ids, 0-65535. -ProcedureCDLL.i BakaShrot_GetLatestMessage(TopicId.l, NodeId.l) - If TopicId < 0 Or TopicId > 65535 Or NodeId < 0 Or NodeId > 65535 - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) - EndIf - ProcedureReturn BakaShrot_GetLatestMessageOfString(Str(TopicId), Str(NodeId)) -EndProcedure - - -; Asks for the messages of a topic/node (each a name or an id) stored after -; AfterMessageId (0 for the first ones), in message id order: at most Limit -; (1-10000), fewer if they didn't fit in about 1 MB, a bigger one alone. The -; server refuses if the client's ReadTopics don't allow the topic, or if -; either is unknown. No more messages isn't a refusal, it returns 0. -; Returns how many came (0 or more), or -1 on failure: BakaShrot_IsConnected() -; tells if it was refused (see BakaShrot_GetRefusalReason()) or if the -; connection failed. -; On success, the first one is selected: read it with BakaShrot_GetMessageId(), -; BakaShrot_GetMessageData() and the others, select the next ones with -; BakaShrot_SelectMessage(). BakaShrot_GetMessageTopic/Node/TopicId/NodeId() -; are set even if none came. BakaShrot_HasMoreMessages() tells if more -; follow the last one: ask again after its id. -Procedure.l BakaShrot_GetMessagesString(Topic.s, Node.s, AfterMessageId.q, Limit.l) - Protected Request.BakaShrot_GetMessages - Protected *Answer.BakaShrot_Messages - Protected *Packet, PacketSize.Integer, *AnswerPacket, AnswerSize.Integer - Protected *View.MsgPackData, IsRefusal.i, IsExpected.i, Count.l - - BakaShrot_ResetError() - BakaShrot_MessageId = 0 - BakaShrot_MessagePushedAt = 0 - BakaShrot_MessageAttachmentSize = 0 - BakaShrot_MessageAttachmentReady = #False - BakaShrot_MessageData = "" - BakaShrot_MessageTopicId = -1 - BakaShrot_MessageNodeId = -1 - BakaShrot_MessageTopic = "" - BakaShrot_MessageNode = "" - ClearList(BakaShrot_Messages()) - BakaShrot_MessagesMore = #False - - If Not BakaShrot_Outbound\ConnectionId Or BakaShrot_Outbound\Metadata\Status <> #BakaShrot_ConnectionStatus_Authenticated - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_NotConnected, -1) - EndIf - - If Not BakaShrot_IsValidRef(Topic) Or Not BakaShrot_IsValidRef(Node) - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1) - EndIf - If AfterMessageId < 0 Or Limit < 1 Or Limit > #BakaShrot_MaxGetMessages - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1) - EndIf - - Request\Topic = Topic - Request\Node = Node - Request\AfterMessageId = AfterMessageId - Request\Limit = Limit - *Packet = BakaShrot_GetMessagesPacket_Encode(@Request, @PacketSize) - If Not *Packet - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_Internal, -1) - EndIf - *AnswerPacket = BakaShrot_SendRequest(*Packet, PacketSize\i, @AnswerSize) - FreeMemory(*Packet) - If Not *AnswerPacket - ProcedureReturn -1 - EndIf - - If BakaShrot_GetPacketType(*AnswerPacket, AnswerSize\i) = #BakaShrot_PacketType_RequestRefused - IsRefusal = BakaShrot_ReadRefusal(*AnswerPacket, AnswerSize\i) - FreeMemory(*AnswerPacket) - If Not IsRefusal - BakaShrot_AbortConnection() - EndIf - ProcedureReturn -1 - EndIf - - *Answer = 0 - *View = MsgPackWrapMsgBuffer(*AnswerPacket, AnswerSize\i) - If *View - *Answer = BakaShrot_MessagesPacket_Decode(*View) - MsgPackFree(*View, #False) - EndIf - FreeMemory(*AnswerPacket) - If Not *Answer - BakaShrot_AbortConnection() - ProcedureReturn -1 - EndIf - - ; An answer about another topic/node, with more messages than asked for, - ; or with ones that aren't after AfterMessageId, is out of order. - IsExpected = Bool(BakaShrot_RefMatches(Topic, *Answer\TopicId, *Answer\TopicName) And BakaShrot_RefMatches(Node, *Answer\NodeId, *Answer\NodeName)) - If IsExpected And ListSize(*Answer\Messages()) > Limit - IsExpected = #False - EndIf - If IsExpected And FirstElement(*Answer\Messages()) - If *Answer\Messages()\MessageId <= AfterMessageId - IsExpected = #False - EndIf - EndIf - If Not IsExpected - FreeStructure(*Answer) - BakaShrot_AbortConnection() - ProcedureReturn -1 - EndIf - - BakaShrot_MessageTopicId = *Answer\TopicId - BakaShrot_MessageNodeId = *Answer\NodeId - BakaShrot_MessageTopic = *Answer\TopicName - BakaShrot_MessageNode = *Answer\NodeName - BakaShrot_MessagesMore = *Answer\More - CopyList(*Answer\Messages(), BakaShrot_Messages()) - Count = ListSize(BakaShrot_Messages()) - FreeStructure(*Answer) - - If FirstElement(BakaShrot_Messages()) - BakaShrot_MessageId = BakaShrot_Messages()\MessageId - BakaShrot_MessagePushedAt = BakaShrot_Messages()\PushedAt - BakaShrot_MessageAttachmentSize = BakaShrot_Messages()\AttachmentSize - BakaShrot_MessageAttachmentReady = BakaShrot_Messages()\AttachmentReady - BakaShrot_MessageData = BakaShrot_Messages()\JsonData - EndIf - ProcedureReturn Count -EndProcedure - -ProcedureCDLL.l BakaShrot_GetMessagesA(*Topic, *Node, AfterMessageId.q, Limit.l) - If Not *Topic Or Not *Node - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1) - EndIf - ProcedureReturn BakaShrot_GetMessagesString(PeekS(*Topic, -1, #PB_UTF8), PeekS(*Node, -1, #PB_UTF8), AfterMessageId, Limit) -EndProcedure - -ProcedureCDLL.l BakaShrot_GetMessagesW(*Topic, *Node, AfterMessageId.q, Limit.l) - If Not *Topic Or Not *Node - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1) - EndIf - ProcedureReturn BakaShrot_GetMessagesString(PeekS(*Topic, -1, #PB_Unicode), PeekS(*Node, -1, #PB_Unicode), AfterMessageId, Limit) -EndProcedure - -; How many messages the last BakaShrot_GetMessages() or -; BakaShrot_GetLatestMessage() got, 0 if it failed. -ProcedureCDLL.l BakaShrot_GetMessageCount() - ProcedureReturn ListSize(BakaShrot_Messages()) -EndProcedure - -; Selects the message at Index (0 to BakaShrot_GetMessageCount() - 1) of the -; last answer, for BakaShrot_GetMessageId() and BakaShrot_GetMessageData(). -; Returns #False if there's none at Index, the selection doesn't change then. -ProcedureCDLL.i BakaShrot_SelectMessage(Index.l) - BakaShrot_LastError = #BakaShrot_Error_None - If Index < 0 Or Index >= ListSize(BakaShrot_Messages()) - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) - EndIf - SelectElement(BakaShrot_Messages(), Index) - BakaShrot_MessageId = BakaShrot_Messages()\MessageId - BakaShrot_MessagePushedAt = BakaShrot_Messages()\PushedAt - BakaShrot_MessageAttachmentSize = BakaShrot_Messages()\AttachmentSize - BakaShrot_MessageAttachmentReady = BakaShrot_Messages()\AttachmentReady - BakaShrot_MessageData = BakaShrot_Messages()\JsonData - ProcedureReturn #True -EndProcedure - -; #True if more messages follow the last one the last BakaShrot_GetMessages() got. -ProcedureCDLL.i BakaShrot_HasMoreMessages() - ProcedureReturn BakaShrot_MessagesMore -EndProcedure - - -; Id of the selected message of the last successful BakaShrot_GetLatestMessage() -; or BakaShrot_GetMessages(), 0 if none. -ProcedureCDLL.q BakaShrot_GetMessageId() - ProcedureReturn BakaShrot_MessageId -EndProcedure - -; When that message was pushed, to whichever server it was pushed to: in -; milliseconds since 1970-01-01 00:00:00 UTC. 0 if none. -ProcedureCDLL.q BakaShrot_GetMessagePushedAt() - ProcedureReturn BakaShrot_MessagePushedAt -EndProcedure - -; The server's topic and node ids of that message, -1 if none. -ProcedureCDLL.l BakaShrot_GetMessageTopicId() - ProcedureReturn BakaShrot_MessageTopicId -EndProcedure - -ProcedureCDLL.l BakaShrot_GetMessageNodeId() - ProcedureReturn BakaShrot_MessageNodeId -EndProcedure - -; The names of its topic and node, or their ids in digits if they have none. -ProcedureCDLL.i BakaShrot_GetMessageTopicA(*Buffer, BufferSize.i) - ProcedureReturn BakaShrot_CopyString(BakaShrot_MessageTopic, *Buffer, BufferSize, #PB_UTF8) -EndProcedure - -ProcedureCDLL.i BakaShrot_GetMessageTopicW(*Buffer, BufferSize.i) - ProcedureReturn BakaShrot_CopyString(BakaShrot_MessageTopic, *Buffer, BufferSize, #PB_Unicode) -EndProcedure - -ProcedureCDLL.i BakaShrot_GetMessageNodeA(*Buffer, BufferSize.i) - ProcedureReturn BakaShrot_CopyString(BakaShrot_MessageNode, *Buffer, BufferSize, #PB_UTF8) -EndProcedure - -ProcedureCDLL.i BakaShrot_GetMessageNodeW(*Buffer, BufferSize.i) - ProcedureReturn BakaShrot_CopyString(BakaShrot_MessageNode, *Buffer, BufferSize, #PB_Unicode) -EndProcedure - - -; Asks the server for its id and name of a topic or node (Kind, see -; ResolveNamePacket.pbi), Ref being a name or an id. The server only -; resolves the topics this client may push to or read, unless it may query. -; Returns the id (0-65535), or -1 on failure: refused (unknown) or the -; connection failed, see BakaShrot_IsConnected(). -; On success, BakaShrot_GetResolvedName() has its name, "" if it has none. -Procedure.l BakaShrot_ResolveString(Kind.i, Ref.s) - Protected Request.BakaShrot_ResolveName - Protected *Resolved.BakaShrot_NameResolved - Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer - Protected *View.MsgPackData, IsRefusal.i, Id.l - - BakaShrot_ResetError() - BakaShrot_ResolvedName = "" - - If Not BakaShrot_Outbound\ConnectionId Or BakaShrot_Outbound\Metadata\Status <> #BakaShrot_ConnectionStatus_Authenticated - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_NotConnected, -1) - EndIf - - If Not BakaShrot_IsValidRef(Ref) - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1) - EndIf - - Request\Kind = Kind - Request\Ref = Ref - *Packet = BakaShrot_ResolveNamePacket_Encode(@Request, @PacketSize) - If Not *Packet - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_Internal, -1) - EndIf - *Answer = BakaShrot_SendRequest(*Packet, PacketSize\i, @AnswerSize) - FreeMemory(*Packet) - If Not *Answer - ProcedureReturn -1 - EndIf - - If BakaShrot_GetPacketType(*Answer, AnswerSize\i) = #BakaShrot_PacketType_RequestRefused - IsRefusal = BakaShrot_ReadRefusal(*Answer, AnswerSize\i) - FreeMemory(*Answer) - If Not IsRefusal - BakaShrot_AbortConnection() - EndIf - ProcedureReturn -1 - EndIf - - *Resolved = 0 - *View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i) - If *View - *Resolved = BakaShrot_NameResolvedPacket_Decode(*View) - MsgPackFree(*View, #False) - EndIf - FreeMemory(*Answer) - If Not *Resolved - BakaShrot_AbortConnection() - ProcedureReturn -1 - EndIf - - ; An answer about something else is out of order. - If *Resolved\Kind <> Kind Or Not BakaShrot_RefMatches(Ref, *Resolved\Id, *Resolved\Name) - FreeStructure(*Resolved) - BakaShrot_AbortConnection() - ProcedureReturn -1 - EndIf - - Id = *Resolved\Id - BakaShrot_ResolvedName = *Resolved\Name - FreeStructure(*Resolved) - ProcedureReturn Id -EndProcedure - -ProcedureCDLL.l BakaShrot_ResolveTopicA(*Ref) - If Not *Ref - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1) - EndIf - ProcedureReturn BakaShrot_ResolveString(#BakaShrot_NameKind_Topic, PeekS(*Ref, -1, #PB_UTF8)) -EndProcedure - -ProcedureCDLL.l BakaShrot_ResolveTopicW(*Ref) - If Not *Ref - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1) - EndIf - ProcedureReturn BakaShrot_ResolveString(#BakaShrot_NameKind_Topic, PeekS(*Ref, -1, #PB_Unicode)) -EndProcedure - -ProcedureCDLL.l BakaShrot_ResolveNodeA(*Ref) - If Not *Ref - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1) - EndIf - ProcedureReturn BakaShrot_ResolveString(#BakaShrot_NameKind_Node, PeekS(*Ref, -1, #PB_UTF8)) -EndProcedure - -ProcedureCDLL.l BakaShrot_ResolveNodeW(*Ref) - If Not *Ref - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1) - EndIf - ProcedureReturn BakaShrot_ResolveString(#BakaShrot_NameKind_Node, PeekS(*Ref, -1, #PB_Unicode)) -EndProcedure - -; Asks the server for every topic (Kind #BakaShrot_NameKind_Topic, only -; those this client may push to or read, unless it may query) or node, and -; keeps them as JSON for BakaShrot_GetNamesList(): -; {"kind": "topic", "truncated": false, -; "items": [{"id": 1, "name": "logs", "origin": "config"}, ...]} -; by id, "name" "" if unnamed (those don't replicate), "origin" "config" or -; "id". "truncated" is true if they didn't all fit in one packet. -; Returns how many are listed, or -1 on failure (see BakaShrot_IsConnected()). -Procedure.l BakaShrot_ListNamesOf(Kind.i) - Protected Request.BakaShrot_ListNames - Protected *List.BakaShrot_NamesList - Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer - Protected *View.MsgPackData, IsRefusal.i, Count.l - Protected Json.i, Root.i, Items.i, Item.i - - BakaShrot_ResetError() - BakaShrot_NamesList = "" - - If Not BakaShrot_Outbound\ConnectionId Or BakaShrot_Outbound\Metadata\Status <> #BakaShrot_ConnectionStatus_Authenticated - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_NotConnected, -1) - EndIf - - Request\Kind = Kind - *Packet = BakaShrot_ListNamesPacket_Encode(@Request, @PacketSize) - If Not *Packet - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_Internal, -1) - EndIf - *Answer = BakaShrot_SendRequest(*Packet, PacketSize\i, @AnswerSize) - FreeMemory(*Packet) - If Not *Answer - ProcedureReturn -1 - EndIf - - If BakaShrot_GetPacketType(*Answer, AnswerSize\i) = #BakaShrot_PacketType_RequestRefused - IsRefusal = BakaShrot_ReadRefusal(*Answer, AnswerSize\i) - FreeMemory(*Answer) - If Not IsRefusal - BakaShrot_AbortConnection() - EndIf - ProcedureReturn -1 - EndIf - - *List = 0 - *View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i) - If *View - *List = BakaShrot_NamesListPacket_Decode(*View) - MsgPackFree(*View, #False) - EndIf - FreeMemory(*Answer) - If Not *List Or *List\Kind <> Kind - If *List - FreeStructure(*List) - EndIf - BakaShrot_AbortConnection() - ProcedureReturn -1 - EndIf - - Json = CreateJSON(#PB_Any) - If Not Json - FreeStructure(*List) - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_Internal, -1) - EndIf - Root = SetJSONObject(JSONValue(Json)) - If Kind = #BakaShrot_NameKind_Topic - SetJSONString(AddJSONMember(Root, "kind"), "topic") - Else - SetJSONString(AddJSONMember(Root, "kind"), "node") - EndIf - SetJSONBoolean(AddJSONMember(Root, "truncated"), *List\Truncated) - Items = SetJSONArray(AddJSONMember(Root, "items")) - ForEach *List\Entries() - Item = SetJSONObject(AddJSONElement(Items)) - SetJSONInteger(AddJSONMember(Item, "id"), *List\Entries()\Id) - SetJSONString(AddJSONMember(Item, "name"), *List\Entries()\Name) - SetJSONString(AddJSONMember(Item, "origin"), *List\Entries()\Origin) - Next - BakaShrot_NamesList = ComposeJSON(Json) - FreeJSON(Json) - - Count = ListSize(*List\Entries()) - FreeStructure(*List) - ProcedureReturn Count -EndProcedure - -ProcedureCDLL.l BakaShrot_ListTopics() - ProcedureReturn BakaShrot_ListNamesOf(#BakaShrot_NameKind_Topic) -EndProcedure - -ProcedureCDLL.l BakaShrot_ListNodes() - ProcedureReturn BakaShrot_ListNamesOf(#BakaShrot_NameKind_Node) -EndProcedure - -; JSON of the last successful BakaShrot_ListTopics/Nodes(). -ProcedureCDLL.i BakaShrot_GetNamesListA(*Buffer, BufferSize.i) - ProcedureReturn BakaShrot_CopyString(BakaShrot_NamesList, *Buffer, BufferSize, #PB_UTF8) -EndProcedure - -ProcedureCDLL.i BakaShrot_GetNamesListW(*Buffer, BufferSize.i) - ProcedureReturn BakaShrot_CopyString(BakaShrot_NamesList, *Buffer, BufferSize, #PB_Unicode) -EndProcedure - - -; Name found by the last successful BakaShrot_ResolveTopic/Node(), "" if it has none. -ProcedureCDLL.i BakaShrot_GetResolvedNameA(*Buffer, BufferSize.i) - ProcedureReturn BakaShrot_CopyString(BakaShrot_ResolvedName, *Buffer, BufferSize, #PB_UTF8) -EndProcedure - -ProcedureCDLL.i BakaShrot_GetResolvedNameW(*Buffer, BufferSize.i) - ProcedureReturn BakaShrot_CopyString(BakaShrot_ResolvedName, *Buffer, BufferSize, #PB_Unicode) -EndProcedure - -; Data (JSON or not) of the selected message of the last successful -; BakaShrot_GetLatestMessage() or BakaShrot_GetMessages(). -ProcedureCDLL.i BakaShrot_GetMessageDataA(*Buffer, BufferSize.i) - ProcedureReturn BakaShrot_CopyString(BakaShrot_MessageData, *Buffer, BufferSize, #PB_UTF8) -EndProcedure - -ProcedureCDLL.i BakaShrot_GetMessageDataW(*Buffer, BufferSize.i) - ProcedureReturn BakaShrot_CopyString(BakaShrot_MessageData, *Buffer, BufferSize, #PB_Unicode) -EndProcedure - - -; Why the server refused the last request, empty if it didn't. -ProcedureCDLL.i BakaShrot_GetRefusalReasonA(*Buffer, BufferSize.i) - ProcedureReturn BakaShrot_CopyString(BakaShrot_RefusalReason, *Buffer, BufferSize, #PB_UTF8) -EndProcedure - -ProcedureCDLL.i BakaShrot_GetRefusalReasonW(*Buffer, BufferSize.i) - ProcedureReturn BakaShrot_CopyString(BakaShrot_RefusalReason, *Buffer, BufferSize, #PB_Unicode) -EndProcedure - - -; Runs a raw SQL query on the server, read-only: a single SELECT (or WITH -; ... SELECT). The server refuses it if this client isn't allowed to query, -; if it fails, or if its result doesn't fit in one packet. -; On success, read the result with BakaShrot_GetQueryResult(), as JSON: -; {"columns": ["name", ...], "rows": [["value", ...], ...]} -; Every value is a string, or null for NULL. -; On failure, BakaShrot_IsConnected() tells if it was refused (see -; BakaShrot_GetRefusalReason()) or if the connection failed. -Procedure.i BakaShrot_QueryString(Sql.s) - Protected Request.BakaShrot_QueryRequest - Protected *Result.BakaShrot_QueryResult - Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer - Protected *View.MsgPackData, IsRefusal.i - - BakaShrot_ResetError() - BakaShrot_QueryResult = "" - - If Not BakaShrot_Outbound\ConnectionId Or BakaShrot_Outbound\Metadata\Status <> #BakaShrot_ConnectionStatus_Authenticated - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_NotConnected, #False) - EndIf - - Request\Sql = Sql - *Packet = BakaShrot_QueryRequestPacket_Encode(@Request, @PacketSize) - If Not *Packet - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_Internal, #False) - EndIf - *Answer = BakaShrot_SendRequest(*Packet, PacketSize\i, @AnswerSize) - FreeMemory(*Packet) - If Not *Answer - ProcedureReturn #False - EndIf - - If BakaShrot_GetPacketType(*Answer, AnswerSize\i) = #BakaShrot_PacketType_RequestRefused - IsRefusal = BakaShrot_ReadRefusal(*Answer, AnswerSize\i) - FreeMemory(*Answer) - If Not IsRefusal - BakaShrot_AbortConnection() - EndIf - ProcedureReturn #False - EndIf - - *Result = 0 - *View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i) - If *View - *Result = BakaShrot_QueryResultPacket_Decode(*View) - MsgPackFree(*View, #False) - EndIf - FreeMemory(*Answer) - If Not *Result - BakaShrot_AbortConnection() - ProcedureReturn #False - EndIf - - BakaShrot_QueryResult = *Result\JsonResult - FreeStructure(*Result) - ProcedureReturn #True -EndProcedure - -ProcedureCDLL.i BakaShrot_QueryA(*Sql) - If Not *Sql - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) - EndIf - ProcedureReturn BakaShrot_QueryString(PeekS(*Sql, -1, #PB_UTF8)) -EndProcedure - -ProcedureCDLL.i BakaShrot_QueryW(*Sql) - If Not *Sql - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) - EndIf - ProcedureReturn BakaShrot_QueryString(PeekS(*Sql, -1, #PB_Unicode)) -EndProcedure - - -; JSON result of the last successful BakaShrot_Query(). -ProcedureCDLL.i BakaShrot_GetQueryResultA(*Buffer, BufferSize.i) - ProcedureReturn BakaShrot_CopyString(BakaShrot_QueryResult, *Buffer, BufferSize, #PB_UTF8) -EndProcedure - -ProcedureCDLL.i BakaShrot_GetQueryResultW(*Buffer, BufferSize.i) - ProcedureReturn BakaShrot_CopyString(BakaShrot_QueryResult, *Buffer, BufferSize, #PB_Unicode) -EndProcedure - - -; --- Attachments ----------------------------------------------------------------- -; At most one per message, of any size the server takes (its -; MaxAttachmentSize), sent and read in parts of 1 MB, checked with their -; SHA-256 (Design/Attachments.md). The message is only stored once all of its -; attachment is: readers never see it without. - -; What BakaShrot_LoadAttachment() read, for BakaShrot_GetAttachmentData(). -Global *BakaShrot_AttachmentData = 0 -Global BakaShrot_AttachmentDataSize.q = 0 - - -; Sends *Request and returns the answer if it's a packet of AnswerType, its -; size in *AnswerSize\i. Returns 0 if the server refused it (the reason in -; BakaShrot_RefusalReason, still connected), or anything else went wrong -; (the connection is closed then). -Procedure.i BakaShrot_RequestExpecting(*Request, RequestSize.i, AnswerType.i, *AnswerSize.Integer) - Protected *Answer, Type.i, IsRefusal.i - - *Answer = BakaShrot_SendRequest(*Request, RequestSize, *AnswerSize) - If Not *Answer - ProcedureReturn 0 - EndIf - - Type = BakaShrot_GetPacketType(*Answer, *AnswerSize\i) - If Type = #BakaShrot_PacketType_RequestRefused - IsRefusal = BakaShrot_ReadRefusal(*Answer, *AnswerSize\i) - FreeMemory(*Answer) - If Not IsRefusal - BakaShrot_AbortConnection() - EndIf - ProcedureReturn 0 - EndIf - If Type <> AnswerType - FreeMemory(*Answer) - BakaShrot_AbortConnection() - ProcedureReturn 0 - EndIf - ProcedureReturn *Answer -EndProcedure - - -; Uploads Size bytes, read from FileId (from its start) or else from *Memory, -; as the attachment of a message about to be pushed to Topic ("" for the -; client's default one). Its SHA-256 is computed first, so the file is read twice. -; Returns the upload id for BakaShrot_PushMessageToString(), 0 on failure. -Procedure.q BakaShrot_Upload(Topic.s, FileId.i, *Memory, Size.q) - Protected Start.BakaShrot_UploadStart, *Started.BakaShrot_UploadStarted - Protected Chunk.BakaShrot_UploadChunk, *Stored.BakaShrot_ChunkStored - Protected Hash.BakaShrot_Sha256, *Buffer, Index.q, Count.q, Bytes.i, UploadId.q, Received.q, Complete.i - Protected *Request, RequestSize.Integer, *Answer, AnswerSize.Integer, *View.MsgPackData - - BakaShrot_ResetError() - If Not BakaShrot_Outbound\ConnectionId Or BakaShrot_Outbound\Metadata\Status <> #BakaShrot_ConnectionStatus_Authenticated - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_NotConnected, 0) - EndIf - If Topic <> "" And Not BakaShrot_IsValidRef(Topic) - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, 0) - EndIf - If Size < 1 - BakaShrot_RefusalReason = "The attachment is empty" - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, 0) - EndIf - If Size > #BakaShrot_MaxAttachmentSize - BakaShrot_RefusalReason = "The attachment is too big: " + Str(Size) + " bytes, at most " + Str(#BakaShrot_MaxAttachmentSize) - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, 0) - EndIf - - *Buffer = AllocateMemory(#BakaShrot_AttachmentChunkSize, #PB_Memory_NoClear) - If Not *Buffer Or Not BakaShrot_Sha256_Start(@Hash) - If *Buffer : FreeMemory(*Buffer) : EndIf - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_Internal, 0) - EndIf - Count = BakaShrot_AttachmentChunkCount(Size) - - ; 1. Its SHA-256. - If FileId - FileSeek(FileId, 0) - For Index = 0 To Count - 1 - Bytes = BakaShrot_AttachmentChunkBytes(Size, Index) - If ReadData(FileId, *Buffer, Bytes) <> Bytes - BakaShrot_RefusalReason = "The file couldn't be read" - FreeMemory(*Buffer) - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_FileError, 0) - EndIf - BakaShrot_Sha256_Add(@Hash, *Buffer, Bytes) - Next - FileSeek(FileId, 0) - Else - BakaShrot_Sha256_Add(@Hash, *Memory, Size) - EndIf - BakaShrot_Sha256_Finish(@Hash, @Start\Sha256[0]) - - ; 2. The server makes room for it. - Start\Topic = Topic - Start\Size = Size - *Request = BakaShrot_UploadStartPacket_Encode(@Start, @RequestSize) - If Not *Request - FreeMemory(*Buffer) - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_Internal, 0) - EndIf - *Answer = BakaShrot_RequestExpecting(*Request, RequestSize\i, #BakaShrot_PacketType_UploadStarted, @AnswerSize) - FreeMemory(*Request) - If Not *Answer - FreeMemory(*Buffer) - ProcedureReturn 0 - EndIf - *Started = 0 - *View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i) - If *View - *Started = BakaShrot_UploadStartedPacket_Decode(*View) - MsgPackFree(*View, #False) - EndIf - FreeMemory(*Answer) - If Not *Started Or *Started\ChunkSize <> #BakaShrot_AttachmentChunkSize - If *Started : FreeStructure(*Started) : EndIf - FreeMemory(*Buffer) - BakaShrot_AbortConnection() - ProcedureReturn 0 - EndIf - UploadId = *Started\UploadId - FreeStructure(*Started) - - ; 3. Its parts, in order. - Chunk\UploadId = UploadId - For Index = 0 To Count - 1 - Bytes = BakaShrot_AttachmentChunkBytes(Size, Index) - If FileId - If ReadData(FileId, *Buffer, Bytes) <> Bytes - BakaShrot_RefusalReason = "The file couldn't be read" - FreeMemory(*Buffer) - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_FileError, 0) - EndIf - Chunk\Data = *Buffer - Else - Chunk\Data = *Memory + Index * #BakaShrot_AttachmentChunkSize - EndIf - Chunk\ChunkIndex = Index - Chunk\DataSize = Bytes - *Request = BakaShrot_UploadChunkPacket_Encode(@Chunk, @RequestSize) - If Not *Request - FreeMemory(*Buffer) - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_Internal, 0) - EndIf - *Answer = BakaShrot_RequestExpecting(*Request, RequestSize\i, #BakaShrot_PacketType_ChunkStored, @AnswerSize) - FreeMemory(*Request) - If Not *Answer - FreeMemory(*Buffer) - ProcedureReturn 0 - EndIf - *Stored = 0 - *View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i) - If *View - *Stored = BakaShrot_ChunkStoredPacket_Decode(*View) - MsgPackFree(*View, #False) - EndIf - FreeMemory(*Answer) - If Not *Stored - FreeMemory(*Buffer) - BakaShrot_AbortConnection() - ProcedureReturn 0 - EndIf - Received = *Stored\Received - Complete = *Stored\Complete - FreeStructure(*Stored) - ; Complete exactly with the last part. - If Received <> Index * #BakaShrot_AttachmentChunkSize + Bytes Or Bool(Complete) <> Bool(Index = Count - 1) - FreeMemory(*Buffer) - BakaShrot_AbortConnection() - ProcedureReturn 0 - EndIf - Next - - FreeMemory(*Buffer) - ProcedureReturn UploadId -EndProcedure - - -; Pushes a message with the file at FilePath as its attachment, see -; BakaShrot_PushMessageToString(): the file is uploaded first, the message -; only stored once all of it is on the server. -; Returns the new message's id, or -1 on failure (refused, see -; BakaShrot_GetRefusalReason(), or the connection failed). -Procedure.q BakaShrot_PushMessageWithFileString(Topic.s, JsonData.s, FilePath.s) - Protected FileId.i, UploadId.q - - BakaShrot_ResetError() - If StringByteLength(JsonData, #PB_UTF8) > #BakaShrot_MaxMessageSize - BakaShrot_RefusalReason = "The message is too big: " + Str(StringByteLength(JsonData, #PB_UTF8)) + " bytes, at most " + Str(#BakaShrot_MaxMessageSize) - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1) - EndIf - FileId = ReadFile(#PB_Any, FilePath, #PB_File_SharedRead) - If Not FileId - BakaShrot_RefusalReason = "Can't open '" + FilePath + "'" - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_FileError, -1) - EndIf - UploadId = BakaShrot_Upload(Topic, FileId, 0, Lof(FileId)) - CloseFile(FileId) - If Not UploadId - ProcedureReturn -1 - EndIf - ProcedureReturn BakaShrot_PushMessageToString(Topic, JsonData, UploadId) -EndProcedure - -; A null *Topic is the client's default topic, a null *JsonData an empty message. -ProcedureCDLL.q BakaShrot_PushMessageWithFileA(*Topic, *JsonData, *FilePath) - Protected Topic.s, JsonData.s - If Not *FilePath - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1) - EndIf - If *Topic : Topic = PeekS(*Topic, -1, #PB_UTF8) : EndIf - If *JsonData : JsonData = PeekS(*JsonData, -1, #PB_UTF8) : EndIf - ProcedureReturn BakaShrot_PushMessageWithFileString(Topic, JsonData, PeekS(*FilePath, -1, #PB_UTF8)) -EndProcedure - -ProcedureCDLL.q BakaShrot_PushMessageWithFileW(*Topic, *JsonData, *FilePath) - Protected Topic.s, JsonData.s - If Not *FilePath - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1) - EndIf - If *Topic : Topic = PeekS(*Topic, -1, #PB_Unicode) : EndIf - If *JsonData : JsonData = PeekS(*JsonData, -1, #PB_Unicode) : EndIf - ProcedureReturn BakaShrot_PushMessageWithFileString(Topic, JsonData, PeekS(*FilePath, -1, #PB_Unicode)) -EndProcedure - - -; Same, the attachment being Size bytes at *Data. -Procedure.q BakaShrot_PushMessageWithDataString(Topic.s, JsonData.s, *Data, Size.q) - Protected UploadId.q - - BakaShrot_ResetError() - If StringByteLength(JsonData, #PB_UTF8) > #BakaShrot_MaxMessageSize - BakaShrot_RefusalReason = "The message is too big: " + Str(StringByteLength(JsonData, #PB_UTF8)) + " bytes, at most " + Str(#BakaShrot_MaxMessageSize) - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1) - EndIf - If Not *Data - BakaShrot_RefusalReason = "The attachment is empty" - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1) - EndIf - UploadId = BakaShrot_Upload(Topic, 0, *Data, Size) - If Not UploadId - ProcedureReturn -1 - EndIf - ProcedureReturn BakaShrot_PushMessageToString(Topic, JsonData, UploadId) -EndProcedure - -ProcedureCDLL.q BakaShrot_PushMessageWithDataA(*Topic, *JsonData, *Data, Size.q) - Protected Topic.s, JsonData.s - If *Topic : Topic = PeekS(*Topic, -1, #PB_UTF8) : EndIf - If *JsonData : JsonData = PeekS(*JsonData, -1, #PB_UTF8) : EndIf - ProcedureReturn BakaShrot_PushMessageWithDataString(Topic, JsonData, *Data, Size) -EndProcedure - -ProcedureCDLL.q BakaShrot_PushMessageWithDataW(*Topic, *JsonData, *Data, Size.q) - Protected Topic.s, JsonData.s - If *Topic : Topic = PeekS(*Topic, -1, #PB_Unicode) : EndIf - If *JsonData : JsonData = PeekS(*JsonData, -1, #PB_Unicode) : EndIf - ProcedureReturn BakaShrot_PushMessageWithDataString(Topic, JsonData, *Data, Size) -EndProcedure - - -; Reads the attachment of Topic:Node#MessageId, a part at a time, into FileId -; (from its start) or else into memory (*BakaShrot_AttachmentData), and -; checks its SHA-256. -; Returns its size, -1 on failure: refused (no attachment, not on this server -; yet...), a SHA-256 mismatch (refusal reason set), or the connection failed. -Procedure.q BakaShrot_Download(Topic.s, Node.s, MessageId.q, FileId.i) - Protected Request.BakaShrot_GetAttachment, *Chunk.BakaShrot_AttachmentChunk - Protected Hash.BakaShrot_Sha256, Index.q, Count.q, Size.q, *Memory, IsValid.i - Protected Dim Expected.a(#BakaShrot_Sha256Size - 1), Dim Result.a(#BakaShrot_Sha256Size - 1) - Protected *Request, RequestSize.Integer, *Answer, AnswerSize.Integer, *View.MsgPackData - - BakaShrot_ResetError() - If Not BakaShrot_Outbound\ConnectionId Or BakaShrot_Outbound\Metadata\Status <> #BakaShrot_ConnectionStatus_Authenticated - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_NotConnected, -1) - EndIf - If Not BakaShrot_IsValidRef(Topic) Or Not BakaShrot_IsValidRef(Node) Or MessageId < 1 Or Not BakaShrot_Sha256_Start(@Hash) - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1) - EndIf - - Request\Topic = Topic - Request\Node = Node - Request\MessageId = MessageId - Index = 0 - Count = 1 - While Index < Count - Request\ChunkIndex = Index - *Request = BakaShrot_GetAttachmentPacket_Encode(@Request, @RequestSize) - If Not *Request - BakaShrot_LastError = #BakaShrot_Error_Internal - Goto DownloadFailed - EndIf - *Answer = BakaShrot_RequestExpecting(*Request, RequestSize\i, #BakaShrot_PacketType_AttachmentChunk, @AnswerSize) - FreeMemory(*Request) - If Not *Answer - Goto DownloadFailed - EndIf - *Chunk = 0 - *View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i) - If *View - *Chunk = BakaShrot_AttachmentChunkPacket_Decode(*View) - MsgPackFree(*View, #False) - EndIf - FreeMemory(*Answer) - If Not *Chunk - BakaShrot_AbortConnection() - Goto DownloadFailed - EndIf - - ; The first part tells the size and SHA-256, every other must agree. - If Index = 0 - Size = *Chunk\Size - Count = BakaShrot_AttachmentChunkCount(Size) - CopyMemory(@*Chunk\Sha256[0], @Expected(0), #BakaShrot_Sha256Size) - If Not FileId - *Memory = AllocateMemory(Size, #PB_Memory_NoClear) - If Not *Memory - BakaShrot_AttachmentChunkPacket_Free(*Chunk) - BakaShrot_RefusalReason = "Out of memory for " + Str(Size) + " bytes" - BakaShrot_LastError = #BakaShrot_Error_Internal - Goto DownloadFailed - EndIf - EndIf - EndIf - If *Chunk\MessageId <> MessageId Or *Chunk\ChunkIndex <> Index Or *Chunk\Size <> Size Or Not CompareMemory(@*Chunk\Sha256[0], @Expected(0), #BakaShrot_Sha256Size) Or *Chunk\DataSize <> BakaShrot_AttachmentChunkBytes(Size, Index) - BakaShrot_AttachmentChunkPacket_Free(*Chunk) - BakaShrot_AbortConnection() - Goto DownloadFailed - EndIf - - BakaShrot_Sha256_Add(@Hash, *Chunk\Data, *Chunk\DataSize) - If FileId - If WriteData(FileId, *Chunk\Data, *Chunk\DataSize) <> *Chunk\DataSize - BakaShrot_AttachmentChunkPacket_Free(*Chunk) - BakaShrot_RefusalReason = "The file couldn't be written" - BakaShrot_LastError = #BakaShrot_Error_FileError - Goto DownloadFailed - EndIf - Else - CopyMemory(*Chunk\Data, *Memory + Index * #BakaShrot_AttachmentChunkSize, *Chunk\DataSize) - EndIf - BakaShrot_AttachmentChunkPacket_Free(*Chunk) - Index + 1 - Wend - - BakaShrot_Sha256_Finish(@Hash, @Result(0)) - If Not CompareMemory(@Result(0), @Expected(0), #BakaShrot_Sha256Size) - BakaShrot_RefusalReason = "The attachment doesn't match its SHA-256" - BakaShrot_LastError = #BakaShrot_Error_AttachmentMismatch - Goto DownloadFailed - EndIf - - If Not FileId - If *BakaShrot_AttachmentData - FreeMemory(*BakaShrot_AttachmentData) - EndIf - *BakaShrot_AttachmentData = *Memory - BakaShrot_AttachmentDataSize = Size - EndIf - ProcedureReturn Size - - DownloadFailed: - If *Memory - FreeMemory(*Memory) - EndIf - ProcedureReturn -1 -EndProcedure - - -; Saves the attachment of Topic:Node#MessageId to FilePath (replaced), -; checked with its SHA-256. A failed one leaves no file. -; Returns its size, -1 on failure, see BakaShrot_Download(). -Procedure.q BakaShrot_SaveAttachmentString(Topic.s, Node.s, MessageId.q, FilePath.s) - Protected FileId.i, Size.q - - BakaShrot_ResetError() - FileId = CreateFile(#PB_Any, FilePath) - If Not FileId - BakaShrot_RefusalReason = "Can't create '" + FilePath + "'" - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_FileError, -1) - EndIf - Size = BakaShrot_Download(Topic, Node, MessageId, FileId) - CloseFile(FileId) - If Size < 0 - DeleteFile(FilePath) - EndIf - ProcedureReturn Size -EndProcedure - -ProcedureCDLL.q BakaShrot_SaveAttachmentA(*Topic, *Node, MessageId.q, *FilePath) - If Not *Topic Or Not *Node Or Not *FilePath - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1) - EndIf - ProcedureReturn BakaShrot_SaveAttachmentString(PeekS(*Topic, -1, #PB_UTF8), PeekS(*Node, -1, #PB_UTF8), MessageId, PeekS(*FilePath, -1, #PB_UTF8)) -EndProcedure - -ProcedureCDLL.q BakaShrot_SaveAttachmentW(*Topic, *Node, MessageId.q, *FilePath) - If Not *Topic Or Not *Node Or Not *FilePath - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1) - EndIf - ProcedureReturn BakaShrot_SaveAttachmentString(PeekS(*Topic, -1, #PB_Unicode), PeekS(*Node, -1, #PB_Unicode), MessageId, PeekS(*FilePath, -1, #PB_Unicode)) -EndProcedure - - -; Reads the attachment of Topic:Node#MessageId into memory, checked with its -; SHA-256, for BakaShrot_GetAttachmentData(). All of it is held at once: -; BakaShrot_SaveAttachment() for big ones. -; Returns its size, -1 on failure, see BakaShrot_Download(). -ProcedureCDLL.q BakaShrot_LoadAttachmentA(*Topic, *Node, MessageId.q) - If Not *Topic Or Not *Node - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1) - EndIf - ProcedureReturn BakaShrot_Download(PeekS(*Topic, -1, #PB_UTF8), PeekS(*Node, -1, #PB_UTF8), MessageId, 0) -EndProcedure - -ProcedureCDLL.q BakaShrot_LoadAttachmentW(*Topic, *Node, MessageId.q) - If Not *Topic Or Not *Node - ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1) - EndIf - ProcedureReturn BakaShrot_Download(PeekS(*Topic, -1, #PB_Unicode), PeekS(*Node, -1, #PB_Unicode), MessageId, 0) -EndProcedure - -; Copies what the last successful BakaShrot_LoadAttachment() read into -; *Buffer, if BufferSize is enough. Returns its size (0 if none): call it -; with a null *Buffer first. -ProcedureCDLL.q BakaShrot_GetAttachmentData(*Buffer, BufferSize.q) - If *Buffer And *BakaShrot_AttachmentData And BufferSize >= BakaShrot_AttachmentDataSize - CopyMemory(*BakaShrot_AttachmentData, *Buffer, BakaShrot_AttachmentDataSize) - EndIf - ProcedureReturn BakaShrot_AttachmentDataSize -EndProcedure - -; Frees what BakaShrot_LoadAttachment() read. -ProcedureCDLL.i BakaShrot_FreeAttachmentData() - If *BakaShrot_AttachmentData - FreeMemory(*BakaShrot_AttachmentData) - EndIf - *BakaShrot_AttachmentData = 0 - BakaShrot_AttachmentDataSize = 0 - ProcedureReturn #True -EndProcedure - - -; Size in bytes of the selected message's attachment, 0 if it has none. -ProcedureCDLL.q BakaShrot_GetMessageAttachmentSize() - ProcedureReturn BakaShrot_MessageAttachmentSize -EndProcedure - -; #True if all of the selected message's attachment is on this server: a -; replicated one comes after its message. -ProcedureCDLL.i BakaShrot_IsMessageAttachmentReady() - ProcedureReturn BakaShrot_MessageAttachmentReady -EndProcedure diff --git a/Client/BakaShrot_Client.pbi.cfg b/Client/BakaShrot_Client.pbi.cfg deleted file mode 100644 index e0cc554..0000000 --- a/Client/BakaShrot_Client.pbi.cfg +++ /dev/null @@ -1,7 +0,0 @@ -IDE Options = PureBasic 6.41 beta 2 (Windows - x64) -CursorPosition = 4 -EnableXP -DPIAware -CompileSourceDirectory -EnableCompileCount = 0 -EnableBuildCount = 0 diff --git a/Client/BakaShrot_Client_Prototypes.pbi b/Client/BakaShrot_Client_Prototypes.pbi deleted file mode 100644 index 35b4710..0000000 --- a/Client/BakaShrot_Client_Prototypes.pbi +++ /dev/null @@ -1,380 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: BakaShrot_Client_Prototypes.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; BakaShrot Client DLL - Prototypes -; -; Include this in an app to use BakaShrot_Client.dll: -; XIncludeFile "BakaShrot_Client_Prototypes.pbi" -; If BakaShrot_LoadClient("BakaShrot_Client.dll") -; BakaShrot_SetPrivateKey("...") -; BakaShrot_SetPublicKey("...") -; BakaShrot_SetServerPublicKey("...") -; ... -; BakaShrot_UnloadClient() -; EndIf -; -; See BakaShrot_Client.pbi for what each function does. -; The string functions are mapped to the DLL's W (UTF-16) variants. -; After a failed call, BakaShrot_GetLastError() tells why: the codes and -; what to do about each are in BakaShrot_ErrorCodes.pbi, next to this file -; (included below), BakaShrot_ErrorName() names them. -; ============================================================================ - -XIncludeFile "BakaShrot_ErrorCodes.pbi" - - -PrototypeC.i BakaShrot_SetPrivateKey_Prototype(PrivateKey.p-unicode) -PrototypeC.i BakaShrot_SetPublicKey_Prototype(PublicKey.p-unicode) -PrototypeC.i BakaShrot_SetServerPublicKey_Prototype(PublicKey.p-unicode) -PrototypeC.i BakaShrot_SetNodeId_Prototype(NodeId.l) -PrototypeC.i BakaShrot_SetNode_Prototype(Node.p-unicode) -PrototypeC.i BakaShrot_Connect_Prototype(Host.p-unicode, Port.l) -PrototypeC.i BakaShrot_IsConnected_Prototype() -PrototypeC.i BakaShrot_Disconnect_Prototype() -PrototypeC.q BakaShrot_PushMessage_Prototype(JsonData.p-unicode) -PrototypeC.q BakaShrot_PushMessageTo_Prototype(Topic.p-unicode, JsonData.p-unicode) -PrototypeC.i BakaShrot_GetLatestMessage_Prototype(TopicId.l, NodeId.l) -PrototypeC.i BakaShrot_GetLatestMessageOf_Prototype(Topic.p-unicode, Node.p-unicode) -PrototypeC.q BakaShrot_GetMessageId_Prototype() -PrototypeC.q BakaShrot_GetMessagePushedAt_Prototype() -PrototypeC.i BakaShrot_GetMessageData_Prototype(*Buffer, BufferSize.i) -PrototypeC.l BakaShrot_GetMessageTopicId_Prototype() -PrototypeC.l BakaShrot_GetMessageNodeId_Prototype() -PrototypeC.i BakaShrot_GetMessageTopic_Prototype(*Buffer, BufferSize.i) -PrototypeC.i BakaShrot_GetMessageNode_Prototype(*Buffer, BufferSize.i) -PrototypeC.l BakaShrot_ResolveTopic_Prototype(Ref.p-unicode) -PrototypeC.l BakaShrot_ResolveNode_Prototype(Ref.p-unicode) -PrototypeC.i BakaShrot_GetResolvedName_Prototype(*Buffer, BufferSize.i) -PrototypeC.l BakaShrot_ListTopics_Prototype() -PrototypeC.l BakaShrot_ListNodes_Prototype() -PrototypeC.i BakaShrot_GetNamesList_Prototype(*Buffer, BufferSize.i) -PrototypeC.i BakaShrot_GetRefusalReason_Prototype(*Buffer, BufferSize.i) -PrototypeC.l BakaShrot_GetLastError_Prototype() -PrototypeC.i BakaShrot_Query_Prototype(Sql.p-unicode) -PrototypeC.i BakaShrot_GetQueryResult_Prototype(*Buffer, BufferSize.i) -PrototypeC.l BakaShrot_GetMessages_Prototype(Topic.p-unicode, Node.p-unicode, AfterMessageId.q, Limit.l) -PrototypeC.l BakaShrot_GetMessageCount_Prototype() -PrototypeC.i BakaShrot_SelectMessage_Prototype(Index.l) -PrototypeC.i BakaShrot_HasMoreMessages_Prototype() -PrototypeC.q BakaShrot_PushMessageWithFile_Prototype(Topic.p-unicode, JsonData.p-unicode, FilePath.p-unicode) -PrototypeC.q BakaShrot_PushMessageWithData_Prototype(Topic.p-unicode, JsonData.p-unicode, *Data, Size.q) -PrototypeC.q BakaShrot_SaveAttachment_Prototype(Topic.p-unicode, Node.p-unicode, MessageId.q, FilePath.p-unicode) -PrototypeC.q BakaShrot_LoadAttachment_Prototype(Topic.p-unicode, Node.p-unicode, MessageId.q) -PrototypeC.q BakaShrot_GetAttachmentData_Prototype(*Buffer, BufferSize.q) -PrototypeC.i BakaShrot_FreeAttachmentData_Prototype() -PrototypeC.q BakaShrot_GetMessageAttachmentSize_Prototype() -PrototypeC.i BakaShrot_IsMessageAttachmentReady_Prototype() - - -Global BakaShrot_SetPrivateKey.BakaShrot_SetPrivateKey_Prototype -Global BakaShrot_SetPublicKey.BakaShrot_SetPublicKey_Prototype -Global BakaShrot_SetServerPublicKey.BakaShrot_SetServerPublicKey_Prototype -Global BakaShrot_SetNodeId.BakaShrot_SetNodeId_Prototype -Global BakaShrot_SetNode.BakaShrot_SetNode_Prototype -Global BakaShrot_Connect.BakaShrot_Connect_Prototype -Global BakaShrot_IsConnected.BakaShrot_IsConnected_Prototype -Global BakaShrot_Disconnect.BakaShrot_Disconnect_Prototype -Global BakaShrot_PushMessage.BakaShrot_PushMessage_Prototype -Global BakaShrot_PushMessageTo.BakaShrot_PushMessageTo_Prototype -Global BakaShrot_GetLatestMessage.BakaShrot_GetLatestMessage_Prototype -Global BakaShrot_GetLatestMessageOf.BakaShrot_GetLatestMessageOf_Prototype -Global BakaShrot_GetMessageId.BakaShrot_GetMessageId_Prototype -Global BakaShrot_GetMessagePushedAt.BakaShrot_GetMessagePushedAt_Prototype -Global BakaShrot_GetMessageData.BakaShrot_GetMessageData_Prototype -Global BakaShrot_GetMessageTopicId.BakaShrot_GetMessageTopicId_Prototype -Global BakaShrot_GetMessageNodeId.BakaShrot_GetMessageNodeId_Prototype -Global BakaShrot_GetMessageTopic.BakaShrot_GetMessageTopic_Prototype -Global BakaShrot_GetMessageNode.BakaShrot_GetMessageNode_Prototype -Global BakaShrot_ResolveTopic.BakaShrot_ResolveTopic_Prototype -Global BakaShrot_ResolveNode.BakaShrot_ResolveNode_Prototype -Global BakaShrot_GetResolvedName.BakaShrot_GetResolvedName_Prototype -Global BakaShrot_ListTopics.BakaShrot_ListTopics_Prototype -Global BakaShrot_ListNodes.BakaShrot_ListNodes_Prototype -Global BakaShrot_GetNamesList.BakaShrot_GetNamesList_Prototype -Global BakaShrot_GetRefusalReason.BakaShrot_GetRefusalReason_Prototype -Global BakaShrot_GetLastError.BakaShrot_GetLastError_Prototype -Global BakaShrot_Query.BakaShrot_Query_Prototype -Global BakaShrot_GetQueryResult.BakaShrot_GetQueryResult_Prototype -Global BakaShrot_GetMessages.BakaShrot_GetMessages_Prototype -Global BakaShrot_GetMessageCount.BakaShrot_GetMessageCount_Prototype -Global BakaShrot_SelectMessage.BakaShrot_SelectMessage_Prototype -Global BakaShrot_HasMoreMessages.BakaShrot_HasMoreMessages_Prototype -Global BakaShrot_PushMessageWithFile.BakaShrot_PushMessageWithFile_Prototype -Global BakaShrot_PushMessageWithData.BakaShrot_PushMessageWithData_Prototype -Global BakaShrot_SaveAttachment.BakaShrot_SaveAttachment_Prototype -Global BakaShrot_LoadAttachment.BakaShrot_LoadAttachment_Prototype -Global BakaShrot_GetAttachmentData.BakaShrot_GetAttachmentData_Prototype -Global BakaShrot_FreeAttachmentData.BakaShrot_FreeAttachmentData_Prototype -Global BakaShrot_GetMessageAttachmentSize.BakaShrot_GetMessageAttachmentSize_Prototype -Global BakaShrot_IsMessageAttachmentReady.BakaShrot_IsMessageAttachmentReady_Prototype - -Global BakaShrot_ClientLibrary.i = 0 - - -; Unloads the DLL loaded by BakaShrot_LoadClient(). -Procedure BakaShrot_UnloadClient() - If BakaShrot_ClientLibrary - CloseLibrary(BakaShrot_ClientLibrary) - BakaShrot_ClientLibrary = 0 - EndIf -EndProcedure - - -; Loads the DLL at DllPath and fills the function pointers above. -; Returns #False if the DLL can't be loaded or a function is missing. -Procedure.i BakaShrot_LoadClient(DllPath.s) - If BakaShrot_ClientLibrary - ProcedureReturn #False - EndIf - - BakaShrot_ClientLibrary = OpenLibrary(#PB_Any, DllPath) - If Not BakaShrot_ClientLibrary - ProcedureReturn #False - EndIf - - ; PureBasic strings are UTF-16, so the W variants are used. - BakaShrot_SetPrivateKey = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_SetPrivateKeyW") - BakaShrot_SetPublicKey = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_SetPublicKeyW") - BakaShrot_SetServerPublicKey = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_SetServerPublicKeyW") - BakaShrot_SetNodeId = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_SetNodeId") - BakaShrot_SetNode = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_SetNodeW") - BakaShrot_Connect = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_ConnectW") - BakaShrot_IsConnected = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_IsConnected") - BakaShrot_Disconnect = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_Disconnect") - BakaShrot_PushMessage = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_PushMessageW") - BakaShrot_GetLatestMessage = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetLatestMessage") - BakaShrot_GetMessageId = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetMessageId") - BakaShrot_GetMessagePushedAt = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetMessagePushedAt") - BakaShrot_GetMessageData = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetMessageDataW") - BakaShrot_GetRefusalReason = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetRefusalReasonW") - BakaShrot_GetLastError = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetLastError") - BakaShrot_Query = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_QueryW") - BakaShrot_GetQueryResult = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetQueryResultW") - BakaShrot_PushMessageTo = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_PushMessageToW") - BakaShrot_GetLatestMessageOf = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetLatestMessageOfW") - BakaShrot_GetMessageTopicId = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetMessageTopicId") - BakaShrot_GetMessageNodeId = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetMessageNodeId") - BakaShrot_GetMessageTopic = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetMessageTopicW") - BakaShrot_GetMessageNode = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetMessageNodeW") - BakaShrot_ResolveTopic = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_ResolveTopicW") - BakaShrot_ResolveNode = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_ResolveNodeW") - BakaShrot_GetResolvedName = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetResolvedNameW") - BakaShrot_ListTopics = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_ListTopics") - BakaShrot_ListNodes = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_ListNodes") - BakaShrot_GetNamesList = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetNamesListW") - BakaShrot_GetMessages = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetMessagesW") - BakaShrot_GetMessageCount = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetMessageCount") - BakaShrot_SelectMessage = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_SelectMessage") - BakaShrot_HasMoreMessages = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_HasMoreMessages") - BakaShrot_PushMessageWithFile = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_PushMessageWithFileW") - BakaShrot_PushMessageWithData = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_PushMessageWithDataW") - BakaShrot_SaveAttachment = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_SaveAttachmentW") - BakaShrot_LoadAttachment = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_LoadAttachmentW") - BakaShrot_GetAttachmentData = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetAttachmentData") - BakaShrot_FreeAttachmentData = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_FreeAttachmentData") - BakaShrot_GetMessageAttachmentSize = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetMessageAttachmentSize") - BakaShrot_IsMessageAttachmentReady = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_IsMessageAttachmentReady") - - If Not BakaShrot_SetPrivateKey Or Not BakaShrot_SetPublicKey Or Not BakaShrot_SetServerPublicKey Or Not BakaShrot_SetNodeId Or Not BakaShrot_Connect Or Not BakaShrot_IsConnected Or Not BakaShrot_Disconnect - BakaShrot_UnloadClient() - ProcedureReturn #False - EndIf - - If Not BakaShrot_PushMessage Or Not BakaShrot_GetLatestMessage Or Not BakaShrot_GetMessageId Or Not BakaShrot_GetMessagePushedAt Or Not BakaShrot_GetMessageData Or Not BakaShrot_GetRefusalReason Or Not BakaShrot_GetLastError - BakaShrot_UnloadClient() - ProcedureReturn #False - EndIf - - If Not BakaShrot_Query Or Not BakaShrot_GetQueryResult - BakaShrot_UnloadClient() - ProcedureReturn #False - EndIf - - If Not BakaShrot_SetNode Or Not BakaShrot_PushMessageTo Or Not BakaShrot_GetLatestMessageOf Or - Not BakaShrot_GetMessageTopicId Or Not BakaShrot_GetMessageNodeId Or Not BakaShrot_GetMessageTopic Or Not BakaShrot_GetMessageNode Or - Not BakaShrot_ResolveTopic Or Not BakaShrot_ResolveNode Or Not BakaShrot_GetResolvedName Or - Not BakaShrot_ListTopics Or Not BakaShrot_ListNodes Or Not BakaShrot_GetNamesList - BakaShrot_UnloadClient() - ProcedureReturn #False - EndIf - - If Not BakaShrot_GetMessages Or Not BakaShrot_GetMessageCount Or Not BakaShrot_SelectMessage Or Not BakaShrot_HasMoreMessages - BakaShrot_UnloadClient() - ProcedureReturn #False - EndIf - - If Not BakaShrot_PushMessageWithFile Or Not BakaShrot_PushMessageWithData Or Not BakaShrot_SaveAttachment Or Not BakaShrot_LoadAttachment Or Not BakaShrot_GetAttachmentData Or Not BakaShrot_FreeAttachmentData Or Not BakaShrot_GetMessageAttachmentSize Or Not BakaShrot_IsMessageAttachmentReady - BakaShrot_UnloadClient() - ProcedureReturn #False - EndIf - - ProcedureReturn #True -EndProcedure - - -; BakaShrot_GetMessageData() as a string, asks for the size, then copies. -Procedure.s BakaShrot_GetMessageDataString() - Protected *Buffer, BufferSize.i, Text.s - - BufferSize = BakaShrot_GetMessageData(0, 0) - *Buffer = AllocateMemory(BufferSize) - If Not *Buffer - ProcedureReturn "" - EndIf - BakaShrot_GetMessageData(*Buffer, BufferSize) - Text = PeekS(*Buffer, -1, #PB_Unicode) - FreeMemory(*Buffer) - - ProcedureReturn Text -EndProcedure - - -; BakaShrot_GetQueryResult() as a string, asks for the size, then copies. -Procedure.s BakaShrot_GetQueryResultString() - Protected *Buffer, BufferSize.i, Text.s - - BufferSize = BakaShrot_GetQueryResult(0, 0) - *Buffer = AllocateMemory(BufferSize) - If Not *Buffer - ProcedureReturn "" - EndIf - BakaShrot_GetQueryResult(*Buffer, BufferSize) - Text = PeekS(*Buffer, -1, #PB_Unicode) - FreeMemory(*Buffer) - - ProcedureReturn Text -EndProcedure - - -; Calls a string getter of the DLL (*Getter(*Buffer, BufferSize)) and -; returns the string: asks for the size, then copies. -PrototypeC.i BakaShrot_StringGetter_Prototype(*Buffer, BufferSize.i) -Procedure.s BakaShrot_GetString(Getter.BakaShrot_StringGetter_Prototype) - Protected *Buffer, BufferSize.i, Text.s - - BufferSize = Getter(0, 0) - *Buffer = AllocateMemory(BufferSize) - If Not *Buffer - ProcedureReturn "" - EndIf - Getter(*Buffer, BufferSize) - Text = PeekS(*Buffer, -1, #PB_Unicode) - FreeMemory(*Buffer) - - ProcedureReturn Text -EndProcedure - -; BakaShrot_GetMessageTopic/Node() and BakaShrot_GetResolvedName() as strings. -Procedure.s BakaShrot_GetMessageTopicString() - ProcedureReturn BakaShrot_GetString(BakaShrot_GetMessageTopic) -EndProcedure - -Procedure.s BakaShrot_GetMessageNodeString() - ProcedureReturn BakaShrot_GetString(BakaShrot_GetMessageNode) -EndProcedure - -Procedure.s BakaShrot_GetResolvedNameString() - ProcedureReturn BakaShrot_GetString(BakaShrot_GetResolvedName) -EndProcedure - -Procedure.s BakaShrot_GetNamesListString() - ProcedureReturn BakaShrot_GetString(BakaShrot_GetNamesList) -EndProcedure - - -; BakaShrot_GetRefusalReason() as a string, asks for the size, then copies. -Procedure.s BakaShrot_GetRefusalReasonString() - Protected *Buffer, BufferSize.i, Text.s - - BufferSize = BakaShrot_GetRefusalReason(0, 0) - *Buffer = AllocateMemory(BufferSize) - If Not *Buffer - ProcedureReturn "" - EndIf - BakaShrot_GetRefusalReason(*Buffer, BufferSize) - Text = PeekS(*Buffer, -1, #PB_Unicode) - FreeMemory(*Buffer) - - ProcedureReturn Text -EndProcedure - - -; Usage example. Only compiled when this file is run directly (F5 in the -; IDE), not when it's included by an app. -; Connects with the identity from the client.ini that Build.ps1 generates, -; run it from the Build folder while BakaShrot_Server.exe is running. -CompilerIf #PB_Compiler_IsMainFile - - Define PrivateKey.s, PublicKey.s, ServerPublicKey.s, Node.s, ServerHost.s, ServerPort.l - - OpenConsole() - - If Not OpenPreferences("client.ini") - PrintN("Failed to open client.ini") - End 1 - EndIf - PreferenceGroup("BakaShrot") - PrivateKey = ReadPreferenceString("PrivateKey", "") - PublicKey = ReadPreferenceString("PublicKey", "") - ServerPublicKey = ReadPreferenceString("ServerPublicKey", "") - Node = ReadPreferenceString("Node", ReadPreferenceString("NodeId", "")) - ServerHost = ReadPreferenceString("ServerHost", "") - ServerPort = ReadPreferenceLong("ServerPort", 0) - ClosePreferences() - - If Not BakaShrot_LoadClient("BakaShrot_Client.dll") - PrintN("Failed to load BakaShrot_Client.dll") - End 1 - EndIf - - If Not BakaShrot_SetPrivateKey(PrivateKey) - PrintN("Failed to set the private key") - End 1 - EndIf - - If Not BakaShrot_SetPublicKey(PublicKey) - PrintN("Failed to set the public key") - End 1 - EndIf - - If Not BakaShrot_SetServerPublicKey(ServerPublicKey) - PrintN("Failed to set the server's public key") - End 1 - EndIf - - If Not BakaShrot_SetNode(Node) - PrintN("Failed to set the node") - End 1 - EndIf - - If Not BakaShrot_Connect(ServerHost, ServerPort) - PrintN("Failed to connect and authenticate to " + ServerHost + ":" + Str(ServerPort)) - End 1 - EndIf - PrintN("Connected and authenticated to " + ServerHost + ":" + Str(ServerPort)) - - Delay(500) - PrintN("IsConnected: " + Str(BakaShrot_IsConnected())) - - BakaShrot_Disconnect() - PrintN("IsConnected after disconnecting: " + Str(BakaShrot_IsConnected())) - - BakaShrot_UnloadClient() - End 0 - -CompilerEndIf diff --git a/Client/notes.txt b/Client/notes.txt deleted file mode 100644 index 8808b4b..0000000 --- a/Client/notes.txt +++ /dev/null @@ -1,4 +0,0 @@ -client should be a DLL that can connect in the back. -And it should provide functions to the caller that lets it query or do shit on the server. - -When saying server, it will usually be a local process. diff --git a/Commons/Cryptography/Cipher.pbi b/Commons/Cryptography/Cipher.pbi deleted file mode 100644 index 31aeb01..0000000 --- a/Commons/Cryptography/Cipher.pbi +++ /dev/null @@ -1,255 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: Cipher.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; BakaShrot Cipher -; -; Encrypts and authenticates buffers with a shared key, and checks and -; decrypts them, so the rest of the code never touches the crypto: give it -; a key once, then hand it buffers. -; -; Cipher.BakaShrot_Cipher -; BakaShrot_Cipher_Init(@Cipher, *Key, #BakaShrot_Cipher_Client) -; *Sealed = BakaShrot_Cipher_Encrypt(@Cipher, *Packet, PacketSize, @SealedSize) -; ... send it, and on the other end, with a cipher for #BakaShrot_Cipher_Server: -; *Packet = BakaShrot_Cipher_Decrypt(@Cipher, *Sealed, SealedSize, @PacketSize) -; If Not *Packet : abort the connection : EndIf -; BakaShrot_Cipher_Clear(@Cipher) once done, wipes the keys. -; -; What it guarantees, for buffers sent in order over one connection (TCP): -; - Nobody without the key can read them (XChaCha20). -; - Nobody without the key can change, forge or truncate one (Poly1305): -; decrypting it fails. -; - Nobody can replay, reorder, drop or reflect one: each buffer carries -; its sequence number, the receiver only takes the next one it expects, -; and each direction encrypts under its own nonces (or its own key), so -; a buffer sent back to its sender doesn't decrypt either. -; Any failure means the stream can't be trusted anymore: abort the -; connection, don't try the next buffer. -; -; What it doesn't do: get the key. Both ends must already share it, agreed -; on for this connection only (Session.pbi does it for the handshake), never -; a key reused across connections: the sequence numbers start over at 0. -; -; A sealed buffer is: -; [sequence number, 8 bytes, little-endian][encrypted data][tag, 16 bytes] -; #BakaShrot_Cipher_Overhead bytes more than the data. The nonce (24 bytes) -; is the direction (1 byte), zeros, then the sequence number, never sent. -; The sequence number is authenticated too (additional data). -; -; libsodium's crypto_aead_xchacha20poly1305_ietf_*, imported in -; Libsodium.pbi: nothing here implements a primitive. InitCryptography() -; must have been called. -; -; Threads: encrypting and decrypting use separate state, so one thread may -; send while another receives. Two threads must not encrypt (or decrypt) -; with the same cipher at once. -; ============================================================================ - -XIncludeFile "Libsodium.pbi" - - -#BakaShrot_Cipher_KeySize = #BakaShrot_XChaCha20Poly1305_KeySize -#BakaShrot_Cipher_SequenceSize = 8 -#BakaShrot_Cipher_Overhead = #BakaShrot_Cipher_SequenceSize + #BakaShrot_XChaCha20Poly1305_TagSize - -; Which end of the connection a cipher is on, when both share one key: each -; encrypts under its own nonces. Never 0. -#BakaShrot_Cipher_Client = 1 -#BakaShrot_Cipher_Server = 2 - -; Past this many buffers in one direction, encrypting refuses: never reached -; in practice (2^63), but a sequence number must never wrap around. -#BakaShrot_Cipher_MaxSequence = $7FFFFFFFFFFFFFFF - - -Structure BakaShrot_CipherNonce - Bytes.a[#BakaShrot_XChaCha20Poly1305_NonceSize] -EndStructure - -Structure BakaShrot_Cipher - SendKey.a[#BakaShrot_Cipher_KeySize] - ReceiveKey.a[#BakaShrot_Cipher_KeySize] - ; First byte of the nonces of each direction. - SendDirection.a - ReceiveDirection.a - ; Sequence number of the next buffer to send, and of the next one - ; expected. - SendSequence.q - ReceiveSequence.q - IsReady.l -EndStructure - - -; Fills *Key (#BakaShrot_Cipher_KeySize bytes) with a new random key. -Procedure BakaShrot_Cipher_GenerateKey(*Key) - crypto_aead_xchacha20poly1305_ietf_keygen(*Key) -EndProcedure - - -; Wipes *Cipher's keys and state, it refuses everything until initialized -; again. Call it once the connection is over. -Procedure BakaShrot_Cipher_Clear(*Cipher.BakaShrot_Cipher) - sodium_memzero(*Cipher, SizeOf(BakaShrot_Cipher)) -EndProcedure - - -; Sets *Cipher up with one key shared by both ends (*Key, -; #BakaShrot_Cipher_KeySize bytes, copied), Role being which end this is: -; #BakaShrot_Cipher_Client or #BakaShrot_Cipher_Server, the other end must -; take the other one. -; Returns #False if Role isn't one of them. -Procedure.i BakaShrot_Cipher_Init(*Cipher.BakaShrot_Cipher, *Key, Role.i) - BakaShrot_Cipher_Clear(*Cipher) - If Not *Key Or (Role <> #BakaShrot_Cipher_Client And Role <> #BakaShrot_Cipher_Server) - ProcedureReturn #False - EndIf - - CopyMemory(*Key, @*Cipher\SendKey[0], #BakaShrot_Cipher_KeySize) - CopyMemory(*Key, @*Cipher\ReceiveKey[0], #BakaShrot_Cipher_KeySize) - *Cipher\SendDirection = Role - If Role = #BakaShrot_Cipher_Client - *Cipher\ReceiveDirection = #BakaShrot_Cipher_Server - Else - *Cipher\ReceiveDirection = #BakaShrot_Cipher_Client - EndIf - *Cipher\IsReady = #True - ProcedureReturn #True -EndProcedure - - -; Sets *Cipher up with a key per direction (each #BakaShrot_Cipher_KeySize -; bytes, copied), like libsodium's crypto_kx_* gives: the other end's -; *SendKey is this one's *ReceiveKey. -; Returns #False if they're the same key: the two directions would then -; encrypt under the same nonces, use BakaShrot_Cipher_Init() for one key. -Procedure.i BakaShrot_Cipher_InitWithKeys(*Cipher.BakaShrot_Cipher, *SendKey, *ReceiveKey) - BakaShrot_Cipher_Clear(*Cipher) - If Not *SendKey Or Not *ReceiveKey Or CompareMemory(*SendKey, *ReceiveKey, #BakaShrot_Cipher_KeySize) - ProcedureReturn #False - EndIf - - CopyMemory(*SendKey, @*Cipher\SendKey[0], #BakaShrot_Cipher_KeySize) - CopyMemory(*ReceiveKey, @*Cipher\ReceiveKey[0], #BakaShrot_Cipher_KeySize) - ; Different keys already keep the directions apart. - *Cipher\SendDirection = 0 - *Cipher\ReceiveDirection = 0 - *Cipher\IsReady = #True - ProcedureReturn #True -EndProcedure - - -; The nonce of the buffer with that direction and sequence number. -Procedure BakaShrot_Cipher_MakeNonce(*Nonce.BakaShrot_CipherNonce, Direction.a, Sequence.q) - FillMemory(*Nonce, #BakaShrot_XChaCha20Poly1305_NonceSize, 0) - *Nonce\Bytes[0] = Direction - PokeQ(@*Nonce\Bytes[#BakaShrot_XChaCha20Poly1305_NonceSize - 8], Sequence) -EndProcedure - - -; Encrypts and authenticates *Data (Size bytes, may be 0) into *Sealed, -; which must have room for Size + #BakaShrot_Cipher_Overhead bytes and not -; overlap *Data. *Data is left untouched. -; Returns #False, writing nothing, if *Cipher isn't set up. -Procedure.i BakaShrot_Cipher_EncryptTo(*Cipher.BakaShrot_Cipher, *Data, Size.i, *Sealed) - Protected Nonce.BakaShrot_CipherNonce - - If Not *Cipher\IsReady Or Not *Sealed Or Size < 0 Or (Size > 0 And Not *Data) Or *Cipher\SendSequence >= #BakaShrot_Cipher_MaxSequence - ProcedureReturn #False - EndIf - ; libsodium wants a valid pointer even for no data. - If Size = 0 - *Data = *Sealed - EndIf - - PokeQ(*Sealed, *Cipher\SendSequence) - BakaShrot_Cipher_MakeNonce(@Nonce, *Cipher\SendDirection, *Cipher\SendSequence) - crypto_aead_xchacha20poly1305_ietf_encrypt(*Sealed + #BakaShrot_Cipher_SequenceSize, 0, *Data, Size, - *Sealed, #BakaShrot_Cipher_SequenceSize, 0, @Nonce, @*Cipher\SendKey[0]) - - *Cipher\SendSequence + 1 - ProcedureReturn #True -EndProcedure - - -; Same, into a freshly allocated buffer of Size + #BakaShrot_Cipher_Overhead -; bytes, its size in *OutSize\i. -; Returns 0 if *Cipher isn't set up, or out of memory. The caller owns the -; returned buffer - free it with FreeMemory. -Procedure.i BakaShrot_Cipher_Encrypt(*Cipher.BakaShrot_Cipher, *Data, Size.i, *OutSize.Integer) - Protected *Sealed - - If Not *Cipher\IsReady Or Size < 0 - ProcedureReturn 0 - EndIf - - *Sealed = AllocateMemory(Size + #BakaShrot_Cipher_Overhead, #PB_Memory_NoClear) - If Not *Sealed - ProcedureReturn 0 - EndIf - If Not BakaShrot_Cipher_EncryptTo(*Cipher, *Data, Size, *Sealed) - FreeMemory(*Sealed) - ProcedureReturn 0 - EndIf - - *OutSize\i = Size + #BakaShrot_Cipher_Overhead - ProcedureReturn *Sealed -EndProcedure - - -; Checks and decrypts *Sealed (Size bytes, as BakaShrot_Cipher_Encrypt() -; made it on the other end) into a freshly allocated buffer, the data's size -; in *OutSize\i (0 or more, the buffer is at least 1 byte). -; Returns 0 if it isn't the next buffer expected (replayed, reordered, one -; missing), was tampered with, made with another key, sent by this end, or -; is too short; also if *Cipher isn't set up, or out of memory. Nothing -; changes then, but the connection can't be trusted anymore: abort it. -; The caller owns the returned buffer - free it with FreeMemory. -Procedure.i BakaShrot_Cipher_Decrypt(*Cipher.BakaShrot_Cipher, *Sealed, Size.i, *OutSize.Integer) - Protected *Data, DataSize.i, Nonce.BakaShrot_CipherNonce, Genuine.i - - If Not *Cipher\IsReady Or Not *Sealed Or Size < #BakaShrot_Cipher_Overhead - ProcedureReturn 0 - EndIf - - ; Only the next one: a replayed, reordered or missing buffer stops here. - If PeekQ(*Sealed) <> *Cipher\ReceiveSequence - ProcedureReturn 0 - EndIf - - DataSize = Size - #BakaShrot_Cipher_Overhead - If DataSize > 0 - *Data = AllocateMemory(DataSize, #PB_Memory_NoClear) - Else - *Data = AllocateMemory(1) - EndIf - If Not *Data - ProcedureReturn 0 - EndIf - - BakaShrot_Cipher_MakeNonce(@Nonce, *Cipher\ReceiveDirection, *Cipher\ReceiveSequence) - Genuine = Bool(crypto_aead_xchacha20poly1305_ietf_decrypt(*Data, 0, 0, *Sealed + #BakaShrot_Cipher_SequenceSize, Size - #BakaShrot_Cipher_SequenceSize, - *Sealed, #BakaShrot_Cipher_SequenceSize, @Nonce, @*Cipher\ReceiveKey[0]) = 0) - If Not Genuine - FreeMemory(*Data) - ProcedureReturn 0 - EndIf - - *Cipher\ReceiveSequence + 1 - *OutSize\i = DataSize - ProcedureReturn *Data -EndProcedure diff --git a/Commons/Cryptography/Libsodium.pbi b/Commons/Cryptography/Libsodium.pbi deleted file mode 100644 index f7913ff..0000000 --- a/Commons/Cryptography/Libsodium.pbi +++ /dev/null @@ -1,315 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: Libsodium.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; BakaShrot Cryptography -; -; Ed25519 signatures via libsodium (this does NOT reimplement any -; cryptographic primitive). -; -; EncodeData signs a buffer with the sending node's own private key. -; DecodeData checks that signature against the claimed sender's public key. -; (Misnamed: they sign and verify, nothing is encoded or decoded.) -; -; The signatures prove each end's identity in the handshake. The sealed -; boxes, key exchange and XChaCha20-Poly1305 below encrypt the connections: -; Session.pbi and Cipher.pbi use them, nothing else should. -; What's done, what isn't, and the plan to abstract it: -; Design/Cryptography.md. -; -; Key material: -; - Public key: #BakaShrot_Ed25519_PublicKeySize (32) raw bytes. -; - Private key: #BakaShrot_Ed25519_PrivateKeySize (64) raw bytes. -; (libsodium's Ed25519 secret key already embeds the seed and the public -; key, which is why it is twice the size of the public key.) -; A node's private key lives in BakaShrot_CoreConfig\PrivateKey (Config.pbi); -; the public key it hands out to peers lives in each -; BakaShrot_PeerConfig\PublicKey. Both are stored as Base64 text in the ini -; file - see EncodeKeyToString()/DecodeKeyFromString() below. -; -; Setup required to build/run this: -; - Windows: the official libsodium MSVC release's dynamic build, extracted -; to Libs/libsodium// by Build.ps1, and "libsodium.dll" -; alongside the executable. -; - Linux: libsodium-dev (Debian/Ubuntu) or libsodium-devel (Fedora) -; installed, so "-lsodium" resolves at link time and -; libsodium.so.* is available at runtime. -; libsodium itself is the same standard, audited library on both platforms, -; so signatures made on one are verifiable on the other without change. -; ============================================================================ - - -#BakaShrot_Ed25519_PublicKeySize = 32 -#BakaShrot_Ed25519_PrivateKeySize = 64 -#BakaShrot_Ed25519_SignatureSize = 64 - -; XChaCha20-Poly1305 (IETF), libsodium's crypto_aead_xchacha20poly1305_ietf_*: -; encryption and authentication of a buffer with a shared key, used by -; Commons/Cryptography/Cipher.pbi. -#BakaShrot_XChaCha20Poly1305_KeySize = 32 -#BakaShrot_XChaCha20Poly1305_NonceSize = 24 -#BakaShrot_XChaCha20Poly1305_TagSize = 16 - -; X25519 (crypto_box_seal, crypto_kx_*): sealed Hellos and the key exchange, -; used by Commons/Cryptography/Session.pbi. -#BakaShrot_X25519_PublicKeySize = 32 -#BakaShrot_X25519_SecretKeySize = 32 -#BakaShrot_SealedBoxOverhead = 48 -#BakaShrot_KxSessionKeySize = 32 - - -; Windows: the dynamic build's import library, libsodium.dll must be next to -; the program. Both are extracted from Libs/libsodium-*-msvc.zip by Build.ps1. -CompilerIf #PB_Compiler_OS = #PB_OS_Windows And #PB_Compiler_Processor = #PB_Processor_x64 - ImportC "../../Libs/libsodium/x64/libsodium.lib" -CompilerElseIf #PB_Compiler_OS = #PB_OS_Windows - ImportC "../../Libs/libsodium/x86/libsodium.lib" -CompilerElse - ImportC "-lsodium" -CompilerEndIf - - ; Must be called once (any number of extra calls are harmless) before any - ; other function below is used. Returns 0 on success, 1 if it was already - ; initialized, -1 if libsodium failed to self-check (e.g. no RNG available). - sodium_init.l() - - ; Fills *PublicKey (32 bytes) and *PrivateKey (64 bytes) with a fresh, - ; cryptographically random Ed25519 keypair. - crypto_sign_keypair.l(*PublicKey, *PrivateKey) - - ; Writes a #BakaShrot_Ed25519_SignatureSize-byte signature of *Message - ; (MessageLength bytes) to *Signature, made with *PrivateKey. - crypto_sign_detached.l(*Signature, *SignatureLength, *Message, MessageLength.q, *PrivateKey) - - ; Returns 0 if *Signature is a valid signature of *Message (MessageLength - ; bytes) made by the holder of the private key matching *PublicKey; - ; non-zero otherwise (forged, corrupted, or signed different data). - crypto_sign_verify_detached.l(*Signature, *Message, MessageLength.q, *PublicKey) - - ; Encrypts *Message (MessageLength bytes) into *Ciphertext (MessageLength + - ; #BakaShrot_XChaCha20Poly1305_TagSize bytes, the tag at the end), with - ; *Key (32 bytes) and *Nonce (24 bytes, never twice with the same key). - ; *AdditionalData (AdLength bytes, may be 0) is authenticated, not - ; encrypted. *Nsec is always 0. Always returns 0. - crypto_aead_xchacha20poly1305_ietf_encrypt.l(*Ciphertext, *CiphertextLength, *Message, MessageLength.q, *AdditionalData, AdLength.q, *Nsec, *Nonce, *Key) - - ; Checks and decrypts *Ciphertext (CiphertextLength bytes, tag included) - ; into *Message (CiphertextLength - TagSize bytes). Returns 0 if it's - ; genuine, -1 if it was tampered with, or made with another key, nonce or - ; additional data: *Message must not be used then. - crypto_aead_xchacha20poly1305_ietf_decrypt.l(*Message, *MessageLength, *Nsec, *Ciphertext, CiphertextLength.q, *AdditionalData, AdLength.q, *Nonce, *Key) - - ; Fills *Key (32 bytes) with a random XChaCha20-Poly1305 key. - crypto_aead_xchacha20poly1305_ietf_keygen(*Key) - - ; Zeroes Length bytes at *Memory, in a way the compiler can't optimize out: - ; for wiping keys. - sodium_memzero(*Memory, Length.i) - - ; Copies the public key embedded in *PrivateKey (64 bytes) into *PublicKey - ; (32 bytes). Always returns 0. - crypto_sign_ed25519_sk_to_pk.l(*PublicKey, *PrivateKey) - - ; The X25519 key (32 bytes) matching an Ed25519 public key (32 bytes) or - ; private key (64 bytes), so one identity key both signs and receives - ; sealed boxes. The public one returns -1 if it isn't a valid key. - crypto_sign_ed25519_pk_to_curve25519.l(*X25519PublicKey, *Ed25519PublicKey) - crypto_sign_ed25519_sk_to_curve25519.l(*X25519SecretKey, *Ed25519PrivateKey) - - ; Encrypts *Message (MessageLength bytes) for the holder of *PublicKey - ; (X25519) into *Ciphertext (MessageLength + 48 bytes), with a throwaway - ; key pair: only *PublicKey's holder can open it, and it doesn't tell who - ; sealed it. Returns 0, -1 on failure. - crypto_box_seal.l(*Ciphertext, *Message, MessageLength.q, *PublicKey) - - ; Opens *Ciphertext (CiphertextLength bytes) sealed for *PublicKey into - ; *Message (CiphertextLength - 48 bytes). Returns 0, or -1 if it wasn't - ; sealed for this key or was tampered with. - crypto_box_seal_open.l(*Message, *Ciphertext, CiphertextLength.q, *PublicKey, *SecretKey) - - ; Fills *PublicKey and *SecretKey (32 bytes each) with a fresh X25519 key - ; pair, for one key exchange. Returns 0. - crypto_kx_keypair.l(*PublicKey, *SecretKey) - - ; Both ends of a key exchange get the same two 32-byte keys from their own - ; key pair and the other end's public key: *Rx decrypts what this end - ; receives, *Tx encrypts what it sends (the client's Tx is the server's - ; Rx). Return -1 if the other end's public key isn't acceptable. - crypto_kx_client_session_keys.l(*Rx, *Tx, *ClientPublicKey, *ClientSecretKey, *ServerPublicKey) - crypto_kx_server_session_keys.l(*Rx, *Tx, *ServerPublicKey, *ServerSecretKey, *ClientPublicKey) - - ; SHA-256, a piece at a time: _init() a state (crypto_hash_sha256_statebytes() - ; bytes), _update() it with each piece, _final() writes the 32-byte hash. - ; For the attachments' checksums, see BakaShrot_Sha256_* below. - crypto_hash_sha256_statebytes.i() - crypto_hash_sha256_init.l(*State) - crypto_hash_sha256_update.l(*State, *Data, DataLength.q) - crypto_hash_sha256_final.l(*State, *Hash) - -EndImport - - -; Must be called once at startup, before GenerateKeyPair/EncodeData/DecodeData. -; Returns #False if libsodium could not initialize - treat that as fatal, -; there is no safe fallback to running without it. -Procedure.i InitCryptography() - ProcedureReturn Bool(sodium_init() >= 0) -EndProcedure - - -; Generates a new Ed25519 keypair for provisioning a node. -; *PublicKey must point to #BakaShrot_Ed25519_PublicKeySize bytes, -; *PrivateKey to #BakaShrot_Ed25519_PrivateKeySize bytes. -Procedure GenerateKeyPair(*PublicKey, *PrivateKey) - crypto_sign_keypair(*PublicKey, *PrivateKey) -EndProcedure - - -; Fills *PublicKey (#BakaShrot_Ed25519_PublicKeySize bytes) with the public -; key matching *PrivateKey (#BakaShrot_Ed25519_PrivateKeySize bytes), so a -; node only needs its private key in its config. -Procedure GetPublicKeyFromPrivateKey(*PrivateKey, *PublicKey) - crypto_sign_ed25519_sk_to_pk(*PublicKey, *PrivateKey) -EndProcedure - - -; Signs *Data (DataLength bytes) with *PrivateKey (this node's own private -; key, #BakaShrot_Ed25519_PrivateKeySize bytes). -; Writes the signature to *Signature, which must point to -; #BakaShrot_Ed25519_SignatureSize bytes. *Data itself is left untouched. -Procedure.i EncodeData(*Data, DataLength.i, *PrivateKey, *Signature) - Protected SignatureLength.q - ProcedureReturn Bool(crypto_sign_detached(*Signature, @SignatureLength, *Data, DataLength, *PrivateKey) = 0) -EndProcedure - - -; Verifies that *Signature (#BakaShrot_Ed25519_SignatureSize bytes) is a -; valid signature of *Data (DataLength bytes), made by the holder of the -; private key matching *PublicKey (the claimed sender's public key, from -; BakaShrot_PeerConfig\PublicKey). -; Returns #True only if the signature checks out. On #False, reject the -; packet outright - do not process it, do not fall back to trusting it. -Procedure.i DecodeData(*Data, DataLength.i, *PublicKey, *Signature) - ProcedureReturn Bool(crypto_sign_verify_detached(*Signature, *Data, DataLength, *PublicKey) = 0) -EndProcedure - - -; SHA-256 of data given a piece at a time (an attachment's parts): Start, Add -; each piece, then Finish writes the 32-byte hash. -#BakaShrot_Sha256_HashSize = 32 - -Structure BakaShrot_Sha256 - ; crypto_hash_sha256_state is 104 bytes, checked by Start. - State.a[128] -EndStructure - -; Returns #False if libsodium's state doesn't fit (a libsodium change). -Procedure.i BakaShrot_Sha256_Start(*Hash.BakaShrot_Sha256) - If crypto_hash_sha256_statebytes() > SizeOf(BakaShrot_Sha256) - ProcedureReturn #False - EndIf - ProcedureReturn Bool(crypto_hash_sha256_init(*Hash) = 0) -EndProcedure - -Procedure BakaShrot_Sha256_Add(*Hash.BakaShrot_Sha256, *Data, Size.i) - If Size > 0 - crypto_hash_sha256_update(*Hash, *Data, Size) - EndIf -EndProcedure - -Procedure BakaShrot_Sha256_Finish(*Hash.BakaShrot_Sha256, *Out) - crypto_hash_sha256_final(*Hash, *Out) -EndProcedure - - -; Encodes KeySize raw bytes at *Key as a Base64 string, for storing a key in -; the ini file (PrivateKey / PublicKey fields in Config.pbi). -Procedure.s EncodeKeyToString(*Key, KeySize.i) - ProcedureReturn Base64Encoder(*Key, KeySize) -EndProcedure - - -; Decodes KeyString back into KeySize raw bytes at *Key. -; Returns #False (and leaves *Key untouched) if KeyString is not valid -; Base64 or does not decode to exactly KeySize bytes - a malformed or -; truncated key in the config file must never be silently accepted as one -; that's merely different. -Procedure.i DecodeKeyFromString(KeyString.s, *Key, KeySize.i) - ; PureBasic's own docs warn the output buffer must have some slack over - ; the exact decoded size or the decoder can overflow it - at least 25% - ; extra and never under 64 bytes, hence the margin below. - Protected *Buffer, BufferSize.i, DecodedSize.i - - BufferSize = (KeySize * 5) / 4 + 64 - *Buffer = AllocateMemory(BufferSize) - DecodedSize = Base64Decoder(KeyString, *Buffer, BufferSize) - If DecodedSize = KeySize - CopyMemory(*Buffer, *Key, KeySize) - EndIf - FreeMemory(*Buffer) - - ProcedureReturn Bool(DecodedSize = KeySize) -EndProcedure - - -; Usage example. Only compiled when this file is run directly (F5 in the -; IDE), not when it's included as a module by the rest of the project. -CompilerIf #PB_Compiler_IsMainFile - - If Not InitCryptography() - Debug "Failed to initialize libsodium." - Else - Define *PublicKey = AllocateMemory(#BakaShrot_Ed25519_PublicKeySize) - Define *PrivateKey = AllocateMemory(#BakaShrot_Ed25519_PrivateKeySize) - Define *Signature = AllocateMemory(#BakaShrot_Ed25519_SignatureSize) - Define Message.s = ~"{\"messageData\": {\"MsgType\": \"hello\"}}" - Define MessageLength = StringByteLength(Message, #PB_Ascii) - Define *MessageBytes = AllocateMemory(MessageLength) - - PokeS(*MessageBytes, Message, -1, #PB_Ascii) - - GenerateKeyPair(*PublicKey, *PrivateKey) - Debug "PublicKey: " + EncodeKeyToString(*PublicKey, #BakaShrot_Ed25519_PublicKeySize) - Debug "PrivateKey: " + EncodeKeyToString(*PrivateKey, #BakaShrot_Ed25519_PrivateKeySize) - - If EncodeData(*MessageBytes, MessageLength, *PrivateKey, *Signature) - Debug "Signed ok. Signature: " + EncodeKeyToString(*Signature, #BakaShrot_Ed25519_SignatureSize) - - If DecodeData(*MessageBytes, MessageLength, *PublicKey, *Signature) - Debug "Verified ok, as expected." - Else - Debug "FAILED to verify a genuine signature - something is broken." - EndIf - - ; Tamper with one byte and make sure verification then rejects it. - PokeB(*MessageBytes, PeekB(*MessageBytes) ! 1) - If DecodeData(*MessageBytes, MessageLength, *PublicKey, *Signature) - Debug "FAILED: tampered data was accepted as genuine." - Else - Debug "Tampered data correctly rejected." - EndIf - Else - Debug "Failed to sign data." - EndIf - - FreeMemory(*PublicKey) - FreeMemory(*PrivateKey) - FreeMemory(*Signature) - FreeMemory(*MessageBytes) - EndIf - -CompilerEndIf diff --git a/Commons/Cryptography/Session.pbi b/Commons/Cryptography/Session.pbi deleted file mode 100644 index 8041c97..0000000 --- a/Commons/Cryptography/Session.pbi +++ /dev/null @@ -1,203 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: Session.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; BakaShrot Session -; -; The handshake's cryptography, so the connections only call these -; (the handshake itself is in Commons/Networking/Connections.pbi): -; -; - The Hello is sealed for the server's identity key: crypto_box_seal, -; for the X25519 key matching the server's Ed25519 one. Only that -; server can read it, and someone watching doesn't learn who connects. -; BakaShrot_Session_SealHello() / _OpenHello(). -; - Each end makes a key pair for this one connection (crypto_kx). The -; client's public half travels in the sealed Hello, the server's in the -; ChallengeRequest; both ends sign them with their identity keys -; (Connections.pbi), so nobody in the middle can swap them. -; BakaShrot_Session_NewKeyPair(). -; - From its own pair and the other end's public half, each end gets a -; key per direction and sets its BakaShrot_Cipher (Cipher.pbi) up with -; them: every packet after the ChallengeRequest is encrypted. -; BakaShrot_Session_StartClient() / _StartServer(). -; -; The key pair's secret and the derived keys are wiped once the cipher has -; them: a recorded connection can't be decrypted later, even with the -; identity keys (forward secrecy). -; -; libsodium does all of it (Libsodium.pbi), InitCryptography() must have -; been called. -; ============================================================================ - -XIncludeFile "Cipher.pbi" - - -#BakaShrot_Session_PublicKeySize = #BakaShrot_X25519_PublicKeySize - - -Structure BakaShrot_SessionKey - Bytes.a[32] -EndStructure - - -; One end's key pair for one connection. -Structure BakaShrot_SessionKeyPair - PublicKey.a[#BakaShrot_X25519_PublicKeySize] - SecretKey.a[#BakaShrot_X25519_SecretKeySize] -EndStructure - - -; A server's keys to open the Hellos sealed for it, from its Ed25519 -; private key. Read-only once loaded, every client thread may use them. -Structure BakaShrot_HelloKeys - PublicKey.a[#BakaShrot_X25519_PublicKeySize] - SecretKey.a[#BakaShrot_X25519_SecretKeySize] -EndStructure - - -Structure BakaShrot_SessionDirections - Rx.a[#BakaShrot_KxSessionKeySize] - Tx.a[#BakaShrot_KxSessionKeySize] -EndStructure - - -; Fills *Keys from *PrivateKey (Ed25519, #BakaShrot_Ed25519_PrivateKeySize -; bytes), for a server to open the Hellos sealed for its public key. -; Returns #False if it isn't a usable key. -Procedure.i BakaShrot_Session_LoadHelloKeys(*Keys.BakaShrot_HelloKeys, *PrivateKey) - Protected Ed25519PublicKey.BakaShrot_SessionKey, IsValid.i - - crypto_sign_ed25519_sk_to_pk(@Ed25519PublicKey, *PrivateKey) - IsValid = Bool(crypto_sign_ed25519_pk_to_curve25519(@*Keys\PublicKey[0], @Ed25519PublicKey) = 0) - If IsValid - IsValid = Bool(crypto_sign_ed25519_sk_to_curve25519(@*Keys\SecretKey[0], *PrivateKey) = 0) - EndIf - If Not IsValid - sodium_memzero(*Keys, SizeOf(BakaShrot_HelloKeys)) - EndIf - ProcedureReturn IsValid -EndProcedure - - -; Wipes *Keys. -Procedure BakaShrot_Session_ClearHelloKeys(*Keys.BakaShrot_HelloKeys) - sodium_memzero(*Keys, SizeOf(BakaShrot_HelloKeys)) -EndProcedure - - -; Seals *Data (Size bytes, at least 1) for the server whose Ed25519 public -; key is *ServerPublicKey (#BakaShrot_Ed25519_PublicKeySize bytes), into a -; freshly allocated buffer of Size + #BakaShrot_SealedBoxOverhead bytes, -; its size in *OutSize\i. -; Returns 0 if *ServerPublicKey isn't a valid key, or out of memory. The -; caller owns the returned buffer - free it with FreeMemory. -Procedure.i BakaShrot_Session_SealHello(*ServerPublicKey, *Data, Size.i, *OutSize.Integer) - Protected BoxPublicKey.BakaShrot_SessionKey, *Sealed - - If Not *ServerPublicKey Or Not *Data Or Size < 1 - ProcedureReturn 0 - EndIf - If crypto_sign_ed25519_pk_to_curve25519(@BoxPublicKey, *ServerPublicKey) <> 0 - ProcedureReturn 0 - EndIf - - *Sealed = AllocateMemory(Size + #BakaShrot_SealedBoxOverhead, #PB_Memory_NoClear) - If Not *Sealed - ProcedureReturn 0 - EndIf - If crypto_box_seal(*Sealed, *Data, Size, @BoxPublicKey) <> 0 - FreeMemory(*Sealed) - ProcedureReturn 0 - EndIf - - *OutSize\i = Size + #BakaShrot_SealedBoxOverhead - ProcedureReturn *Sealed -EndProcedure - - -; Opens *Sealed (Size bytes), sealed by BakaShrot_Session_SealHello() for -; *Keys' server, into a freshly allocated buffer, its size in *OutSize\i. -; Returns 0 if it wasn't sealed for this server, was tampered with, is too -; short, or out of memory. The caller owns the returned buffer - free it -; with FreeMemory. -Procedure.i BakaShrot_Session_OpenHello(*Keys.BakaShrot_HelloKeys, *Sealed, Size.i, *OutSize.Integer) - Protected *Data, DataSize.i - - If Not *Sealed Or Size <= #BakaShrot_SealedBoxOverhead - ProcedureReturn 0 - EndIf - - DataSize = Size - #BakaShrot_SealedBoxOverhead - *Data = AllocateMemory(DataSize, #PB_Memory_NoClear) - If Not *Data - ProcedureReturn 0 - EndIf - If crypto_box_seal_open(*Data, *Sealed, Size, @*Keys\PublicKey[0], @*Keys\SecretKey[0]) <> 0 - FreeMemory(*Data) - ProcedureReturn 0 - EndIf - - *OutSize\i = DataSize - ProcedureReturn *Data -EndProcedure - - -; Fills *KeyPair with a fresh key pair, for one connection. Its PublicKey -; goes to the other end. -Procedure BakaShrot_Session_NewKeyPair(*KeyPair.BakaShrot_SessionKeyPair) - crypto_kx_keypair(@*KeyPair\PublicKey[0], @*KeyPair\SecretKey[0]) -EndProcedure - - -; Wipes *KeyPair. -Procedure BakaShrot_Session_ClearKeyPair(*KeyPair.BakaShrot_SessionKeyPair) - sodium_memzero(*KeyPair, SizeOf(BakaShrot_SessionKeyPair)) -EndProcedure - - -; Sets *Cipher up for the client's end of the connection, from the client's -; *KeyPair and the server's public half (*ServerSessionKey, -; #BakaShrot_Session_PublicKeySize bytes). *KeyPair is wiped either way. -; Returns #False if the server's half isn't acceptable: abort then. -Procedure.i BakaShrot_Session_StartClient(*Cipher.BakaShrot_Cipher, *KeyPair.BakaShrot_SessionKeyPair, *ServerSessionKey) - Protected Keys.BakaShrot_SessionDirections, IsReady.i - - BakaShrot_Cipher_Clear(*Cipher) - If crypto_kx_client_session_keys(@Keys\Rx[0], @Keys\Tx[0], @*KeyPair\PublicKey[0], @*KeyPair\SecretKey[0], *ServerSessionKey) = 0 - IsReady = BakaShrot_Cipher_InitWithKeys(*Cipher, @Keys\Tx[0], @Keys\Rx[0]) - EndIf - - sodium_memzero(@Keys, SizeOf(BakaShrot_SessionDirections)) - BakaShrot_Session_ClearKeyPair(*KeyPair) - ProcedureReturn IsReady -EndProcedure - - -; Same for the server's end, from the server's *KeyPair and the client's -; public half (*ClientSessionKey). -Procedure.i BakaShrot_Session_StartServer(*Cipher.BakaShrot_Cipher, *KeyPair.BakaShrot_SessionKeyPair, *ClientSessionKey) - Protected Keys.BakaShrot_SessionDirections, IsReady.i - - BakaShrot_Cipher_Clear(*Cipher) - If crypto_kx_server_session_keys(@Keys\Rx[0], @Keys\Tx[0], @*KeyPair\PublicKey[0], @*KeyPair\SecretKey[0], *ClientSessionKey) = 0 - IsReady = BakaShrot_Cipher_InitWithKeys(*Cipher, @Keys\Tx[0], @Keys\Rx[0]) - EndIf - - sodium_memzero(@Keys, SizeOf(BakaShrot_SessionDirections)) - BakaShrot_Session_ClearKeyPair(*KeyPair) - ProcedureReturn IsReady -EndProcedure diff --git a/Commons/Networking/Connections.pbi b/Commons/Networking/Connections.pbi deleted file mode 100644 index 4937907..0000000 --- a/Commons/Networking/Connections.pbi +++ /dev/null @@ -1,475 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: Connections.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; BakaShrot Connections -; -; What both ends need to keep track of a connection and authenticate it. -; -; Handshake, anything out of order or unexpected aborts the connection. -; The client must already know the server's public key (client.ini's -; ServerPublicKey, a peer section's PublicKey). -; C->S Hello Sealed for the server's public key, only it can -; read it (Session.pbi): the client's identity and -; public key, and the public half of its key pair -; for this connection. -; The server checks they're registered together. -; S->C ChallengeRequest In plain text: random challenge (Base64) and -; nonce, the public half of the server's key pair -; for this connection, and the server's signature -; of the handshake (BakaShrot_MakeHandshakeTranscript()). -; The client checks it with the server's public -; key: it's the right server, and nobody swapped -; the halves. Both ends now have this connection's -; keys, every packet from here on is encrypted -; (Cipher.pbi). -; C->S ChallengeResponse The client's signature of the handshake, and -; the nonce echoed back. -; S->C AuthAccepted The client is authenticated. -; -; Requests, only once authenticated, each one gets one answer: -; C->S PushMessage -> S->C MessagePushed or RequestRefused -; C->S GetLatestMessage -> S->C LatestMessage or RequestRefused -; C->S GetMessages -> S->C Messages (maybe none) or RequestRefused -; C->S QueryRequest -> S->C QueryResult or RequestRefused -; C->S ResolveName -> S->C NameResolved or RequestRefused -; C->S ListNames -> S->C NamesList -; C->S UploadStart -> S->C UploadStarted or RequestRefused -; C->S UploadChunk -> S->C ChunkStored or RequestRefused -; then a PushMessage with the UploadId attaches it to the message -; C->S GetAttachment -> S->C AttachmentChunk or RequestRefused -; Topics and nodes are given by name or id, see Names.pbi. -; A refusal keeps the connection open, a malformed or unexpected packet -; still aborts it. -; -; Replication, only from a peer (see Server/Networking/Peers.pbi), over the -; link it opened to the server: -; P->S SyncStateRequest -> S->P SyncState or RequestRefused -; P->S ReplicateMessages -> S->P MessagePushed (last id) or RequestRefused -; once the messages are caught up: -; P->S MissingAttachmentsRequest -> S->P MissingAttachments or RequestRefused -; P->S ReplicateAttachmentChunk -> S->P ChunkStored or RequestRefused -; -; -; Framing: every packet is sent as its size (4 bytes, little-endian), -; followed by the packet itself, so the receiver knows where it ends. -; Once the connection's cipher is set up, the packet is encrypted first -; (#BakaShrot_Cipher_Overhead bytes more), the size isn't: see -; BakaShrot_SendPacket() and BakaShrot_OpenFrame(). -; Up to #BakaShrot_MaxHandshakePacketSize until the other end authenticated, -; then up to #BakaShrot_MaxPacketSize (BakaShrot_Inbox_Lift()): anyone can -; connect, only those with a key get to make the other end hold big frames. -; ============================================================================ - - -XIncludeFile "../Cryptography/Session.pbi" -XIncludeFile "Packets/HelloPacket.pbi" -XIncludeFile "Packets/ChallengeRequestPacket.pbi" -XIncludeFile "Packets/ChallengeResponsePacket.pbi" -XIncludeFile "Packets/AuthAcceptedPacket.pbi" -XIncludeFile "Packets/PushMessagePacket.pbi" -XIncludeFile "Packets/MessagePushedPacket.pbi" -XIncludeFile "Packets/GetLatestMessagePacket.pbi" -XIncludeFile "Packets/LatestMessagePacket.pbi" -XIncludeFile "Packets/RequestRefusedPacket.pbi" -XIncludeFile "Packets/SyncStateRequestPacket.pbi" -XIncludeFile "Packets/SyncStatePacket.pbi" -XIncludeFile "Packets/ReplicateMessagesPacket.pbi" -XIncludeFile "Packets/QueryRequestPacket.pbi" -XIncludeFile "Packets/QueryResultPacket.pbi" -XIncludeFile "Packets/ResolveNamePacket.pbi" -XIncludeFile "Packets/NameResolvedPacket.pbi" -XIncludeFile "Packets/ListNamesPacket.pbi" -XIncludeFile "Packets/NamesListPacket.pbi" -XIncludeFile "Packets/GetMessagesPacket.pbi" -XIncludeFile "Packets/MessagesPacket.pbi" -XIncludeFile "Packets/UploadStartPacket.pbi" -XIncludeFile "Packets/UploadStartedPacket.pbi" -XIncludeFile "Packets/UploadChunkPacket.pbi" -XIncludeFile "Packets/ChunkStoredPacket.pbi" -XIncludeFile "Packets/GetAttachmentPacket.pbi" -XIncludeFile "Packets/AttachmentChunkPacket.pbi" -XIncludeFile "Packets/MissingAttachmentsRequestPacket.pbi" -XIncludeFile "Packets/MissingAttachmentsPacket.pbi" -XIncludeFile "Packets/ReplicateAttachmentChunkPacket.pbi" - - -; Reads the type of a received packet, to know which decoder to use. -; Returns #BakaShrot_PacketType_None if the packet's base fields are invalid. -Procedure.i BakaShrot_GetPacketType(*Packet, PacketSize.i) - Protected *View.MsgPackData, Base.BakaShrot_PacketBase, IsValid.i - - *View = MsgPackWrapMsgBuffer(*Packet, PacketSize) - If Not *View - ProcedureReturn #BakaShrot_PacketType_None - EndIf - IsValid = BakaShrot_ReadPacketBase(@Base, *View) - MsgPackFree(*View, #False) - - If Not IsValid - ProcedureReturn #BakaShrot_PacketType_None - EndIf - ProcedureReturn Base\PacketType -EndProcedure - - -Enumeration BakaShrot_ConnectionStatuses - ; Connected, the Hello hasn't been sent/received yet. - #BakaShrot_ConnectionStatus_New - ; The challenge was issued, its response hasn't been sent/received yet. - #BakaShrot_ConnectionStatus_Challenged - #BakaShrot_ConnectionStatus_Authenticated - #BakaShrot_ConnectionStatus_Disconnected - #BakaShrot_ConnectionStatus_Aborted -EndEnumeration - - -CompilerIf #BakaShrot_SessionKeySize <> #BakaShrot_Session_PublicKeySize Or #BakaShrot_HandshakeSignatureSize <> #BakaShrot_Ed25519_SignatureSize - CompilerError "Packets.pbi's handshake sizes don't match the cryptography's." -CompilerEndIf - - -Structure BakaShrot_ConnectionMetadata - Status.i - - ; Server side only, trusted once Status is Authenticated: the node from - ; the Hello, and the default topic of its pushes from its client - ; section's DefaultTopic (-1 without one: pushes must name their topic), - ; both as the server's own ids. - DefaultTopicId.l - NodeId.u - ; The client's Ed25519 public key, on both sides. - PublicKey.a[#BakaShrot_Ed25519_PublicKeySize] - ; The server's Ed25519 public key, on both sides. - ServerPublicKey.a[#BakaShrot_Ed25519_PublicKeySize] - - ; TempKey to prevent replay attacks, fresh random data for every connection. - Challenge.a[#BakaShrot_ChallengeSize] - Nonce.a[#BakaShrot_NonceSize] - - ; Public halves of both ends' key pairs for this connection. - ClientSessionKey.a[#BakaShrot_SessionKeySize] - ServerSessionKey.a[#BakaShrot_SessionKeySize] - - ; Set up once both ends have their keys (after the ChallengeRequest), - ; then every packet is encrypted with it. Wiped when the connection ends. - Cipher.BakaShrot_Cipher -EndStructure - - -; What each end signs: proves it holds its identity key, for this -; connection (the challenge, the nonce, both key pairs), to this other end. -; Label tells which end signed it, so one end's signature can't be sent -; back as the other's. -#BakaShrot_TranscriptLabelSize = 16 -#BakaShrot_TranscriptServerLabel = "BakaShrot3 srv" -#BakaShrot_TranscriptClientLabel = "BakaShrot3 cli" - -Structure BakaShrot_HandshakeTranscript - Label.a[#BakaShrot_TranscriptLabelSize] - ClientPublicKey.a[#BakaShrot_Ed25519_PublicKeySize] - ServerPublicKey.a[#BakaShrot_Ed25519_PublicKeySize] - ClientSessionKey.a[#BakaShrot_SessionKeySize] - ServerSessionKey.a[#BakaShrot_SessionKeySize] - Challenge.a[#BakaShrot_ChallengeSize] - Nonce.a[#BakaShrot_NonceSize] -EndStructure - -Structure BakaShrot_ChallengeProof - Message.BakaShrot_HandshakeTranscript - Signature.a[#BakaShrot_Ed25519_SignatureSize] -EndStructure - -; Fills *Proof\Message from *Metadata, as signed by one end: Label is -; #BakaShrot_TranscriptServerLabel or #BakaShrot_TranscriptClientLabel. -Procedure BakaShrot_MakeHandshakeTranscript(*Metadata.BakaShrot_ConnectionMetadata, Label.s, *Proof.BakaShrot_ChallengeProof) - FillMemory(@*Proof\Message, SizeOf(BakaShrot_HandshakeTranscript), 0) - PokeS(@*Proof\Message\Label[0], Label, #BakaShrot_TranscriptLabelSize - 1, #PB_Ascii) - CopyMemory(@*Metadata\PublicKey[0], @*Proof\Message\ClientPublicKey[0], #BakaShrot_Ed25519_PublicKeySize) - CopyMemory(@*Metadata\ServerPublicKey[0], @*Proof\Message\ServerPublicKey[0], #BakaShrot_Ed25519_PublicKeySize) - CopyMemory(@*Metadata\ClientSessionKey[0], @*Proof\Message\ClientSessionKey[0], #BakaShrot_SessionKeySize) - CopyMemory(@*Metadata\ServerSessionKey[0], @*Proof\Message\ServerSessionKey[0], #BakaShrot_SessionKeySize) - CopyMemory(@*Metadata\Challenge[0], @*Proof\Message\Challenge[0], #BakaShrot_ChallengeSize) - CopyMemory(@*Metadata\Nonce[0], @*Proof\Message\Nonce[0], #BakaShrot_NonceSize) -EndProcedure - -; Signs *Proof\Message with *PrivateKey into *Proof\Signature. -Procedure.i BakaShrot_SignHandshake(*Proof.BakaShrot_ChallengeProof, *PrivateKey) - ProcedureReturn EncodeData(@*Proof\Message, SizeOf(BakaShrot_HandshakeTranscript), *PrivateKey, @*Proof\Signature[0]) -EndProcedure - -; #True if *Proof\Signature is *PublicKey's holder's signature of *Proof\Message. -Procedure.i BakaShrot_VerifyHandshake(*Proof.BakaShrot_ChallengeProof, *PublicKey) - ProcedureReturn DecodeData(@*Proof\Message, SizeOf(BakaShrot_HandshakeTranscript), *PublicKey, @*Proof\Signature[0]) -EndProcedure - -; Wipes what's secret in *Metadata, once the connection is over. -Procedure BakaShrot_ClearConnectionMetadata(*Metadata.BakaShrot_ConnectionMetadata) - BakaShrot_Cipher_Clear(@*Metadata\Cipher) -EndProcedure - - -; --- Framing ----------------------------------------------------------------- - -#BakaShrot_FrameHeaderSize = 4 - -; Biggest packet before the other end is authenticated. The handshake's are a -; few hundred bytes. -#BakaShrot_MaxHandshakePacketSize = 4096 - -; A buffer this big or more is freed once emptied, instead of kept for the -; next packets. -#BakaShrot_InboxKeptCapacity = 256 * 1024 - -; How long a send waits for the other end to make room, without a single -; byte going out, before it gives up. Same as how long a client waits for -; each packet (#BakaShrot_Outbound_Timeout). -#BakaShrot_SendStallTimeout = 10000 - -Enumeration BakaShrot_InboxResults - #BakaShrot_Inbox_Incomplete - #BakaShrot_Inbox_Packet - #BakaShrot_Inbox_Invalid -EndEnumeration - -; Received data that hasn't been read as packets yet: Size bytes, from -; Buffer + Start. -Structure BakaShrot_Inbox - *Buffer - Start.i - Size.i - Capacity.i - - ; Biggest packet accepted: #BakaShrot_MaxHandshakePacketSize while 0, - ; #BakaShrot_MaxPacketSize once lifted. - MaxPacketSize.i -EndStructure - - -; Biggest packet *Inbox accepts. -Procedure.i BakaShrot_Inbox_MaxPacketSize(*Inbox.BakaShrot_Inbox) - If *Inbox\MaxPacketSize - ProcedureReturn *Inbox\MaxPacketSize - EndIf - ProcedureReturn #BakaShrot_MaxHandshakePacketSize -EndProcedure - -; Biggest amount of received data waiting to be read as packets, anything -; more aborts the connection: two of the biggest packets. -Procedure.i BakaShrot_Inbox_MaxSize(*Inbox.BakaShrot_Inbox) - ProcedureReturn 2 * (#BakaShrot_FrameHeaderSize + BakaShrot_Inbox_MaxPacketSize(*Inbox)) -EndProcedure - -; Accepts packets up to #BakaShrot_MaxPacketSize (encrypted) from now on. Call -; it once the other end is authenticated, before it can send anything big: -; on the server, before sending AuthAccepted. -Procedure BakaShrot_Inbox_Lift(*Inbox.BakaShrot_Inbox) - *Inbox\MaxPacketSize = #BakaShrot_MaxPacketSize + #BakaShrot_Cipher_Overhead -EndProcedure - - -; Sends *Packet as one frame, encrypted with *Cipher, or in plain text if -; *Cipher is 0: only the Hello (sealed on its own) and the ChallengeRequest. -; Returns #False if the packet is too big, *Cipher isn't set up, or the data -; couldn't be sent. -; PureBasic's sockets don't block: SendNetworkData() returns -1 once the -; system's send buffer is full (EAGAIN on Linux, a few hundred KB), so -1 is -; retried until nothing went out for #BakaShrot_SendStallTimeout. PureBasic -; doesn't tell that from a broken connection, which then takes that long to -; give up on. -Procedure.i BakaShrot_SendPacket(ConnectionId.i, *Packet, PacketSize.i, *Cipher.BakaShrot_Cipher) - Protected *Frame, FrameSize.i, PayloadSize.i, Offset.i, Sent.i, LastProgress.i - - If PacketSize < 1 Or PacketSize > #BakaShrot_MaxPacketSize - ProcedureReturn #False - EndIf - - PayloadSize = PacketSize - If *Cipher - If Not *Cipher\IsReady - ProcedureReturn #False - EndIf - PayloadSize + #BakaShrot_Cipher_Overhead - EndIf - - FrameSize = #BakaShrot_FrameHeaderSize + PayloadSize - *Frame = AllocateMemory(FrameSize, #PB_Memory_NoClear) - If Not *Frame - ProcedureReturn #False - EndIf - PokeL(*Frame, PayloadSize) - If *Cipher - If Not BakaShrot_Cipher_EncryptTo(*Cipher, *Packet, PacketSize, *Frame + #BakaShrot_FrameHeaderSize) - FreeMemory(*Frame) - ProcedureReturn #False - EndIf - Else - CopyMemory(*Packet, *Frame + #BakaShrot_FrameHeaderSize, PacketSize) - EndIf - - LastProgress = ElapsedMilliseconds() - While Offset < FrameSize - Sent = SendNetworkData(ConnectionId, *Frame + Offset, FrameSize - Offset) - If Sent > 0 - Offset + Sent - LastProgress = ElapsedMilliseconds() - ElseIf ElapsedMilliseconds() - LastProgress > #BakaShrot_SendStallTimeout - FreeMemory(*Frame) - ProcedureReturn #False - Else - ; Full, until the other end reads some of it. - Delay(1) - EndIf - Wend - - FreeMemory(*Frame) - ProcedureReturn #True -EndProcedure - - -; Adds received data at the end of *Inbox. -; Returns #False if it would go over BakaShrot_Inbox_MaxSize() or memory ran out. -Procedure.i BakaShrot_Inbox_Append(*Inbox.BakaShrot_Inbox, *Data, DataSize.i) - Protected *NewBuffer, Needed.i, MaxSize.i, NewCapacity.i - - Needed = *Inbox\Size + DataSize - MaxSize = BakaShrot_Inbox_MaxSize(*Inbox) - If Needed > MaxSize - ProcedureReturn #False - EndIf - - ; Out of room at the end: moves what's left to the front, but only if it - ; isn't bigger than the room that frees, so each byte gets moved about - ; once. Otherwise the buffer grows instead, doubling: moving 32 MB under - ; the server's mutex for every 64 KB received, near the limit, would stall - ; every client. At worst it reaches twice BakaShrot_Inbox_MaxSize(). - If *Inbox\Start + Needed > *Inbox\Capacity And *Inbox\Start > 0 And *Inbox\Size <= *Inbox\Start - MoveMemory(*Inbox\Buffer + *Inbox\Start, *Inbox\Buffer, *Inbox\Size) - *Inbox\Start = 0 - EndIf - - If *Inbox\Start + Needed > *Inbox\Capacity - NewCapacity = *Inbox\Capacity * 2 - If NewCapacity < *Inbox\Start + Needed - NewCapacity = *Inbox\Start + Needed - EndIf - If NewCapacity > *Inbox\Start + MaxSize - NewCapacity = *Inbox\Start + MaxSize - EndIf - - If *Inbox\Buffer - *NewBuffer = ReAllocateMemory(*Inbox\Buffer, NewCapacity, #PB_Memory_NoClear) - Else - *NewBuffer = AllocateMemory(NewCapacity, #PB_Memory_NoClear) - EndIf - If Not *NewBuffer - ProcedureReturn #False - EndIf - *Inbox\Buffer = *NewBuffer - *Inbox\Capacity = NewCapacity - EndIf - - CopyMemory(*Data, *Inbox\Buffer + *Inbox\Start + *Inbox\Size, DataSize) - *Inbox\Size + DataSize - - ProcedureReturn #True -EndProcedure - - -; Takes the first complete packet out of *Inbox. -; Returns: -; #BakaShrot_Inbox_Packet *OutPacket\i receives the packet (free it with FreeMemory), *OutSize\i its size. -; #BakaShrot_Inbox_Incomplete The next packet hasn't fully arrived yet. -; #BakaShrot_Inbox_Invalid The frame's size is invalid (too big for now included), or memory ran out. Abort the connection. -Procedure.i BakaShrot_Inbox_TakePacket(*Inbox.BakaShrot_Inbox, *OutPacket.Integer, *OutSize.Integer) - Protected PacketSize.i, *Packet, *Frame - - If *Inbox\Size < #BakaShrot_FrameHeaderSize - ProcedureReturn #BakaShrot_Inbox_Incomplete - EndIf - - ; Checked as soon as the size arrived, not once the whole frame did. - *Frame = *Inbox\Buffer + *Inbox\Start - PacketSize = PeekL(*Frame) & $FFFFFFFF - If PacketSize < 1 Or PacketSize > BakaShrot_Inbox_MaxPacketSize(*Inbox) - ProcedureReturn #BakaShrot_Inbox_Invalid - EndIf - - If *Inbox\Size < #BakaShrot_FrameHeaderSize + PacketSize - ProcedureReturn #BakaShrot_Inbox_Incomplete - EndIf - - *Packet = AllocateMemory(PacketSize, #PB_Memory_NoClear) - If Not *Packet - ProcedureReturn #BakaShrot_Inbox_Invalid - EndIf - CopyMemory(*Frame + #BakaShrot_FrameHeaderSize, *Packet, PacketSize) - - ; What's left stays where it is, Append() moves it when it needs room. - *Inbox\Start + #BakaShrot_FrameHeaderSize + PacketSize - *Inbox\Size - (#BakaShrot_FrameHeaderSize + PacketSize) - If *Inbox\Size = 0 - *Inbox\Start = 0 - If *Inbox\Capacity >= #BakaShrot_InboxKeptCapacity - FreeMemory(*Inbox\Buffer) - *Inbox\Buffer = 0 - *Inbox\Capacity = 0 - EndIf - EndIf - - *OutPacket\i = *Packet - *OutSize\i = PacketSize - ProcedureReturn #BakaShrot_Inbox_Packet -EndProcedure - - -; Turns a frame's content taken out of an inbox (*Frame, FrameSize bytes) -; into the packet: decrypts it with *Cipher once it's set up, as it must -; be from the ChallengeResponse on, else it's the packet already. -; Returns the packet (free it with FreeMemory), its size in *OutSize\i, or -; 0 if it doesn't decrypt: abort the connection. *Frame is freed or -; returned either way. -Procedure.i BakaShrot_OpenFrame(*Cipher.BakaShrot_Cipher, *Frame, FrameSize.i, *OutSize.Integer) - Protected *Packet - - If Not *Cipher\IsReady - *OutSize\i = FrameSize - ProcedureReturn *Frame - EndIf - - *Packet = BakaShrot_Cipher_Decrypt(*Cipher, *Frame, FrameSize, *OutSize) - FreeMemory(*Frame) - If *Packet And *OutSize\i < 1 - ; Never sent: BakaShrot_SendPacket() refuses empty packets. - FreeMemory(*Packet) - *Packet = 0 - EndIf - ProcedureReturn *Packet -EndProcedure - - -; Frees *Inbox's data, and puts its limit back to the handshake's. -Procedure BakaShrot_Inbox_Clear(*Inbox.BakaShrot_Inbox) - If *Inbox\Buffer - FreeMemory(*Inbox\Buffer) - EndIf - *Inbox\Buffer = 0 - *Inbox\Start = 0 - *Inbox\Size = 0 - *Inbox\Capacity = 0 - *Inbox\MaxPacketSize = 0 -EndProcedure diff --git a/Commons/Networking/Names.pbi b/Commons/Networking/Names.pbi deleted file mode 100644 index ffdcccc..0000000 --- a/Commons/Networking/Names.pbi +++ /dev/null @@ -1,169 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: Names.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; BakaShrot Names -; -; Topics and nodes have a numeric id (0-65535) on each server, and a name -; that's the same on every server: replication sends names, and each server -; translates them to its own ids (see Server/Storage/Names.pbi). -; -; Wherever a topic or node is given (config, requests, tools), it's a "ref": -; - a name: 1-64 characters out of A-Z a-z 0-9 _ . -, not only digits, -; compared without case ("Logs" is "logs"), -; - or an id written in digits, 0-65535, which is always that id. -; A topic or node without a name is known by its id in digits, "7". -; ============================================================================ - - -#BakaShrot_MaxNameLength = 64 -#BakaShrot_MaxId = 65535 - - -; #True if Text is made of digits only (and isn't empty). -Procedure.i BakaShrot_IsDigits(Text.s) - Protected i.i, c.i - - If Text = "" - ProcedureReturn #False - EndIf - For i = 1 To Len(Text) - c = Asc(Mid(Text, i, 1)) - If c < '0' Or c > '9' - ProcedureReturn #False - EndIf - Next - ProcedureReturn #True -EndProcedure - - -; #True if Name can be a topic or node name: see the top of this file. -Procedure.i BakaShrot_IsValidName(Name.s) - Protected i.i, c.i - - If Name = "" Or Len(Name) > #BakaShrot_MaxNameLength Or BakaShrot_IsDigits(Name) - ProcedureReturn #False - EndIf - For i = 1 To Len(Name) - c = Asc(Mid(Name, i, 1)) - If Not ((c >= 'a' And c <= 'z') Or (c >= 'A' And c <= 'Z') Or (c >= '0' And c <= '9') Or c = '_' Or c = '.' Or c = '-') - ProcedureReturn #False - EndIf - Next - ProcedureReturn #True -EndProcedure - - -; The id a ref written in digits stands for, or -1 if it isn't one (a name, -; or out of range). Leading zeros are refused, "007" isn't "7". -Procedure.i BakaShrot_RefToId(Ref.s) - Protected Id.i - - If Not BakaShrot_IsDigits(Ref) Or Len(Ref) > 5 - ProcedureReturn -1 - EndIf - Id = Val(Ref) - If Str(Id) <> Ref Or Id > #BakaShrot_MaxId - ProcedureReturn -1 - EndIf - ProcedureReturn Id -EndProcedure - - -; #True if Ref is a valid name or a valid id in digits. -Procedure.i BakaShrot_IsValidRef(Ref.s) - ProcedureReturn Bool(BakaShrot_RefToId(Ref) >= 0 Or BakaShrot_IsValidName(Ref)) -EndProcedure - - -; #True if Ref designates the topic or node Id, named Name ("" if unnamed). -Procedure.i BakaShrot_RefMatches(Ref.s, Id.i, Name.s) - If BakaShrot_IsDigits(Ref) - ProcedureReturn Bool(BakaShrot_RefToId(Ref) = Id) - EndIf - ProcedureReturn Bool(Name <> "" And LCase(Ref) = LCase(Name)) -EndProcedure - - -; --- Wildcards --------------------------------------------------------------- -; Server-side lists of topics and nodes (topic lists, SendNodes, ...) also -; take patterns, like file names: "*" any characters (none included), "?" -; exactly one, everything else itself, without case. "sensors.*", -; "kitchen-??", "*". A pattern only matches names, never ids in digits. - -; #True if Pattern is a valid pattern: has a * or a ?, and otherwise only -; characters a name can have. -Procedure.i BakaShrot_IsValidPattern(Pattern.s) - Protected i.i, c.i - - If Pattern = "" Or Len(Pattern) > #BakaShrot_MaxNameLength - ProcedureReturn #False - EndIf - If Not FindString(Pattern, "*") And Not FindString(Pattern, "?") - ProcedureReturn #False - EndIf - For i = 1 To Len(Pattern) - c = Asc(Mid(Pattern, i, 1)) - If Not ((c >= 'a' And c <= 'z') Or (c >= 'A' And c <= 'Z') Or (c >= '0' And c <= '9') Or c = '_' Or c = '.' Or c = '-' Or c = '*' Or c = '?') - ProcedureReturn #False - EndIf - Next - ProcedureReturn #True -EndProcedure - - -; #True if Name matches Pattern (see above), without case. Ids in digits -; never match. -Procedure.i BakaShrot_GlobMatch(Pattern.s, Name.s) - Protected p.i = 1, n.i = 1, StarP.i = 0, StarN.i = 0 - Protected PLen.i, NLen.i, pc.s - - If Not BakaShrot_IsValidName(Name) - ProcedureReturn #False - EndIf - Pattern = LCase(Pattern) - Name = LCase(Name) - PLen = Len(Pattern) - NLen = Len(Name) - - ; Greedy with backtracking to the last "*": linear enough for 64 characters. - While n <= NLen - If p <= PLen - pc = Mid(Pattern, p, 1) - Else - pc = "" - EndIf - If pc = "*" - StarP = p - StarN = n - p + 1 - ElseIf pc <> "" And (pc = "?" Or pc = Mid(Name, n, 1)) - p + 1 - n + 1 - ElseIf StarP - p = StarP + 1 - StarN + 1 - n = StarN - Else - ProcedureReturn #False - EndIf - Wend - While p <= PLen And Mid(Pattern, p, 1) = "*" - p + 1 - Wend - ProcedureReturn Bool(p > PLen) -EndProcedure diff --git a/Commons/Networking/Outbound.pbi b/Commons/Networking/Outbound.pbi deleted file mode 100644 index 8ed89f4..0000000 --- a/Commons/Networking/Outbound.pbi +++ /dev/null @@ -1,368 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: Outbound.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; BakaShrot Outbound connections -; -; The client side of a connection: connecting to a server and running the -; handshake from Connections.pbi as the one being authenticated, then -; sending requests (BakaShrot_Outbound_Send()) and waiting for the answers -; (BakaShrot_Outbound_WaitPacket()), encrypted for this connection. -; Used by the client DLL, and by the server to link to its peers. -; -; A BakaShrot_Outbound must only be used by one thread at a time. -; ============================================================================ - -XIncludeFile "Connections.pbi" -XIncludeFile "SocketWait.pbi" - - -#BakaShrot_Outbound_ReceiveBufferSize = 65536 - -; How long the server gets to send each packet, handshake or answer. -#BakaShrot_Outbound_Timeout = 10000 - - -; Who to authenticate as. -Structure BakaShrot_OutboundIdentity - ; The node it writes as, a name or an id in digits (Names.pbi), resolved - ; by the server, which must allow it for this key. - Node.s - - ; Ed25519 public key (Base64), sent in the Hello. - PublicKey.s - - ; Ed25519 private key, #BakaShrot_Ed25519_PrivateKeySize bytes, used to - ; answer the challenge. Must stay valid while connecting. - *PrivateKey -EndStructure - - -Structure BakaShrot_Outbound - ; 0 when not connected. - ConnectionId.i - Inbox.BakaShrot_Inbox - Metadata.BakaShrot_ConnectionMetadata - - ; Optional, set by the owner: while it points to a non-zero value, waits - ; for the server's packets give up right away, as if they timed out. - ; Lets a server stop its peer links without waiting out their timeouts. - *StopRequested.Integer - - ; Why BakaShrot_Outbound_Connect() failed, a #BakaShrot_Error_* of - ; Client/BakaShrot_ErrorCodes.pbi, 0 once it succeeded. - LastError.l -EndStructure - - -; Closes *Outbound's connection, if any, and sets its status to Status. -Procedure BakaShrot_Outbound_Close(*Outbound.BakaShrot_Outbound, Status.i) - If *Outbound\ConnectionId - CloseNetworkConnection(*Outbound\ConnectionId) - EndIf - *Outbound\ConnectionId = 0 - BakaShrot_Inbox_Clear(@*Outbound\Inbox) - BakaShrot_ClearConnectionMetadata(@*Outbound\Metadata) - *Outbound\Metadata\Status = Status -EndProcedure - - -; Sends *Packet to the server, encrypted for this connection. -; Returns #False if it couldn't be sent: close the connection then. -Procedure.i BakaShrot_Outbound_Send(*Outbound.BakaShrot_Outbound, *Packet, PacketSize.i) - If Not *Outbound\ConnectionId - ProcedureReturn #False - EndIf - ProcedureReturn BakaShrot_SendPacket(*Outbound\ConnectionId, *Packet, PacketSize, @*Outbound\Metadata\Cipher) -EndProcedure - - -; Waits for the next packet from the server, for up to TimeoutMs, decrypted -; once the connection's cipher is set up. -; Returns the packet (free it with FreeMemory) with its size in *OutSize\i, -; or 0 if the server disconnected, sent an invalid frame, one that doesn't -; decrypt or too much data, timed out, or the owner asked to stop (see -; *StopRequested). -Procedure.i BakaShrot_Outbound_WaitPacket(*Outbound.BakaShrot_Outbound, *OutSize.Integer, TimeoutMs.i) - Protected *Packet = 0, *Buffer, Result.i, Received.i, StartTime.i, WaitMs.i - - *Buffer = AllocateMemory(#BakaShrot_Outbound_ReceiveBufferSize) - If Not *Buffer - ProcedureReturn 0 - EndIf - - StartTime = ElapsedMilliseconds() - - Repeat - Result = BakaShrot_Inbox_TakePacket(@*Outbound\Inbox, @*Packet, *OutSize) - If Result = #BakaShrot_Inbox_Packet Or Result = #BakaShrot_Inbox_Invalid - Break - EndIf - - If ElapsedMilliseconds() - StartTime > TimeoutMs - Break - EndIf - - If *Outbound\StopRequested - If *Outbound\StopRequested\i - Break - EndIf - EndIf - - Select NetworkClientEvent(*Outbound\ConnectionId) - - Case #PB_NetworkEvent_Data - Received = ReceiveNetworkData(*Outbound\ConnectionId, *Buffer, #BakaShrot_Outbound_ReceiveBufferSize) - If Received <= 0 - Break - EndIf - If Not BakaShrot_Inbox_Append(@*Outbound\Inbox, *Buffer, Received) - Break - EndIf - - Case #PB_NetworkEvent_Disconnect - Break - - Default - ; Sleeps until the server sends something, waking up at least - ; every 50 ms to check the timeout and *StopRequested. - WaitMs = TimeoutMs - (ElapsedMilliseconds() - StartTime) - If WaitMs > 50 - WaitMs = 50 - EndIf - If WaitMs < 1 - WaitMs = 1 - EndIf - BakaShrot_WaitSocket(ConnectionID(*Outbound\ConnectionId), WaitMs) - - EndSelect - ForEver - - FreeMemory(*Buffer) - If *Packet - *Packet = BakaShrot_OpenFrame(@*Outbound\Metadata\Cipher, *Packet, *OutSize\i, *OutSize) - EndIf - ProcedureReturn *Packet -EndProcedure - - -; Connects to Host:Port and authenticates as *Identity, to the server whose -; Ed25519 public key is *ServerPublicKey (#BakaShrot_Ed25519_PublicKeySize -; bytes): sends the Hello sealed for that key, checks the server's -; signature in the challenge it gets back, sets up the connection's cipher, -; signs the handshake, then waits for the server to accept it. -; Fails if already connected, if *Identity's public key isn't valid Base64, -; if the server can't prove it holds *ServerPublicKey's private key, or if -; anything in the handshake is out of order or unexpected, in which case -; the connection is closed. -Procedure.i BakaShrot_Outbound_Connect(*Outbound.BakaShrot_Outbound, Host.s, Port.i, *Identity.BakaShrot_OutboundIdentity, *ServerPublicKey) - Protected *Packet, PacketSize.Integer, *View.MsgPackData, Sent.i, *Sealed, SealedSize.Integer - Protected Hello.BakaShrot_AuthHello - Protected *Request.BakaShrot_ChallengeRequest - Protected Response.BakaShrot_ChallengeResponse - Protected *Accepted.BakaShrot_AuthAccepted - Protected Proof.BakaShrot_ChallengeProof - Protected KeyPair.BakaShrot_SessionKeyPair - Protected ChallengeDecoded.i, ServerProved.i - - *Outbound\LastError = #BakaShrot_Error_None - If *Outbound\ConnectionId - *Outbound\LastError = #BakaShrot_Error_AlreadyConnected - ProcedureReturn #False - EndIf - - If Not *ServerPublicKey Or Port < 1 Or Port > 65535 - *Outbound\LastError = #BakaShrot_Error_InvalidArgument - ProcedureReturn #False - EndIf - - ; Only needed before PureBasic 6.00. - CompilerIf #PB_Compiler_Version < 600 - If Not InitNetwork() - *Outbound\LastError = #BakaShrot_Error_Internal - ProcedureReturn #False - EndIf - CompilerEndIf - - If Not InitCryptography() - *Outbound\LastError = #BakaShrot_Error_Internal - ProcedureReturn #False - EndIf - - BakaShrot_ClearConnectionMetadata(@*Outbound\Metadata) - ClearStructure(@*Outbound\Metadata, BakaShrot_ConnectionMetadata) - If Not DecodeKeyFromString(*Identity\PublicKey, @*Outbound\Metadata\PublicKey[0], #BakaShrot_Ed25519_PublicKeySize) - *Outbound\Metadata\Status = #BakaShrot_ConnectionStatus_Aborted - *Outbound\LastError = #BakaShrot_Error_InvalidArgument - ProcedureReturn #False - EndIf - CopyMemory(*ServerPublicKey, @*Outbound\Metadata\ServerPublicKey[0], #BakaShrot_Ed25519_PublicKeySize) - - *Outbound\ConnectionId = OpenNetworkConnection(Host, Port, #PB_Network_TCP | #PB_Network_IPv4) - If Not *Outbound\ConnectionId - *Outbound\Metadata\Status = #BakaShrot_ConnectionStatus_Aborted - *Outbound\LastError = #BakaShrot_Error_ConnectFailed - ProcedureReturn #False - EndIf - *Outbound\Metadata\Status = #BakaShrot_ConnectionStatus_New - - ; This connection's key pair, the public half goes in the Hello. - BakaShrot_Session_NewKeyPair(@KeyPair) - CopyMemory(@KeyPair\PublicKey[0], @*Outbound\Metadata\ClientSessionKey[0], #BakaShrot_SessionKeySize) - - - ; 1. Hello, sealed for the server - Hello\ClientNode = *Identity\Node - Hello\ClientPubKeyB64 = *Identity\PublicKey - CopyMemory(@KeyPair\PublicKey[0], @Hello\ClientSessionKey[0], #BakaShrot_SessionKeySize) - - *Outbound\LastError = #BakaShrot_Error_Internal - *Packet = BakaShrot_HelloPacket_Encode(@Hello, @PacketSize) - If Not *Packet - Goto ConnectFailed - EndIf - *Sealed = BakaShrot_Session_SealHello(*ServerPublicKey, *Packet, PacketSize\i, @SealedSize) - FreeMemory(*Packet) - If Not *Sealed - Goto ConnectFailed - EndIf - *Outbound\LastError = #BakaShrot_Error_ConnectFailed - Sent = BakaShrot_SendPacket(*Outbound\ConnectionId, *Sealed, SealedSize\i, 0) - FreeMemory(*Sealed) - If Not Sent - Goto ConnectFailed - EndIf - - - ; 2. Challenge request, in plain text. No answer: the server closed the - ; connection, it couldn't open the Hello or doesn't allow this key and - ; node (or speaks another protocol version). - *Outbound\LastError = #BakaShrot_Error_AuthRejected - *Packet = BakaShrot_Outbound_WaitPacket(*Outbound, @PacketSize, #BakaShrot_Outbound_Timeout) - If Not *Packet - Goto ConnectFailed - EndIf - - *Outbound\LastError = #BakaShrot_Error_ProtocolError - - *Request = 0 - *View = MsgPackWrapMsgBuffer(*Packet, PacketSize\i) - If *View - *Request = BakaShrot_ChallengeRequestPacket_Decode(*View) - MsgPackFree(*View, #False) - EndIf - FreeMemory(*Packet) - If Not *Request - Goto ConnectFailed - EndIf - - ChallengeDecoded = DecodeKeyFromString(*Request\ChallengeB64, @*Outbound\Metadata\Challenge[0], #BakaShrot_ChallengeSize) - CopyMemory(@*Request\Nonce[0], @*Outbound\Metadata\Nonce[0], #BakaShrot_NonceSize) - CopyMemory(@*Request\ServerSessionKey[0], @*Outbound\Metadata\ServerSessionKey[0], #BakaShrot_SessionKeySize) - CopyMemory(@*Request\ServerSignature[0], @Proof\Signature[0], #BakaShrot_Ed25519_SignatureSize) - FreeStructure(*Request) - If Not ChallengeDecoded - Goto ConnectFailed - EndIf - - ; Only the server holding *ServerPublicKey's private key could sign this - ; connection's halves and challenge. - BakaShrot_MakeHandshakeTranscript(@*Outbound\Metadata, #BakaShrot_TranscriptServerLabel, @Proof) - ServerProved = BakaShrot_VerifyHandshake(@Proof, *ServerPublicKey) - If Not ServerProved - *Outbound\LastError = #BakaShrot_Error_ServerNotVerified - Goto ConnectFailed - EndIf - - ; Every packet is encrypted from now on. - *Outbound\LastError = #BakaShrot_Error_Internal - If Not BakaShrot_Session_StartClient(@*Outbound\Metadata\Cipher, @KeyPair, @*Outbound\Metadata\ServerSessionKey[0]) - Goto ConnectFailed - EndIf - - *Outbound\Metadata\Status = #BakaShrot_ConnectionStatus_Challenged - - - ; 3. Challenge response - BakaShrot_MakeHandshakeTranscript(@*Outbound\Metadata, #BakaShrot_TranscriptClientLabel, @Proof) - If Not BakaShrot_SignHandshake(@Proof, *Identity\PrivateKey) - Goto ConnectFailed - EndIf - - Response\ChallengeResponseB64 = EncodeKeyToString(@Proof\Signature[0], #BakaShrot_Ed25519_SignatureSize) - CopyMemory(@*Outbound\Metadata\Nonce[0], @Response\Nonce[0], #BakaShrot_NonceSize) - - *Packet = BakaShrot_ChallengeResponsePacket_Encode(@Response, @PacketSize) - If Not *Packet - Goto ConnectFailed - EndIf - *Outbound\LastError = #BakaShrot_Error_AuthRejected - Sent = BakaShrot_Outbound_Send(*Outbound, *Packet, PacketSize\i) - FreeMemory(*Packet) - If Not Sent - Goto ConnectFailed - EndIf - - - ; 4. Accepted. No answer: the server didn't accept this key's signature. - *Packet = BakaShrot_Outbound_WaitPacket(*Outbound, @PacketSize, #BakaShrot_Outbound_Timeout) - If Not *Packet - Goto ConnectFailed - EndIf - *Outbound\LastError = #BakaShrot_Error_ProtocolError - - *Accepted = 0 - *View = MsgPackWrapMsgBuffer(*Packet, PacketSize\i) - If *View - *Accepted = BakaShrot_AuthAcceptedPacket_Decode(*View) - MsgPackFree(*View, #False) - EndIf - FreeMemory(*Packet) - If Not *Accepted - Goto ConnectFailed - EndIf - FreeStructure(*Accepted) - - ; The server's answers may be big from now on. - BakaShrot_Inbox_Lift(@*Outbound\Inbox) - *Outbound\Metadata\Status = #BakaShrot_ConnectionStatus_Authenticated - *Outbound\LastError = #BakaShrot_Error_None - ProcedureReturn #True - - - ConnectFailed: - BakaShrot_Session_ClearKeyPair(@KeyPair) - BakaShrot_Outbound_Close(*Outbound, #BakaShrot_ConnectionStatus_Aborted) - ProcedureReturn #False -EndProcedure - - -; Returns #True while *Outbound is connected, notices when the server closed -; the connection. -; Data the server sent is left to read, only a disconnect is acted upon. -Procedure.i BakaShrot_Outbound_IsConnected(*Outbound.BakaShrot_Outbound) - If Not *Outbound\ConnectionId - ProcedureReturn #False - EndIf - - If NetworkClientEvent(*Outbound\ConnectionId) = #PB_NetworkEvent_Disconnect - BakaShrot_Outbound_Close(*Outbound, #BakaShrot_ConnectionStatus_Disconnected) - ProcedureReturn #False - EndIf - - ProcedureReturn #True -EndProcedure diff --git a/Commons/Networking/Packets.pbi b/Commons/Networking/Packets.pbi deleted file mode 100644 index e08910d..0000000 --- a/Commons/Networking/Packets.pbi +++ /dev/null @@ -1,229 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: Packets.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -XIncludeFile "../../Includes/PB-MessagePack/Includes/MessagePack.pbi" -XIncludeFile "Names.pbi" -; The refusal codes (RequestRefused) and the client's error codes. -XIncludeFile "../../Client/BakaShrot_ErrorCodes.pbi" - - -; Represents the root of all BakaShrot packets. -; Any packets below this size MUST be thrown out. -Structure BakaShrot_PacketBase - Magic.l - Version.l - PacketType.l -EndStructure - - -; Fixed values every BakaShrot_PacketBase must carry. Checked on decode so a -; packet from a different protocol/version is thrown out instead of being -; misparsed. -#BakaShrot_ProtocolMagic = $42534854 ; "BSHT" -; 2: topics and nodes by name (Commons/Networking/Names.pbi), see Design/Packets.md. -; 3: the Hello sealed for the server, a key per connection, everything after -; the ChallengeRequest encrypted (Connections.pbi). Messages carry when -; they were pushed (PushedAt). -; 4: attachments (Design/Attachments.md). -; 5: the Hello carries the client's node only: its default topic is the -; server's to say (DefaultTopic in its client section). -; 6: RequestRefused carries a Code (Client/BakaShrot_ErrorCodes.pbi). -#BakaShrot_ProtocolVersion = 6 - -; Size in bytes of the nonce sent in a challenge request and echoed in its response. -; It MUST be filled with CryptRandomData(), never reused, and be checked against the one the -; server issued for that connection, so a captured response can't be replayed. -#BakaShrot_NonceSize = 32 - -; Size in bytes of the random challenge sent Base64-encoded in a challenge request. -; The client proves it holds its private key by signing the challenge followed by the nonce. -#BakaShrot_ChallengeSize = 32 - -; Size in bytes of the public half of a connection's key pair, sent by the -; client in its Hello and by the server in its ChallengeRequest -; (#BakaShrot_Session_PublicKeySize, Commons/Cryptography/Session.pbi). -#BakaShrot_SessionKeySize = 32 - -; Size in bytes of the server's signature in a ChallengeRequest -; (#BakaShrot_Ed25519_SignatureSize). -#BakaShrot_HandshakeSignatureSize = 64 - -; When a message was pushed: milliseconds since 1970-01-01 00:00:00 UTC, set -; by the server it was pushed to, and kept as is by every server it's -; replicated to. Anything outside 1 to #BakaShrot_MaxTimestamp (9999-12-31) -; is invalid on the wire. -#BakaShrot_MaxTimestamp = 253402300799999 - -Procedure.i BakaShrot_IsValidTimestamp(Timestamp.q) - ProcedureReturn Bool(Timestamp >= 1 And Timestamp <= #BakaShrot_MaxTimestamp) -EndProcedure - -; Attachments (Design/Attachments.md): at most one per message, sent and -; stored in parts of #BakaShrot_AttachmentChunkSize bytes (the last one what's -; left), checked with their SHA-256. #BakaShrot_MaxAttachmentSize is the -; protocol's limit, each server sets its own ([BakaShrot.Server] -; MaxAttachmentSize). -#BakaShrot_AttachmentChunkSize = 1048576 -#BakaShrot_MaxAttachmentSize = 1099511627776 -#BakaShrot_MaxAttachmentChunks = #BakaShrot_MaxAttachmentSize / #BakaShrot_AttachmentChunkSize -#BakaShrot_Sha256Size = 32 - -; How many parts Size bytes take. -Procedure.q BakaShrot_AttachmentChunkCount(Size.q) - ProcedureReturn (Size + #BakaShrot_AttachmentChunkSize - 1) / #BakaShrot_AttachmentChunkSize -EndProcedure - -; How big part Index of Size bytes is, 0 if there's no such part. -Procedure.i BakaShrot_AttachmentChunkBytes(Size.q, Index.q) - Protected Left.q = Size - Index * #BakaShrot_AttachmentChunkSize - If Index < 0 Or Left <= 0 - ProcedureReturn 0 - ElseIf Left > #BakaShrot_AttachmentChunkSize - ProcedureReturn #BakaShrot_AttachmentChunkSize - EndIf - ProcedureReturn Left -EndProcedure - -; Biggest packet accepted on the wire once authenticated, anything bigger -; aborts the connection. Before that, only #BakaShrot_MaxHandshakePacketSize -; (Connections.pbi). -#BakaShrot_MaxPacketSize = 16 * 1024 * 1024 - -; Biggest message a client may push (its JSON, in UTF-8 bytes). Leaves room -; for the fields around it, so a stored message fits in every packet that -; carries one: LatestMessage, a ReplicateMessages batch of one. -#BakaShrot_MaxMessageSize = #BakaShrot_MaxPacketSize - 4096 - -Enumeration BakaShrot_PacketTypes - ; Safety fallback value, should be dropped when encountered - #BakaShrot_PacketType_None = 0 - - ; 1-3 were used by the removed AuthenticationPacket.pbi, don't reuse them. - #BakaShrot_PacketType_ClientHello = 4 - #BakaShrot_PacketType_ChallengeRequest = 5 - #BakaShrot_PacketType_ChallengeResponse = 6 - #BakaShrot_PacketType_AuthAccepted = 7 - - ; Only accepted once authenticated. - #BakaShrot_PacketType_PushMessage = 8 - #BakaShrot_PacketType_MessagePushed = 9 - #BakaShrot_PacketType_GetLatestMessage = 10 - #BakaShrot_PacketType_LatestMessage = 11 - #BakaShrot_PacketType_RequestRefused = 12 - - ; Replication, only accepted from peers once authenticated. - #BakaShrot_PacketType_SyncStateRequest = 13 - #BakaShrot_PacketType_SyncState = 14 - #BakaShrot_PacketType_ReplicateMessages = 15 - - ; Raw read-only SQL, only accepted once authenticated, from clients allowed to. - #BakaShrot_PacketType_QueryRequest = 16 - #BakaShrot_PacketType_QueryResult = 17 - - ; Name <-> id of a topic or node, only accepted once authenticated. - #BakaShrot_PacketType_ResolveName = 18 - #BakaShrot_PacketType_NameResolved = 19 - - ; Every topic or node the client may see, only accepted once authenticated. - #BakaShrot_PacketType_ListNames = 20 - #BakaShrot_PacketType_NamesList = 21 - - ; A run of messages of a topic/node, only accepted once authenticated. - #BakaShrot_PacketType_GetMessages = 22 - #BakaShrot_PacketType_Messages = 23 - - ; Attachments, only accepted once authenticated: uploading one (before - ; its PushMessage), and reading one, in parts. - #BakaShrot_PacketType_UploadStart = 24 - #BakaShrot_PacketType_UploadStarted = 25 - #BakaShrot_PacketType_UploadChunk = 26 - #BakaShrot_PacketType_ChunkStored = 27 - #BakaShrot_PacketType_GetAttachment = 28 - #BakaShrot_PacketType_AttachmentChunk = 29 - - ; Replicating attachments, only accepted from peers, once their messages are. - #BakaShrot_PacketType_MissingAttachmentsRequest = 30 - #BakaShrot_PacketType_MissingAttachments = 31 - #BakaShrot_PacketType_ReplicateAttachmentChunk = 32 -EndEnumeration - - -; Checks and reads the given MsgPack data into a packet structure's common fields. -; The caller can handle the MsgPack data validation however it see fit. -; On success, the structure's fields will be populated, and the MsgPack structure will be ready to ready the packet's remaining fields. -; On failure, all data should be discarded and be treated as tainted. -Procedure.b BakaShrot_ReadPacketBase(*PacketStruct.BakaShrot_PacketBase, *MsgPackData.MsgPackData) - ; Returns true on success, false otherwise - ; The caller will usually drop all data and tell the remote client to fuck off if this fails. - Protected TempValue.q - - If Not *PacketStruct Or Not *MsgPackData - ProcedureReturn #False - EndIf - - ; Magic - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - ProcedureReturn #False - EndIf - TempValue = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or TempValue <> #BakaShrot_ProtocolMagic - ProcedureReturn #False - EndIf - *PacketStruct\Magic = TempValue - - ; Version - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - ProcedureReturn #False - EndIf - TempValue = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or TempValue <> #BakaShrot_ProtocolVersion - ProcedureReturn #False - EndIf - *PacketStruct\Version = TempValue - - ; PacketType - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - ProcedureReturn #False - EndIf - TempValue = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or TempValue <= #BakaShrot_PacketType_None Or TempValue > 2147483647 - ProcedureReturn #False - EndIf - *PacketStruct\PacketType = TempValue - - ProcedureReturn #True -EndProcedure - -; Writes a packet structure's common fields into the given MsgPack data. -; On success, the MsgPack structure will be ready to write the packet's remaining fields. -; On failure, the MsgPack data should be discarded and be treated as tainted. -Procedure.b BakaShrot_WritePacketBase(*PacketStruct.BakaShrot_PacketBase, *MsgPackData.MsgPackData) - ; Returns true on success, false otherwise - If MsgPackWriteInteger(*MsgPackData, *PacketStruct\Magic) <> #MsgPack_Error_Success - ProcedureReturn #False - EndIf - - If MsgPackWriteInteger(*MsgPackData, *PacketStruct\Version) <> #MsgPack_Error_Success - ProcedureReturn #False - EndIf - - If MsgPackWriteInteger(*MsgPackData, *PacketStruct\PacketType) <> #MsgPack_Error_Success - ProcedureReturn #False - EndIf - - ProcedureReturn #True -EndProcedure diff --git a/Commons/Networking/Packets/AttachmentChunkPacket.pbi b/Commons/Networking/Packets/AttachmentChunkPacket.pbi deleted file mode 100644 index afe9027..0000000 --- a/Commons/Networking/Packets/AttachmentChunkPacket.pbi +++ /dev/null @@ -1,212 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: AttachmentChunkPacket.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; ... -; ============================================================================ - - -XIncludeFile "../Packets.pbi" - -; S2C, answers a GetAttachment: part ChunkIndex of the attachment of -; TopicId:NodeId#MessageId (the server's ids), Size bytes in all, in parts of -; #BakaShrot_AttachmentChunkSize, whose SHA-256 is Sha256. -Structure BakaShrot_AttachmentChunk Extends BakaShrot_PacketBase - TopicId.l - NodeId.l - MessageId.q - Size.q - Sha256.a[#BakaShrot_Sha256Size] - ChunkIndex.l - *Data - DataSize.l -EndStructure - - -; Encodes *Chunk into a freshly allocated buffer, its base fields are set by this procedure. -; *OutSize receives its size in bytes. -; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory. -Procedure.i BakaShrot_AttachmentChunkPacket_Encode(*Chunk.BakaShrot_AttachmentChunk, *OutSize.Integer) - Protected *MsgPackData.MsgPackData, *Buffer - - *Chunk\Magic = #BakaShrot_ProtocolMagic - *Chunk\Version = #BakaShrot_ProtocolVersion - *Chunk\PacketType = #BakaShrot_PacketType_AttachmentChunk - - If *Chunk\TopicId < 0 Or *Chunk\TopicId > #BakaShrot_MaxId Or *Chunk\NodeId < 0 Or *Chunk\NodeId > #BakaShrot_MaxId Or *Chunk\MessageId < 1 Or *Chunk\Size < 1 Or *Chunk\Size > #BakaShrot_MaxAttachmentSize Or *Chunk\ChunkIndex < 0 Or *Chunk\ChunkIndex > #BakaShrot_MaxAttachmentChunks Or Not *Chunk\Data Or *Chunk\DataSize < 1 Or *Chunk\DataSize > #BakaShrot_AttachmentChunkSize - ProcedureReturn 0 - EndIf - - *MsgPackData = MsgPackCreate(#BakaShrot_AttachmentChunkSize + 256) - If Not *MsgPackData - ProcedureReturn 0 - EndIf - - If Not BakaShrot_WritePacketBase(*Chunk, *MsgPackData) - Goto EncodeFailed - EndIf - - If MsgPackWriteInteger(*MsgPackData, *Chunk\TopicId) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteInteger(*MsgPackData, *Chunk\NodeId) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteInteger(*MsgPackData, *Chunk\MessageId) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteInteger(*MsgPackData, *Chunk\Size) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteBinary(*MsgPackData, @*Chunk\Sha256[0], #BakaShrot_Sha256Size) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteInteger(*MsgPackData, *Chunk\ChunkIndex) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteBinary(*MsgPackData, *Chunk\Data, *Chunk\DataSize) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - ; Frees *MsgPackData on success, leaves it untouched on failure. - *Buffer = MsgPackFinalize(*MsgPackData) - If Not *Buffer - Goto EncodeFailed - EndIf - - *OutSize\i = MemorySize(*Buffer) - ProcedureReturn *Buffer - - EncodeFailed: - MsgPackFree(*MsgPackData, #True) - ProcedureReturn 0 -EndProcedure - -; Frees a decoded *Chunk and the data it holds. -Procedure BakaShrot_AttachmentChunkPacket_Free(*Chunk.BakaShrot_AttachmentChunk) - If Not *Chunk - ProcedureReturn - EndIf - If *Chunk\Data - FreeMemory(*Chunk\Data) - EndIf - FreeStructure(*Chunk) -EndProcedure - -; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct. -; *MsgPackData stays owned by the caller, and should be discarded on failure. -; Returns 0 on failure, the caller owns the returned struct - free it with BakaShrot_AttachmentChunkPacket_Free(). -Procedure.i BakaShrot_AttachmentChunkPacket_Decode(*MsgPackData.MsgPackData) - Protected *Chunk.BakaShrot_AttachmentChunk, Value.q, ReadSize.q - - *Chunk = AllocateStructure(BakaShrot_AttachmentChunk) - If Not *Chunk - ProcedureReturn 0 - EndIf - - ; The base parser doesn't check which packet it is, that's on us. - If Not BakaShrot_ReadPacketBase(*Chunk, *MsgPackData) Or *Chunk\PacketType <> #BakaShrot_PacketType_AttachmentChunk - Goto DecodeFailed - EndIf - - ; TopicId - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - Value = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > #BakaShrot_MaxId - Goto DecodeFailed - EndIf - *Chunk\TopicId = Value - - ; NodeId - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - Value = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > #BakaShrot_MaxId - Goto DecodeFailed - EndIf - *Chunk\NodeId = Value - - ; MessageId - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - Value = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 1 - Goto DecodeFailed - EndIf - *Chunk\MessageId = Value - - ; Size - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - Value = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 1 Or Value > #BakaShrot_MaxAttachmentSize - Goto DecodeFailed - EndIf - *Chunk\Size = Value - - ; Sha256 - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary - Goto DecodeFailed - EndIf - ; Anything bigger than the struct's array is rejected by MsgPackReadBinary, anything smaller by the size check. - ReadSize = MsgPackReadBinary(*MsgPackData, @*Chunk\Sha256[0], #BakaShrot_Sha256Size) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or ReadSize <> #BakaShrot_Sha256Size - Goto DecodeFailed - EndIf - - ; ChunkIndex - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - Value = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > #BakaShrot_MaxAttachmentChunks - Goto DecodeFailed - EndIf - *Chunk\ChunkIndex = Value - - ; Data - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary - Goto DecodeFailed - EndIf - ; A copy, freed with the packet (_Free()). - *Chunk\Data = MsgPackCopyBinary(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not *Chunk\Data - Goto DecodeFailed - EndIf - *Chunk\DataSize = MemorySize(*Chunk\Data) - If *Chunk\DataSize > #BakaShrot_AttachmentChunkSize - Goto DecodeFailed - EndIf - - ProcedureReturn *Chunk - - ; Everything read so far is tainted, drop it. - DecodeFailed: - BakaShrot_AttachmentChunkPacket_Free(*Chunk) - ProcedureReturn 0 -EndProcedure diff --git a/Commons/Networking/Packets/AuthAcceptedPacket.pbi b/Commons/Networking/Packets/AuthAcceptedPacket.pbi deleted file mode 100644 index 6a7d18c..0000000 --- a/Commons/Networking/Packets/AuthAcceptedPacket.pbi +++ /dev/null @@ -1,82 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: AuthAcceptedPacket.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; ... -; ============================================================================ - - -XIncludeFile "../Packets.pbi" - -; S2C, tells the client its challenge response was accepted and it is now authenticated. -; Only carries the base fields. -Structure BakaShrot_AuthAccepted Extends BakaShrot_PacketBase -EndStructure - - -; Encodes *Accepted into a freshly allocated buffer, its base fields are set by this procedure. -; *OutSize receives its size in bytes. -; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory. -Procedure.i BakaShrot_AuthAcceptedPacket_Encode(*Accepted.BakaShrot_AuthAccepted, *OutSize.Integer) - Protected *MsgPackData.MsgPackData, *Buffer - - *Accepted\Magic = #BakaShrot_ProtocolMagic - *Accepted\Version = #BakaShrot_ProtocolVersion - *Accepted\PacketType = #BakaShrot_PacketType_AuthAccepted - - *MsgPackData = MsgPackCreate(16) - If Not *MsgPackData - ProcedureReturn 0 - EndIf - - If Not BakaShrot_WritePacketBase(*Accepted, *MsgPackData) - Goto EncodeFailed - EndIf - - ; Frees *MsgPackData on success, leaves it untouched on failure. - *Buffer = MsgPackFinalize(*MsgPackData) - If Not *Buffer - Goto EncodeFailed - EndIf - - *OutSize\i = MemorySize(*Buffer) - ProcedureReturn *Buffer - - EncodeFailed: - MsgPackFree(*MsgPackData, #True) - ProcedureReturn 0 -EndProcedure - -; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct. -; *MsgPackData stays owned by the caller, and should be discarded on failure. -; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure. -Procedure.i BakaShrot_AuthAcceptedPacket_Decode(*MsgPackData.MsgPackData) - Protected *Accepted.BakaShrot_AuthAccepted - - *Accepted = AllocateStructure(BakaShrot_AuthAccepted) - If Not *Accepted - ProcedureReturn 0 - EndIf - - ; The base parser doesn't check which packet it is, that's on us. - If Not BakaShrot_ReadPacketBase(*Accepted, *MsgPackData) Or *Accepted\PacketType <> #BakaShrot_PacketType_AuthAccepted - FreeStructure(*Accepted) - ProcedureReturn 0 - EndIf - - ProcedureReturn *Accepted -EndProcedure diff --git a/Commons/Networking/Packets/ChallengeRequestPacket.pbi b/Commons/Networking/Packets/ChallengeRequestPacket.pbi deleted file mode 100644 index cc1c6b1..0000000 --- a/Commons/Networking/Packets/ChallengeRequestPacket.pbi +++ /dev/null @@ -1,148 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: ChallengeRequestPacket.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; ... -; ============================================================================ - - -XIncludeFile "../Packets.pbi" - -; S2C challenge the client must sign with its private key, the last packet sent in plain text. -; Nonce is fresh random data tied to this connection, the client must echo it back in its response. -; ServerSessionKey: the public half of the server's key pair for this connection. -; ServerSignature: the server's signature of the handshake so far, made with its identity key -; (BakaShrot_MakeHandshakeTranscript(), Connections.pbi), so the client knows it's the right server. -Structure BakaShrot_ChallengeRequest Extends BakaShrot_PacketBase - ChallengeB64.s - Nonce.a[#BakaShrot_NonceSize] - ServerSessionKey.a[#BakaShrot_SessionKeySize] - ServerSignature.a[#BakaShrot_HandshakeSignatureSize] -EndStructure - - -; Encodes *Request into a freshly allocated buffer, its base fields are set by this procedure. -; *Request\Nonce must already be filled by the caller with CryptRandomData(). -; *OutSize receives its size in bytes. -; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory. -Procedure.i BakaShrot_ChallengeRequestPacket_Encode(*Request.BakaShrot_ChallengeRequest, *OutSize.Integer) - Protected *MsgPackData.MsgPackData, *Buffer - - *Request\Magic = #BakaShrot_ProtocolMagic - *Request\Version = #BakaShrot_ProtocolVersion - *Request\PacketType = #BakaShrot_PacketType_ChallengeRequest - - *MsgPackData = MsgPackCreate(64) - If Not *MsgPackData - ProcedureReturn 0 - EndIf - - If Not BakaShrot_WritePacketBase(*Request, *MsgPackData) - Goto EncodeFailed - EndIf - - If MsgPackWriteString(*MsgPackData, *Request\ChallengeB64) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteBinary(*MsgPackData, @*Request\Nonce[0], #BakaShrot_NonceSize) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteBinary(*MsgPackData, @*Request\ServerSessionKey[0], #BakaShrot_SessionKeySize) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteBinary(*MsgPackData, @*Request\ServerSignature[0], #BakaShrot_HandshakeSignatureSize) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - ; Frees *MsgPackData on success, leaves it untouched on failure. - *Buffer = MsgPackFinalize(*MsgPackData) - If Not *Buffer - Goto EncodeFailed - EndIf - - *OutSize\i = MemorySize(*Buffer) - ProcedureReturn *Buffer - - EncodeFailed: - MsgPackFree(*MsgPackData, #True) - ProcedureReturn 0 -EndProcedure - -; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct. -; *MsgPackData stays owned by the caller, and should be discarded on failure. -; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure. -Procedure.i BakaShrot_ChallengeRequestPacket_Decode(*MsgPackData.MsgPackData) - Protected *Request.BakaShrot_ChallengeRequest - Protected ReadSize.q - - *Request = AllocateStructure(BakaShrot_ChallengeRequest) - If Not *Request - ProcedureReturn 0 - EndIf - - ; The base parser doesn't check which packet it is, that's on us. - If Not BakaShrot_ReadPacketBase(*Request, *MsgPackData) Or *Request\PacketType <> #BakaShrot_PacketType_ChallengeRequest - Goto DecodeFailed - EndIf - - ; ChallengeB64 - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String - Goto DecodeFailed - EndIf - *Request\ChallengeB64 = MsgPackReadString(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success - Goto DecodeFailed - EndIf - - ; Nonce - ; Anything bigger than the struct's array is rejected by MsgPackReadBinary, anything smaller by the size check. - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary - Goto DecodeFailed - EndIf - ReadSize = MsgPackReadBinary(*MsgPackData, @*Request\Nonce[0], #BakaShrot_NonceSize) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or ReadSize <> #BakaShrot_NonceSize - Goto DecodeFailed - EndIf - - ; ServerSessionKey - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary - Goto DecodeFailed - EndIf - ReadSize = MsgPackReadBinary(*MsgPackData, @*Request\ServerSessionKey[0], #BakaShrot_SessionKeySize) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or ReadSize <> #BakaShrot_SessionKeySize - Goto DecodeFailed - EndIf - - ; ServerSignature - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary - Goto DecodeFailed - EndIf - ReadSize = MsgPackReadBinary(*MsgPackData, @*Request\ServerSignature[0], #BakaShrot_HandshakeSignatureSize) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or ReadSize <> #BakaShrot_HandshakeSignatureSize - Goto DecodeFailed - EndIf - - ProcedureReturn *Request - - ; Everything read so far is tainted, drop it. - DecodeFailed: - FreeStructure(*Request) - ProcedureReturn 0 -EndProcedure diff --git a/Commons/Networking/Packets/ChallengeResponsePacket.pbi b/Commons/Networking/Packets/ChallengeResponsePacket.pbi deleted file mode 100644 index b450f92..0000000 --- a/Commons/Networking/Packets/ChallengeResponsePacket.pbi +++ /dev/null @@ -1,118 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: ChallengeResponsePacket.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; ... -; ============================================================================ - - -XIncludeFile "../Packets.pbi" - -; C2S response with the handshake (challenge included) signed by the client's private key -; (BakaShrot_MakeHandshakeTranscript(), Connections.pbi). Sent encrypted, as everything after it. -; Nonce is the one received in the challenge request, echoed back as-is. -; The server MUST compare it with the nonce it issued for this connection and drop the client on mismatch. -Structure BakaShrot_ChallengeResponse Extends BakaShrot_PacketBase - ChallengeResponseB64.s - Nonce.a[#BakaShrot_NonceSize] -EndStructure - - -; Encodes *Response into a freshly allocated buffer, its base fields are set by this procedure. -; *OutSize receives its size in bytes. -; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory. -Procedure.i BakaShrot_ChallengeResponsePacket_Encode(*Response.BakaShrot_ChallengeResponse, *OutSize.Integer) - Protected *MsgPackData.MsgPackData, *Buffer - - *Response\Magic = #BakaShrot_ProtocolMagic - *Response\Version = #BakaShrot_ProtocolVersion - *Response\PacketType = #BakaShrot_PacketType_ChallengeResponse - - *MsgPackData = MsgPackCreate(64) - If Not *MsgPackData - ProcedureReturn 0 - EndIf - - If Not BakaShrot_WritePacketBase(*Response, *MsgPackData) - Goto EncodeFailed - EndIf - - If MsgPackWriteString(*MsgPackData, *Response\ChallengeResponseB64) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteBinary(*MsgPackData, @*Response\Nonce[0], #BakaShrot_NonceSize) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - ; Frees *MsgPackData on success, leaves it untouched on failure. - *Buffer = MsgPackFinalize(*MsgPackData) - If Not *Buffer - Goto EncodeFailed - EndIf - - *OutSize\i = MemorySize(*Buffer) - ProcedureReturn *Buffer - - EncodeFailed: - MsgPackFree(*MsgPackData, #True) - ProcedureReturn 0 -EndProcedure - -; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct. -; *MsgPackData stays owned by the caller, and should be discarded on failure. -; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure. -Procedure.i BakaShrot_ChallengeResponsePacket_Decode(*MsgPackData.MsgPackData) - Protected *Response.BakaShrot_ChallengeResponse - Protected ReadSize.q - - *Response = AllocateStructure(BakaShrot_ChallengeResponse) - If Not *Response - ProcedureReturn 0 - EndIf - - ; The base parser doesn't check which packet it is, that's on us. - If Not BakaShrot_ReadPacketBase(*Response, *MsgPackData) Or *Response\PacketType <> #BakaShrot_PacketType_ChallengeResponse - Goto DecodeFailed - EndIf - - ; ChallengeResponseB64 - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String - Goto DecodeFailed - EndIf - *Response\ChallengeResponseB64 = MsgPackReadString(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success - Goto DecodeFailed - EndIf - - ; Nonce - ; Anything bigger than the struct's array is rejected by MsgPackReadBinary, anything smaller by the size check. - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary - Goto DecodeFailed - EndIf - ReadSize = MsgPackReadBinary(*MsgPackData, @*Response\Nonce[0], #BakaShrot_NonceSize) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or ReadSize <> #BakaShrot_NonceSize - Goto DecodeFailed - EndIf - - ProcedureReturn *Response - - ; Everything read so far is tainted, drop it. - DecodeFailed: - FreeStructure(*Response) - ProcedureReturn 0 -EndProcedure diff --git a/Commons/Networking/Packets/ChunkStoredPacket.pbi b/Commons/Networking/Packets/ChunkStoredPacket.pbi deleted file mode 100644 index 79831c8..0000000 --- a/Commons/Networking/Packets/ChunkStoredPacket.pbi +++ /dev/null @@ -1,121 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: ChunkStoredPacket.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; ... -; ============================================================================ - - -XIncludeFile "../Packets.pbi" - -; S2C (and S2P), answers an UploadChunk (or a ReplicateAttachmentChunk): Received -; bytes are stored so far. Complete is 1 once they all are, and their SHA-256 -; checked out. -Structure BakaShrot_ChunkStored Extends BakaShrot_PacketBase - Received.q - Complete.l -EndStructure - - -; Encodes *Stored into a freshly allocated buffer, its base fields are set by this procedure. -; *OutSize receives its size in bytes. -; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory. -Procedure.i BakaShrot_ChunkStoredPacket_Encode(*Stored.BakaShrot_ChunkStored, *OutSize.Integer) - Protected *MsgPackData.MsgPackData, *Buffer - - *Stored\Magic = #BakaShrot_ProtocolMagic - *Stored\Version = #BakaShrot_ProtocolVersion - *Stored\PacketType = #BakaShrot_PacketType_ChunkStored - - If *Stored\Received < 0 Or *Stored\Received > #BakaShrot_MaxAttachmentSize Or *Stored\Complete < 0 Or *Stored\Complete > 1 - ProcedureReturn 0 - EndIf - - *MsgPackData = MsgPackCreate(64) - If Not *MsgPackData - ProcedureReturn 0 - EndIf - - If Not BakaShrot_WritePacketBase(*Stored, *MsgPackData) - Goto EncodeFailed - EndIf - - If MsgPackWriteInteger(*MsgPackData, *Stored\Received) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteInteger(*MsgPackData, *Stored\Complete) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - ; Frees *MsgPackData on success, leaves it untouched on failure. - *Buffer = MsgPackFinalize(*MsgPackData) - If Not *Buffer - Goto EncodeFailed - EndIf - - *OutSize\i = MemorySize(*Buffer) - ProcedureReturn *Buffer - - EncodeFailed: - MsgPackFree(*MsgPackData, #True) - ProcedureReturn 0 -EndProcedure - -; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct. -; *MsgPackData stays owned by the caller, and should be discarded on failure. -; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure. -Procedure.i BakaShrot_ChunkStoredPacket_Decode(*MsgPackData.MsgPackData) - Protected *Stored.BakaShrot_ChunkStored, Value.q - - *Stored = AllocateStructure(BakaShrot_ChunkStored) - If Not *Stored - ProcedureReturn 0 - EndIf - - ; The base parser doesn't check which packet it is, that's on us. - If Not BakaShrot_ReadPacketBase(*Stored, *MsgPackData) Or *Stored\PacketType <> #BakaShrot_PacketType_ChunkStored - Goto DecodeFailed - EndIf - - ; Received - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - Value = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > #BakaShrot_MaxAttachmentSize - Goto DecodeFailed - EndIf - *Stored\Received = Value - - ; Complete - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - Value = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > 1 - Goto DecodeFailed - EndIf - *Stored\Complete = Value - - ProcedureReturn *Stored - - ; Everything read so far is tainted, drop it. - DecodeFailed: - FreeStructure(*Stored) - ProcedureReturn 0 -EndProcedure diff --git a/Commons/Networking/Packets/GetAttachmentPacket.pbi b/Commons/Networking/Packets/GetAttachmentPacket.pbi deleted file mode 100644 index 79a9fe5..0000000 --- a/Commons/Networking/Packets/GetAttachmentPacket.pbi +++ /dev/null @@ -1,151 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: GetAttachmentPacket.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; ... -; ============================================================================ - - -XIncludeFile "../Packets.pbi" - -; C2S, asks for part ChunkIndex (0 for the first) of the attachment of a message. -; Topic, Node: each a name or an id in digits, as GetMessages'. ReadTopics must -; allow the topic. -; Answered with an AttachmentChunk, or a RequestRefused (no such message, no -; attachment, or not here yet: replicated attachments come after their message). -Structure BakaShrot_GetAttachment Extends BakaShrot_PacketBase - Topic.s - Node.s - MessageId.q - ChunkIndex.l -EndStructure - - -; Encodes *Request into a freshly allocated buffer, its base fields are set by this procedure. -; *OutSize receives its size in bytes. -; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory. -Procedure.i BakaShrot_GetAttachmentPacket_Encode(*Request.BakaShrot_GetAttachment, *OutSize.Integer) - Protected *MsgPackData.MsgPackData, *Buffer - - *Request\Magic = #BakaShrot_ProtocolMagic - *Request\Version = #BakaShrot_ProtocolVersion - *Request\PacketType = #BakaShrot_PacketType_GetAttachment - - If *Request\MessageId < 1 Or *Request\ChunkIndex < 0 Or *Request\ChunkIndex > #BakaShrot_MaxAttachmentChunks - ProcedureReturn 0 - EndIf - - *MsgPackData = MsgPackCreate(64) - If Not *MsgPackData - ProcedureReturn 0 - EndIf - - If Not BakaShrot_WritePacketBase(*Request, *MsgPackData) - Goto EncodeFailed - EndIf - - If MsgPackWriteString(*MsgPackData, *Request\Topic) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteString(*MsgPackData, *Request\Node) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteInteger(*MsgPackData, *Request\MessageId) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteInteger(*MsgPackData, *Request\ChunkIndex) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - ; Frees *MsgPackData on success, leaves it untouched on failure. - *Buffer = MsgPackFinalize(*MsgPackData) - If Not *Buffer - Goto EncodeFailed - EndIf - - *OutSize\i = MemorySize(*Buffer) - ProcedureReturn *Buffer - - EncodeFailed: - MsgPackFree(*MsgPackData, #True) - ProcedureReturn 0 -EndProcedure - -; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct. -; *MsgPackData stays owned by the caller, and should be discarded on failure. -; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure. -Procedure.i BakaShrot_GetAttachmentPacket_Decode(*MsgPackData.MsgPackData) - Protected *Request.BakaShrot_GetAttachment, Value.q - - *Request = AllocateStructure(BakaShrot_GetAttachment) - If Not *Request - ProcedureReturn 0 - EndIf - - ; The base parser doesn't check which packet it is, that's on us. - If Not BakaShrot_ReadPacketBase(*Request, *MsgPackData) Or *Request\PacketType <> #BakaShrot_PacketType_GetAttachment - Goto DecodeFailed - EndIf - - ; Topic - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String - Goto DecodeFailed - EndIf - *Request\Topic = MsgPackReadString(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success - Goto DecodeFailed - EndIf - - ; Node - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String - Goto DecodeFailed - EndIf - *Request\Node = MsgPackReadString(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success - Goto DecodeFailed - EndIf - - ; MessageId - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - Value = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 1 - Goto DecodeFailed - EndIf - *Request\MessageId = Value - - ; ChunkIndex - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - Value = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > #BakaShrot_MaxAttachmentChunks - Goto DecodeFailed - EndIf - *Request\ChunkIndex = Value - - ProcedureReturn *Request - - ; Everything read so far is tainted, drop it. - DecodeFailed: - FreeStructure(*Request) - ProcedureReturn 0 -EndProcedure diff --git a/Commons/Networking/Packets/GetLatestMessagePacket.pbi b/Commons/Networking/Packets/GetLatestMessagePacket.pbi deleted file mode 100644 index 0590c31..0000000 --- a/Commons/Networking/Packets/GetLatestMessagePacket.pbi +++ /dev/null @@ -1,116 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: GetLatestMessagePacket.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; ... -; ============================================================================ - - -XIncludeFile "../Packets.pbi" - -; C2S, asks for the latest message stored for a topic/node combination. -; Topic, Node: each a name or an id in digits (Commons/Networking/Names.pbi). -; The client's [BakaShrot.Client.] ReadTopics must allow the topic. -; Answered with a LatestMessage or a RequestRefused. -Structure BakaShrot_GetLatestMessage Extends BakaShrot_PacketBase - Topic.s - Node.s -EndStructure - - -; Encodes *Request into a freshly allocated buffer, its base fields are set by this procedure. -; *OutSize receives its size in bytes. -; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory. -Procedure.i BakaShrot_GetLatestMessagePacket_Encode(*Request.BakaShrot_GetLatestMessage, *OutSize.Integer) - Protected *MsgPackData.MsgPackData, *Buffer - - *Request\Magic = #BakaShrot_ProtocolMagic - *Request\Version = #BakaShrot_ProtocolVersion - *Request\PacketType = #BakaShrot_PacketType_GetLatestMessage - - *MsgPackData = MsgPackCreate(64) - If Not *MsgPackData - ProcedureReturn 0 - EndIf - - If Not BakaShrot_WritePacketBase(*Request, *MsgPackData) - Goto EncodeFailed - EndIf - - If MsgPackWriteString(*MsgPackData, *Request\Topic) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteString(*MsgPackData, *Request\Node) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - ; Frees *MsgPackData on success, leaves it untouched on failure. - *Buffer = MsgPackFinalize(*MsgPackData) - If Not *Buffer - Goto EncodeFailed - EndIf - - *OutSize\i = MemorySize(*Buffer) - ProcedureReturn *Buffer - - EncodeFailed: - MsgPackFree(*MsgPackData, #True) - ProcedureReturn 0 -EndProcedure - -; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct. -; *MsgPackData stays owned by the caller, and should be discarded on failure. -; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure. -Procedure.i BakaShrot_GetLatestMessagePacket_Decode(*MsgPackData.MsgPackData) - Protected *Request.BakaShrot_GetLatestMessage - - *Request = AllocateStructure(BakaShrot_GetLatestMessage) - If Not *Request - ProcedureReturn 0 - EndIf - - ; The base parser doesn't check which packet it is, that's on us. - If Not BakaShrot_ReadPacketBase(*Request, *MsgPackData) Or *Request\PacketType <> #BakaShrot_PacketType_GetLatestMessage - Goto DecodeFailed - EndIf - - ; Topic - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String - Goto DecodeFailed - EndIf - *Request\Topic = MsgPackReadString(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success - Goto DecodeFailed - EndIf - - ; Node - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String - Goto DecodeFailed - EndIf - *Request\Node = MsgPackReadString(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success - Goto DecodeFailed - EndIf - - ProcedureReturn *Request - - ; Everything read so far is tainted, drop it. - DecodeFailed: - FreeStructure(*Request) - ProcedureReturn 0 -EndProcedure diff --git a/Commons/Networking/Packets/GetMessagesPacket.pbi b/Commons/Networking/Packets/GetMessagesPacket.pbi deleted file mode 100644 index d43ad4e..0000000 --- a/Commons/Networking/Packets/GetMessagesPacket.pbi +++ /dev/null @@ -1,155 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: GetMessagesPacket.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; ... -; ============================================================================ - - -XIncludeFile "../Packets.pbi" - -; Most messages a GetMessages may ask for. -#BakaShrot_MaxGetMessages = 10000 - -; C2S, asks for the messages of a topic/node combination stored after -; AfterMessageId (0 for the first ones), in message id order, at most Limit -; (1-#BakaShrot_MaxGetMessages) of them. -; Topic, Node: each a name or an id in digits (Commons/Networking/Names.pbi). -; The client's [BakaShrot.Client.] ReadTopics must allow the topic. -; Answered with a Messages (maybe with none) or a RequestRefused. -Structure BakaShrot_GetMessages Extends BakaShrot_PacketBase - Topic.s - Node.s - AfterMessageId.q - Limit.l -EndStructure - - -; Encodes *Request into a freshly allocated buffer, its base fields are set by this procedure. -; *OutSize receives its size in bytes. -; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory. -Procedure.i BakaShrot_GetMessagesPacket_Encode(*Request.BakaShrot_GetMessages, *OutSize.Integer) - Protected *MsgPackData.MsgPackData, *Buffer - - *Request\Magic = #BakaShrot_ProtocolMagic - *Request\Version = #BakaShrot_ProtocolVersion - *Request\PacketType = #BakaShrot_PacketType_GetMessages - - If *Request\AfterMessageId < 0 Or *Request\Limit < 1 Or *Request\Limit > #BakaShrot_MaxGetMessages - ProcedureReturn 0 - EndIf - - *MsgPackData = MsgPackCreate(64) - If Not *MsgPackData - ProcedureReturn 0 - EndIf - - If Not BakaShrot_WritePacketBase(*Request, *MsgPackData) - Goto EncodeFailed - EndIf - - If MsgPackWriteString(*MsgPackData, *Request\Topic) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteString(*MsgPackData, *Request\Node) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteInteger(*MsgPackData, *Request\AfterMessageId) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteInteger(*MsgPackData, *Request\Limit) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - ; Frees *MsgPackData on success, leaves it untouched on failure. - *Buffer = MsgPackFinalize(*MsgPackData) - If Not *Buffer - Goto EncodeFailed - EndIf - - *OutSize\i = MemorySize(*Buffer) - ProcedureReturn *Buffer - - EncodeFailed: - MsgPackFree(*MsgPackData, #True) - ProcedureReturn 0 -EndProcedure - -; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct. -; *MsgPackData stays owned by the caller, and should be discarded on failure. -; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure. -Procedure.i BakaShrot_GetMessagesPacket_Decode(*MsgPackData.MsgPackData) - Protected *Request.BakaShrot_GetMessages - Protected Value.q - - *Request = AllocateStructure(BakaShrot_GetMessages) - If Not *Request - ProcedureReturn 0 - EndIf - - ; The base parser doesn't check which packet it is, that's on us. - If Not BakaShrot_ReadPacketBase(*Request, *MsgPackData) Or *Request\PacketType <> #BakaShrot_PacketType_GetMessages - Goto DecodeFailed - EndIf - - ; Topic - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String - Goto DecodeFailed - EndIf - *Request\Topic = MsgPackReadString(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success - Goto DecodeFailed - EndIf - - ; Node - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String - Goto DecodeFailed - EndIf - *Request\Node = MsgPackReadString(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success - Goto DecodeFailed - EndIf - - ; AfterMessageId - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - *Request\AfterMessageId = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Request\AfterMessageId < 0 - Goto DecodeFailed - EndIf - - ; Limit - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - Value = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 1 Or Value > #BakaShrot_MaxGetMessages - Goto DecodeFailed - EndIf - *Request\Limit = Value - - ProcedureReturn *Request - - ; Everything read so far is tainted, drop it. - DecodeFailed: - FreeStructure(*Request) - ProcedureReturn 0 -EndProcedure diff --git a/Commons/Networking/Packets/HelloPacket.pbi b/Commons/Networking/Packets/HelloPacket.pbi deleted file mode 100644 index 8450c76..0000000 --- a/Commons/Networking/Packets/HelloPacket.pbi +++ /dev/null @@ -1,134 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: HelloPacket.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; ... -; ============================================================================ - - -XIncludeFile "../Packets.pbi" - -; C2S auth request, sent sealed for the server's public key (Connections.pbi). -; ClientNode: who the client is, the node it writes as, a name or an id in -; digits (Commons/Networking/Names.pbi), resolved by the server in its own -; names. Its default topic is the server's to say, not the client's. -; ClientSessionKey: the public half of the client's key pair for this -; connection (Commons/Cryptography/Session.pbi). -Structure BakaShrot_AuthHello Extends BakaShrot_PacketBase - ClientNode.s - ClientPubKeyB64.s - ClientSessionKey.a[#BakaShrot_SessionKeySize] -EndStructure - - -; Encodes *Hello into a freshly allocated buffer, its base fields are set by this procedure. -; *OutSize receives its size in bytes. -; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory. -Procedure.i BakaShrot_HelloPacket_Encode(*Hello.BakaShrot_AuthHello, *OutSize.Integer) - Protected *MsgPackData.MsgPackData, *Buffer - - *Hello\Magic = #BakaShrot_ProtocolMagic - *Hello\Version = #BakaShrot_ProtocolVersion - *Hello\PacketType = #BakaShrot_PacketType_ClientHello - - *MsgPackData = MsgPackCreate(64) - If Not *MsgPackData - ProcedureReturn 0 - EndIf - - If Not BakaShrot_WritePacketBase(*Hello, *MsgPackData) - Goto EncodeFailed - EndIf - - If MsgPackWriteString(*MsgPackData, *Hello\ClientNode) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteString(*MsgPackData, *Hello\ClientPubKeyB64) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteBinary(*MsgPackData, @*Hello\ClientSessionKey[0], #BakaShrot_SessionKeySize) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - ; Frees *MsgPackData on success, leaves it untouched on failure. - *Buffer = MsgPackFinalize(*MsgPackData) - If Not *Buffer - Goto EncodeFailed - EndIf - - *OutSize\i = MemorySize(*Buffer) - ProcedureReturn *Buffer - - EncodeFailed: - MsgPackFree(*MsgPackData, #True) - ProcedureReturn 0 -EndProcedure - -; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct. -; *MsgPackData stays owned by the caller, and should be discarded on failure. -; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure. -Procedure.i BakaShrot_HelloPacket_Decode(*MsgPackData.MsgPackData) - Protected *Hello.BakaShrot_AuthHello - Protected ReadSize.q - - *Hello = AllocateStructure(BakaShrot_AuthHello) - If Not *Hello - ProcedureReturn 0 - EndIf - - ; The base parser doesn't check which packet it is, that's on us. - If Not BakaShrot_ReadPacketBase(*Hello, *MsgPackData) Or *Hello\PacketType <> #BakaShrot_PacketType_ClientHello - Goto DecodeFailed - EndIf - - ; ClientNode - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String - Goto DecodeFailed - EndIf - *Hello\ClientNode = MsgPackReadString(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success - Goto DecodeFailed - EndIf - - ; ClientPubKeyB64 - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String - Goto DecodeFailed - EndIf - *Hello\ClientPubKeyB64 = MsgPackReadString(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success - Goto DecodeFailed - EndIf - - ; ClientSessionKey - ; Anything bigger than the struct's array is rejected by MsgPackReadBinary, anything smaller by the size check. - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary - Goto DecodeFailed - EndIf - ReadSize = MsgPackReadBinary(*MsgPackData, @*Hello\ClientSessionKey[0], #BakaShrot_SessionKeySize) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or ReadSize <> #BakaShrot_SessionKeySize - Goto DecodeFailed - EndIf - - ProcedureReturn *Hello - - ; Everything read so far is tainted, drop it. - DecodeFailed: - FreeStructure(*Hello) - ProcedureReturn 0 -EndProcedure diff --git a/Commons/Networking/Packets/LatestMessagePacket.pbi b/Commons/Networking/Packets/LatestMessagePacket.pbi deleted file mode 100644 index 601dd5b..0000000 --- a/Commons/Networking/Packets/LatestMessagePacket.pbi +++ /dev/null @@ -1,215 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: LatestMessagePacket.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; ... -; ============================================================================ - - -XIncludeFile "../Packets.pbi" - -; S2C, answers a GetLatestMessage with the latest message of that topic/node combination. -; TopicId, NodeId: the server's own ids for them. -; TopicName, NodeName: their names, or their ids in digits if they have none. -; PushedAt: when it was pushed, see Packets.pbi. -Structure BakaShrot_LatestMessage Extends BakaShrot_PacketBase - TopicId.l - NodeId.l - TopicName.s - NodeName.s - MessageId.q - PushedAt.q - JsonData.s - ; Its attachment's size in bytes, 0 for none, and whether this server has - ; all of it yet (a replicated one comes after its message). - AttachmentSize.q - AttachmentReady.l -EndStructure - - -; Encodes *Latest into a freshly allocated buffer, its base fields are set by this procedure. -; *OutSize receives its size in bytes. -; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory. -Procedure.i BakaShrot_LatestMessagePacket_Encode(*Latest.BakaShrot_LatestMessage, *OutSize.Integer) - Protected *MsgPackData.MsgPackData, *Buffer - - *Latest\Magic = #BakaShrot_ProtocolMagic - *Latest\Version = #BakaShrot_ProtocolVersion - *Latest\PacketType = #BakaShrot_PacketType_LatestMessage - - *MsgPackData = MsgPackCreate(64) - If Not *MsgPackData - ProcedureReturn 0 - EndIf - - If Not BakaShrot_WritePacketBase(*Latest, *MsgPackData) - Goto EncodeFailed - EndIf - - If MsgPackWriteInteger(*MsgPackData, *Latest\TopicId) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteInteger(*MsgPackData, *Latest\NodeId) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteString(*MsgPackData, *Latest\TopicName) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteString(*MsgPackData, *Latest\NodeName) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteInteger(*MsgPackData, *Latest\MessageId) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - If MsgPackWriteInteger(*MsgPackData, *Latest\PushedAt) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteString(*MsgPackData, *Latest\JsonData) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - If MsgPackWriteInteger(*MsgPackData, *Latest\AttachmentSize) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - If MsgPackWriteInteger(*MsgPackData, *Latest\AttachmentReady) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - ; Frees *MsgPackData on success, leaves it untouched on failure. - *Buffer = MsgPackFinalize(*MsgPackData) - If Not *Buffer - Goto EncodeFailed - EndIf - - *OutSize\i = MemorySize(*Buffer) - ProcedureReturn *Buffer - - EncodeFailed: - MsgPackFree(*MsgPackData, #True) - ProcedureReturn 0 -EndProcedure - -; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct. -; *MsgPackData stays owned by the caller, and should be discarded on failure. -; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure. -Procedure.i BakaShrot_LatestMessagePacket_Decode(*MsgPackData.MsgPackData) - Protected *Latest.BakaShrot_LatestMessage - Protected Value.q - - *Latest = AllocateStructure(BakaShrot_LatestMessage) - If Not *Latest - ProcedureReturn 0 - EndIf - - ; The base parser doesn't check which packet it is, that's on us. - If Not BakaShrot_ReadPacketBase(*Latest, *MsgPackData) Or *Latest\PacketType <> #BakaShrot_PacketType_LatestMessage - Goto DecodeFailed - EndIf - - ; TopicId - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - Value = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > 65535 - Goto DecodeFailed - EndIf - *Latest\TopicId = Value - - ; NodeId - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - Value = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > 65535 - Goto DecodeFailed - EndIf - *Latest\NodeId = Value - - ; TopicName - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String - Goto DecodeFailed - EndIf - *Latest\TopicName = MsgPackReadString(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success - Goto DecodeFailed - EndIf - - ; NodeName - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String - Goto DecodeFailed - EndIf - *Latest\NodeName = MsgPackReadString(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success - Goto DecodeFailed - EndIf - - ; MessageId - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - *Latest\MessageId = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Latest\MessageId < 1 - Goto DecodeFailed - EndIf - - ; PushedAt - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - *Latest\PushedAt = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidTimestamp(*Latest\PushedAt) - Goto DecodeFailed - EndIf - - ; JsonData - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String - Goto DecodeFailed - EndIf - *Latest\JsonData = MsgPackReadString(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success - Goto DecodeFailed - EndIf - ; AttachmentSize - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - *Latest\AttachmentSize = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Latest\AttachmentSize < 0 Or *Latest\AttachmentSize > #BakaShrot_MaxAttachmentSize - Goto DecodeFailed - EndIf - - ; AttachmentReady - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - *Latest\AttachmentReady = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Latest\AttachmentReady < 0 Or *Latest\AttachmentReady > 1 - Goto DecodeFailed - EndIf - - ProcedureReturn *Latest - - ; Everything read so far is tainted, drop it. - DecodeFailed: - FreeStructure(*Latest) - ProcedureReturn 0 -EndProcedure diff --git a/Commons/Networking/Packets/ListNamesPacket.pbi b/Commons/Networking/Packets/ListNamesPacket.pbi deleted file mode 100644 index 970686c..0000000 --- a/Commons/Networking/Packets/ListNamesPacket.pbi +++ /dev/null @@ -1,104 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: ListNamesPacket.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; ... -; ============================================================================ - - -XIncludeFile "ResolveNamePacket.pbi" - -; C2S, asks for every topic or node the server has, with their ids and names. -; Kind: #BakaShrot_NameKind_Topic or #BakaShrot_NameKind_Node. -; Topics: only those the client may push to or read, unless it may query. -; Answered with a NamesList. -Structure BakaShrot_ListNames Extends BakaShrot_PacketBase - Kind.l -EndStructure - - -; Encodes *Request into a freshly allocated buffer, its base fields are set by this procedure. -; *OutSize receives its size in bytes. -; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory. -Procedure.i BakaShrot_ListNamesPacket_Encode(*Request.BakaShrot_ListNames, *OutSize.Integer) - Protected *MsgPackData.MsgPackData, *Buffer - - *Request\Magic = #BakaShrot_ProtocolMagic - *Request\Version = #BakaShrot_ProtocolVersion - *Request\PacketType = #BakaShrot_PacketType_ListNames - - *MsgPackData = MsgPackCreate(32) - If Not *MsgPackData - ProcedureReturn 0 - EndIf - - If Not BakaShrot_WritePacketBase(*Request, *MsgPackData) - Goto EncodeFailed - EndIf - - If MsgPackWriteInteger(*MsgPackData, *Request\Kind) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - ; Frees *MsgPackData on success, leaves it untouched on failure. - *Buffer = MsgPackFinalize(*MsgPackData) - If Not *Buffer - Goto EncodeFailed - EndIf - - *OutSize\i = MemorySize(*Buffer) - ProcedureReturn *Buffer - - EncodeFailed: - MsgPackFree(*MsgPackData, #True) - ProcedureReturn 0 -EndProcedure - -; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct. -; *MsgPackData stays owned by the caller, and should be discarded on failure. -; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure. -Procedure.i BakaShrot_ListNamesPacket_Decode(*MsgPackData.MsgPackData) - Protected *Request.BakaShrot_ListNames - Protected Value.q - - *Request = AllocateStructure(BakaShrot_ListNames) - If Not *Request - ProcedureReturn 0 - EndIf - - ; The base parser doesn't check which packet it is, that's on us. - If Not BakaShrot_ReadPacketBase(*Request, *MsgPackData) Or *Request\PacketType <> #BakaShrot_PacketType_ListNames - Goto DecodeFailed - EndIf - - ; Kind - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - Value = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or (Value <> #BakaShrot_NameKind_Topic And Value <> #BakaShrot_NameKind_Node) - Goto DecodeFailed - EndIf - *Request\Kind = Value - - ProcedureReturn *Request - - ; Everything read so far is tainted, drop it. - DecodeFailed: - FreeStructure(*Request) - ProcedureReturn 0 -EndProcedure diff --git a/Commons/Networking/Packets/MessagePushedPacket.pbi b/Commons/Networking/Packets/MessagePushedPacket.pbi deleted file mode 100644 index 23bee0e..0000000 --- a/Commons/Networking/Packets/MessagePushedPacket.pbi +++ /dev/null @@ -1,99 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: MessagePushedPacket.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; ... -; ============================================================================ - - -XIncludeFile "../Packets.pbi" - -; S2C, answers a PushMessage with the id the message was stored under. -Structure BakaShrot_MessagePushed Extends BakaShrot_PacketBase - MessageId.q -EndStructure - - -; Encodes *Pushed into a freshly allocated buffer, its base fields are set by this procedure. -; *OutSize receives its size in bytes. -; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory. -Procedure.i BakaShrot_MessagePushedPacket_Encode(*Pushed.BakaShrot_MessagePushed, *OutSize.Integer) - Protected *MsgPackData.MsgPackData, *Buffer - - *Pushed\Magic = #BakaShrot_ProtocolMagic - *Pushed\Version = #BakaShrot_ProtocolVersion - *Pushed\PacketType = #BakaShrot_PacketType_MessagePushed - - *MsgPackData = MsgPackCreate(32) - If Not *MsgPackData - ProcedureReturn 0 - EndIf - - If Not BakaShrot_WritePacketBase(*Pushed, *MsgPackData) - Goto EncodeFailed - EndIf - - If MsgPackWriteInteger(*MsgPackData, *Pushed\MessageId) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - ; Frees *MsgPackData on success, leaves it untouched on failure. - *Buffer = MsgPackFinalize(*MsgPackData) - If Not *Buffer - Goto EncodeFailed - EndIf - - *OutSize\i = MemorySize(*Buffer) - ProcedureReturn *Buffer - - EncodeFailed: - MsgPackFree(*MsgPackData, #True) - ProcedureReturn 0 -EndProcedure - -; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct. -; *MsgPackData stays owned by the caller, and should be discarded on failure. -; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure. -Procedure.i BakaShrot_MessagePushedPacket_Decode(*MsgPackData.MsgPackData) - Protected *Pushed.BakaShrot_MessagePushed - - *Pushed = AllocateStructure(BakaShrot_MessagePushed) - If Not *Pushed - ProcedureReturn 0 - EndIf - - ; The base parser doesn't check which packet it is, that's on us. - If Not BakaShrot_ReadPacketBase(*Pushed, *MsgPackData) Or *Pushed\PacketType <> #BakaShrot_PacketType_MessagePushed - Goto DecodeFailed - EndIf - - ; MessageId - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - *Pushed\MessageId = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Pushed\MessageId < 1 - Goto DecodeFailed - EndIf - - ProcedureReturn *Pushed - - ; Everything read so far is tainted, drop it. - DecodeFailed: - FreeStructure(*Pushed) - ProcedureReturn 0 -EndProcedure diff --git a/Commons/Networking/Packets/MessagesPacket.pbi b/Commons/Networking/Packets/MessagesPacket.pbi deleted file mode 100644 index c7e444c..0000000 --- a/Commons/Networking/Packets/MessagesPacket.pbi +++ /dev/null @@ -1,277 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: MessagesPacket.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; ... -; ============================================================================ - - -XIncludeFile "../Packets.pbi" -XIncludeFile "GetMessagesPacket.pbi" - -; One message of a Messages answer. -Structure BakaShrot_MessagesEntry - MessageId.q - ; When it was pushed, see Packets.pbi. - PushedAt.q - ; Its attachment's size in bytes, 0 for none, and whether this server has - ; all of it yet (a replicated one comes after its message). - AttachmentSize.q - AttachmentReady.l - JsonData.s -EndStructure - -; About how big a Messages answer gets: messages are added while they fit -; in it, and a bigger one goes alone (up to #BakaShrot_MaxMessageSize). -#BakaShrot_MessagesBatchBytes = 1024 * 1024 - -; Encoded size of the answer's own fields, and of each message on top of its -; JSON, rounded up. Used to stop an answer before it gets over #BakaShrot_MaxPacketSize. -#BakaShrot_MessagesOverhead = 64 + 2 * (#BakaShrot_MaxNameLength + 2) -#BakaShrot_MessagesMessageOverhead = 40 - -; S2C, answers a GetMessages with the messages of that topic/node combination -; stored after the asked id, in message id order: as many as were asked for, -; or fewer if they didn't fit in about #BakaShrot_MessagesBatchBytes. None -; if there are no more. -; TopicId, NodeId: the server's own ids for them. -; TopicName, NodeName: their names, or their ids in digits if they have none. -; More: 1 if more messages follow the last one, ask again after it. -; On the wire: topic id, node id, topic name, node name, more, message -; count, then each message's id and JSON. -Structure BakaShrot_Messages Extends BakaShrot_PacketBase - TopicId.l - NodeId.l - TopicName.s - NodeName.s - More.l - List Messages.BakaShrot_MessagesEntry() -EndStructure - - -; Encodes *Answer into a freshly allocated buffer, its base fields are set by this procedure. -; *OutSize receives its size in bytes. -; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory. -Procedure.i BakaShrot_MessagesPacket_Encode(*Answer.BakaShrot_Messages, *OutSize.Integer) - Protected *MsgPackData.MsgPackData, *Buffer - - *Answer\Magic = #BakaShrot_ProtocolMagic - *Answer\Version = #BakaShrot_ProtocolVersion - *Answer\PacketType = #BakaShrot_PacketType_Messages - - If ListSize(*Answer\Messages()) > #BakaShrot_MaxGetMessages - ProcedureReturn 0 - EndIf - - *MsgPackData = MsgPackCreate(256) - If Not *MsgPackData - ProcedureReturn 0 - EndIf - - If Not BakaShrot_WritePacketBase(*Answer, *MsgPackData) - Goto EncodeFailed - EndIf - - If MsgPackWriteInteger(*MsgPackData, *Answer\TopicId) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteInteger(*MsgPackData, *Answer\NodeId) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteString(*MsgPackData, *Answer\TopicName) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteString(*MsgPackData, *Answer\NodeName) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteInteger(*MsgPackData, Bool(*Answer\More)) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - ; Messages - If MsgPackWriteInteger(*MsgPackData, ListSize(*Answer\Messages())) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - ForEach *Answer\Messages() - If MsgPackWriteInteger(*MsgPackData, *Answer\Messages()\MessageId) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - If MsgPackWriteInteger(*MsgPackData, *Answer\Messages()\PushedAt) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - If MsgPackWriteString(*MsgPackData, *Answer\Messages()\JsonData) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - If MsgPackWriteInteger(*MsgPackData, *Answer\Messages()\AttachmentSize) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - If MsgPackWriteInteger(*MsgPackData, *Answer\Messages()\AttachmentReady) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - Next - - ; Frees *MsgPackData on success, leaves it untouched on failure. - *Buffer = MsgPackFinalize(*MsgPackData) - If Not *Buffer - Goto EncodeFailed - EndIf - - *OutSize\i = MemorySize(*Buffer) - ProcedureReturn *Buffer - - EncodeFailed: - MsgPackFree(*MsgPackData, #True) - ProcedureReturn 0 -EndProcedure - -; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct. -; Message ids must be 1 or more, and strictly increasing. -; *MsgPackData stays owned by the caller, and should be discarded on failure. -; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure. -Procedure.i BakaShrot_MessagesPacket_Decode(*MsgPackData.MsgPackData) - Protected *Answer.BakaShrot_Messages - Protected Value.q, Count.q, i.q, PreviousMessageId.q - - *Answer = AllocateStructure(BakaShrot_Messages) - If Not *Answer - ProcedureReturn 0 - EndIf - - ; The base parser doesn't check which packet it is, that's on us. - If Not BakaShrot_ReadPacketBase(*Answer, *MsgPackData) Or *Answer\PacketType <> #BakaShrot_PacketType_Messages - Goto DecodeFailed - EndIf - - ; TopicId - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - Value = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > 65535 - Goto DecodeFailed - EndIf - *Answer\TopicId = Value - - ; NodeId - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - Value = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > 65535 - Goto DecodeFailed - EndIf - *Answer\NodeId = Value - - ; TopicName - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String - Goto DecodeFailed - EndIf - *Answer\TopicName = MsgPackReadString(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success - Goto DecodeFailed - EndIf - - ; NodeName - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String - Goto DecodeFailed - EndIf - *Answer\NodeName = MsgPackReadString(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success - Goto DecodeFailed - EndIf - - ; More - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - Value = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > 1 - Goto DecodeFailed - EndIf - *Answer\More = Value - - ; Message count - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - Count = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Count < 0 Or Count > #BakaShrot_MaxGetMessages - Goto DecodeFailed - EndIf - - ; Messages - PreviousMessageId = 0 - For i = 1 To Count - AddElement(*Answer\Messages()) - - ; MessageId - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - *Answer\Messages()\MessageId = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Answer\Messages()\MessageId <= PreviousMessageId - Goto DecodeFailed - EndIf - PreviousMessageId = *Answer\Messages()\MessageId - - ; PushedAt - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - *Answer\Messages()\PushedAt = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidTimestamp(*Answer\Messages()\PushedAt) - Goto DecodeFailed - EndIf - - ; JsonData - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String - Goto DecodeFailed - EndIf - *Answer\Messages()\JsonData = MsgPackReadString(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success - Goto DecodeFailed - EndIf - ; AttachmentSize - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - *Answer\Messages()\AttachmentSize = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Answer\Messages()\AttachmentSize < 0 Or *Answer\Messages()\AttachmentSize > #BakaShrot_MaxAttachmentSize - Goto DecodeFailed - EndIf - - ; AttachmentReady - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - *Answer\Messages()\AttachmentReady = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Answer\Messages()\AttachmentReady < 0 Or *Answer\Messages()\AttachmentReady > 1 - Goto DecodeFailed - EndIf - Next - - ProcedureReturn *Answer - - ; Everything read so far is tainted, drop it. - DecodeFailed: - FreeStructure(*Answer) - ProcedureReturn 0 -EndProcedure diff --git a/Commons/Networking/Packets/MissingAttachmentsPacket.pbi b/Commons/Networking/Packets/MissingAttachmentsPacket.pbi deleted file mode 100644 index 34561b0..0000000 --- a/Commons/Networking/Packets/MissingAttachmentsPacket.pbi +++ /dev/null @@ -1,173 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: MissingAttachmentsPacket.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; ... -; ============================================================================ - - -XIncludeFile "../Packets.pbi" - -; Most attachments one MissingAttachments lists, the next check-in asks again. -#BakaShrot_MaxMissingAttachments = 256 - -; One attachment the server is missing: of Topic:Node#MessageId (names, never -; digits), from part NextChunk on (0 if it has none of it yet). -Structure BakaShrot_MissingAttachment - Topic.s - Node.s - MessageId.q - NextChunk.l -EndStructure - -; S2P, answers a MissingAttachmentsRequest: attachments of messages the server -; has, that it takes from this peer, and doesn't have all of yet. Maybe none. -; On the wire: the count, then each one's topic, node, message id and next chunk. -Structure BakaShrot_MissingAttachments Extends BakaShrot_PacketBase - List Attachments.BakaShrot_MissingAttachment() -EndStructure - - -; Encodes *Answer into a freshly allocated buffer, its base fields are set by this procedure. -; *OutSize receives its size in bytes. -; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory. -Procedure.i BakaShrot_MissingAttachmentsPacket_Encode(*Answer.BakaShrot_MissingAttachments, *OutSize.Integer) - Protected *MsgPackData.MsgPackData, *Buffer - - *Answer\Magic = #BakaShrot_ProtocolMagic - *Answer\Version = #BakaShrot_ProtocolVersion - *Answer\PacketType = #BakaShrot_PacketType_MissingAttachments - - If ListSize(*Answer\Attachments()) > #BakaShrot_MaxMissingAttachments - ProcedureReturn 0 - EndIf - - *MsgPackData = MsgPackCreate(256) - If Not *MsgPackData - ProcedureReturn 0 - EndIf - - If Not BakaShrot_WritePacketBase(*Answer, *MsgPackData) - Goto EncodeFailed - EndIf - - If MsgPackWriteInteger(*MsgPackData, ListSize(*Answer\Attachments())) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - ForEach *Answer\Attachments() - If MsgPackWriteString(*MsgPackData, *Answer\Attachments()\Topic) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - If MsgPackWriteString(*MsgPackData, *Answer\Attachments()\Node) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - If MsgPackWriteInteger(*MsgPackData, *Answer\Attachments()\MessageId) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - If MsgPackWriteInteger(*MsgPackData, *Answer\Attachments()\NextChunk) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - Next - - ; Frees *MsgPackData on success, leaves it untouched on failure. - *Buffer = MsgPackFinalize(*MsgPackData) - If Not *Buffer - Goto EncodeFailed - EndIf - - *OutSize\i = MemorySize(*Buffer) - ProcedureReturn *Buffer - - EncodeFailed: - MsgPackFree(*MsgPackData, #True) - ProcedureReturn 0 -EndProcedure - -; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct. -; *MsgPackData stays owned by the caller, and should be discarded on failure. -; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure. -Procedure.i BakaShrot_MissingAttachmentsPacket_Decode(*MsgPackData.MsgPackData) - Protected *Answer.BakaShrot_MissingAttachments - Protected Value.q, Count.q, i.q - - *Answer = AllocateStructure(BakaShrot_MissingAttachments) - If Not *Answer - ProcedureReturn 0 - EndIf - - ; The base parser doesn't check which packet it is, that's on us. - If Not BakaShrot_ReadPacketBase(*Answer, *MsgPackData) Or *Answer\PacketType <> #BakaShrot_PacketType_MissingAttachments - Goto DecodeFailed - EndIf - - ; Count - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - Count = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Count < 0 Or Count > #BakaShrot_MaxMissingAttachments - Goto DecodeFailed - EndIf - - For i = 1 To Count - AddElement(*Answer\Attachments()) - - ; Topic - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String - Goto DecodeFailed - EndIf - *Answer\Attachments()\Topic = MsgPackReadString(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidName(*Answer\Attachments()\Topic) - Goto DecodeFailed - EndIf - - ; Node - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String - Goto DecodeFailed - EndIf - *Answer\Attachments()\Node = MsgPackReadString(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidName(*Answer\Attachments()\Node) - Goto DecodeFailed - EndIf - - ; MessageId - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - *Answer\Attachments()\MessageId = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Answer\Attachments()\MessageId < 1 - Goto DecodeFailed - EndIf - - ; NextChunk - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - Value = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > #BakaShrot_MaxAttachmentChunks - Goto DecodeFailed - EndIf - *Answer\Attachments()\NextChunk = Value - Next - - ProcedureReturn *Answer - - ; Everything read so far is tainted, drop it. - DecodeFailed: - FreeStructure(*Answer) - ProcedureReturn 0 -EndProcedure diff --git a/Commons/Networking/Packets/MissingAttachmentsRequestPacket.pbi b/Commons/Networking/Packets/MissingAttachmentsRequestPacket.pbi deleted file mode 100644 index 9d9b4f5..0000000 --- a/Commons/Networking/Packets/MissingAttachmentsRequestPacket.pbi +++ /dev/null @@ -1,88 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: MissingAttachmentsRequestPacket.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; ... -; ============================================================================ - - -XIncludeFile "../Packets.pbi" - -; P2S, asks which attachments the server is still missing from this peer, once -; the messages are caught up. Only the base fields. -; Answered with a MissingAttachments, or a RequestRefused. -Structure BakaShrot_MissingAttachmentsRequest Extends BakaShrot_PacketBase - -EndStructure - - -; Encodes *Request into a freshly allocated buffer, its base fields are set by this procedure. -; *OutSize receives its size in bytes. -; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory. -Procedure.i BakaShrot_MissingAttachmentsRequestPacket_Encode(*Request.BakaShrot_MissingAttachmentsRequest, *OutSize.Integer) - Protected *MsgPackData.MsgPackData, *Buffer - - *Request\Magic = #BakaShrot_ProtocolMagic - *Request\Version = #BakaShrot_ProtocolVersion - *Request\PacketType = #BakaShrot_PacketType_MissingAttachmentsRequest - - *MsgPackData = MsgPackCreate(64) - If Not *MsgPackData - ProcedureReturn 0 - EndIf - - If Not BakaShrot_WritePacketBase(*Request, *MsgPackData) - Goto EncodeFailed - EndIf - - ; Frees *MsgPackData on success, leaves it untouched on failure. - *Buffer = MsgPackFinalize(*MsgPackData) - If Not *Buffer - Goto EncodeFailed - EndIf - - *OutSize\i = MemorySize(*Buffer) - ProcedureReturn *Buffer - - EncodeFailed: - MsgPackFree(*MsgPackData, #True) - ProcedureReturn 0 -EndProcedure - -; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct. -; *MsgPackData stays owned by the caller, and should be discarded on failure. -; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure. -Procedure.i BakaShrot_MissingAttachmentsRequestPacket_Decode(*MsgPackData.MsgPackData) - Protected *Request.BakaShrot_MissingAttachmentsRequest - - *Request = AllocateStructure(BakaShrot_MissingAttachmentsRequest) - If Not *Request - ProcedureReturn 0 - EndIf - - ; The base parser doesn't check which packet it is, that's on us. - If Not BakaShrot_ReadPacketBase(*Request, *MsgPackData) Or *Request\PacketType <> #BakaShrot_PacketType_MissingAttachmentsRequest - Goto DecodeFailed - EndIf - - ProcedureReturn *Request - - ; Everything read so far is tainted, drop it. - DecodeFailed: - FreeStructure(*Request) - ProcedureReturn 0 -EndProcedure diff --git a/Commons/Networking/Packets/NameResolvedPacket.pbi b/Commons/Networking/Packets/NameResolvedPacket.pbi deleted file mode 100644 index c7e90af..0000000 --- a/Commons/Networking/Packets/NameResolvedPacket.pbi +++ /dev/null @@ -1,133 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: NameResolvedPacket.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; ... -; ============================================================================ - - -XIncludeFile "ResolveNamePacket.pbi" - -; S2C, answers a ResolveName. -; Kind: the one asked about, #BakaShrot_NameKind_Topic or #BakaShrot_NameKind_Node. -; Id: the server's own id for it, 0-65535. -; Name: its name, "" if it has none. -Structure BakaShrot_NameResolved Extends BakaShrot_PacketBase - Kind.l - Id.l - Name.s -EndStructure - - -; Encodes *Answer into a freshly allocated buffer, its base fields are set by this procedure. -; *OutSize receives its size in bytes. -; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory. -Procedure.i BakaShrot_NameResolvedPacket_Encode(*Answer.BakaShrot_NameResolved, *OutSize.Integer) - Protected *MsgPackData.MsgPackData, *Buffer - - *Answer\Magic = #BakaShrot_ProtocolMagic - *Answer\Version = #BakaShrot_ProtocolVersion - *Answer\PacketType = #BakaShrot_PacketType_NameResolved - - *MsgPackData = MsgPackCreate(64) - If Not *MsgPackData - ProcedureReturn 0 - EndIf - - If Not BakaShrot_WritePacketBase(*Answer, *MsgPackData) - Goto EncodeFailed - EndIf - - If MsgPackWriteInteger(*MsgPackData, *Answer\Kind) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteInteger(*MsgPackData, *Answer\Id) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteString(*MsgPackData, *Answer\Name) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - ; Frees *MsgPackData on success, leaves it untouched on failure. - *Buffer = MsgPackFinalize(*MsgPackData) - If Not *Buffer - Goto EncodeFailed - EndIf - - *OutSize\i = MemorySize(*Buffer) - ProcedureReturn *Buffer - - EncodeFailed: - MsgPackFree(*MsgPackData, #True) - ProcedureReturn 0 -EndProcedure - -; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct. -; *MsgPackData stays owned by the caller, and should be discarded on failure. -; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure. -Procedure.i BakaShrot_NameResolvedPacket_Decode(*MsgPackData.MsgPackData) - Protected *Answer.BakaShrot_NameResolved - Protected Value.q - - *Answer = AllocateStructure(BakaShrot_NameResolved) - If Not *Answer - ProcedureReturn 0 - EndIf - - ; The base parser doesn't check which packet it is, that's on us. - If Not BakaShrot_ReadPacketBase(*Answer, *MsgPackData) Or *Answer\PacketType <> #BakaShrot_PacketType_NameResolved - Goto DecodeFailed - EndIf - - ; Kind - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - Value = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or (Value <> #BakaShrot_NameKind_Topic And Value <> #BakaShrot_NameKind_Node) - Goto DecodeFailed - EndIf - *Answer\Kind = Value - - ; Id - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - Value = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > #BakaShrot_MaxId - Goto DecodeFailed - EndIf - *Answer\Id = Value - - ; Name - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String - Goto DecodeFailed - EndIf - *Answer\Name = MsgPackReadString(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success - Goto DecodeFailed - EndIf - - ProcedureReturn *Answer - - ; Everything read so far is tainted, drop it. - DecodeFailed: - FreeStructure(*Answer) - ProcedureReturn 0 -EndProcedure diff --git a/Commons/Networking/Packets/NamesListPacket.pbi b/Commons/Networking/Packets/NamesListPacket.pbi deleted file mode 100644 index 535668a..0000000 --- a/Commons/Networking/Packets/NamesListPacket.pbi +++ /dev/null @@ -1,194 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: NamesListPacket.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; ... -; ============================================================================ - - -XIncludeFile "ResolveNamePacket.pbi" - -; One topic or node of a NamesList. -; Origin: where its name comes from, "config" (named in the config) or "id" -; (unnamed, Name is ""). See Server/Storage/Names.pbi. -Structure BakaShrot_NameEntry - Id.l - Name.s - Origin.s -EndStructure - -#BakaShrot_MaxNamesListEntries = 65536 - -; S2C, answers a ListNames, by id. -; Kind: the one asked about. Truncated: 1 if there were more than fit in one -; packet, the first ones by id are listed. -; On the wire: Kind, Truncated, entry count, then each entry's id, name and origin. -Structure BakaShrot_NamesList Extends BakaShrot_PacketBase - Kind.l - Truncated.l - List Entries.BakaShrot_NameEntry() -EndStructure - - -; Encoded size of the packet's own fields, and of each entry on top of its -; name and origin, rounded up. Used to cut a list before it gets over -; #BakaShrot_MaxPacketSize. -#BakaShrot_NamesListOverhead = 64 -#BakaShrot_NamesListEntryOverhead = 16 - - -; Encodes *List into a freshly allocated buffer, its base fields are set by this procedure. -; *OutSize receives its size in bytes. -; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory. -Procedure.i BakaShrot_NamesListPacket_Encode(*List.BakaShrot_NamesList, *OutSize.Integer) - Protected *MsgPackData.MsgPackData, *Buffer - - *List\Magic = #BakaShrot_ProtocolMagic - *List\Version = #BakaShrot_ProtocolVersion - *List\PacketType = #BakaShrot_PacketType_NamesList - - If ListSize(*List\Entries()) > #BakaShrot_MaxNamesListEntries - ProcedureReturn 0 - EndIf - - *MsgPackData = MsgPackCreate(256) - If Not *MsgPackData - ProcedureReturn 0 - EndIf - - If Not BakaShrot_WritePacketBase(*List, *MsgPackData) - Goto EncodeFailed - EndIf - - If MsgPackWriteInteger(*MsgPackData, *List\Kind) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteInteger(*MsgPackData, Bool(*List\Truncated)) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteInteger(*MsgPackData, ListSize(*List\Entries())) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - ForEach *List\Entries() - If MsgPackWriteInteger(*MsgPackData, *List\Entries()\Id) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - If MsgPackWriteString(*MsgPackData, *List\Entries()\Name) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - If MsgPackWriteString(*MsgPackData, *List\Entries()\Origin) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - Next - - ; Frees *MsgPackData on success, leaves it untouched on failure. - *Buffer = MsgPackFinalize(*MsgPackData) - If Not *Buffer - Goto EncodeFailed - EndIf - - *OutSize\i = MemorySize(*Buffer) - ProcedureReturn *Buffer - - EncodeFailed: - MsgPackFree(*MsgPackData, #True) - ProcedureReturn 0 -EndProcedure - -; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct. -; *MsgPackData stays owned by the caller, and should be discarded on failure. -; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure. -Procedure.i BakaShrot_NamesListPacket_Decode(*MsgPackData.MsgPackData) - Protected *List.BakaShrot_NamesList - Protected Value.q, Count.q, i.q - - *List = AllocateStructure(BakaShrot_NamesList) - If Not *List - ProcedureReturn 0 - EndIf - - ; The base parser doesn't check which packet it is, that's on us. - If Not BakaShrot_ReadPacketBase(*List, *MsgPackData) Or *List\PacketType <> #BakaShrot_PacketType_NamesList - Goto DecodeFailed - EndIf - - ; Kind - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - Value = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or (Value <> #BakaShrot_NameKind_Topic And Value <> #BakaShrot_NameKind_Node) - Goto DecodeFailed - EndIf - *List\Kind = Value - - ; Truncated - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - Value = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > 1 - Goto DecodeFailed - EndIf - *List\Truncated = Value - - ; Entries - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - Count = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Count < 0 Or Count > #BakaShrot_MaxNamesListEntries - Goto DecodeFailed - EndIf - For i = 1 To Count - AddElement(*List\Entries()) - - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - Value = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > #BakaShrot_MaxId - Goto DecodeFailed - EndIf - *List\Entries()\Id = Value - - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String - Goto DecodeFailed - EndIf - *List\Entries()\Name = MsgPackReadString(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success - Goto DecodeFailed - EndIf - - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String - Goto DecodeFailed - EndIf - *List\Entries()\Origin = MsgPackReadString(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success - Goto DecodeFailed - EndIf - Next - - ProcedureReturn *List - - ; Everything read so far is tainted, drop it. - DecodeFailed: - FreeStructure(*List) - ProcedureReturn 0 -EndProcedure diff --git a/Commons/Networking/Packets/PushMessagePacket.pbi b/Commons/Networking/Packets/PushMessagePacket.pbi deleted file mode 100644 index dd9a4fe..0000000 --- a/Commons/Networking/Packets/PushMessagePacket.pbi +++ /dev/null @@ -1,133 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: PushMessagePacket.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; ... -; ============================================================================ - - -XIncludeFile "../Packets.pbi" - -; C2S, asks the server to store a JSON message. -; Topic: where to push it, a name or an id in digits (Commons/Networking/Names.pbi), -; "" for the topic of the client's authenticated identity. The client's -; [BakaShrot.Client.] PushTopics must allow it. -; The node is always the client's authenticated one, the client can't pick it. -; UploadId: the attachment uploaded for it (UploadStart, all of it stored), 0 for none. -; Answered with a MessagePushed or a RequestRefused. -Structure BakaShrot_PushMessage Extends BakaShrot_PacketBase - Topic.s - JsonData.s - UploadId.q -EndStructure - - -; Encodes *Push into a freshly allocated buffer, its base fields are set by this procedure. -; *OutSize receives its size in bytes. -; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory. -Procedure.i BakaShrot_PushMessagePacket_Encode(*Push.BakaShrot_PushMessage, *OutSize.Integer) - Protected *MsgPackData.MsgPackData, *Buffer - - *Push\Magic = #BakaShrot_ProtocolMagic - *Push\Version = #BakaShrot_ProtocolVersion - *Push\PacketType = #BakaShrot_PacketType_PushMessage - - *MsgPackData = MsgPackCreate(64) - If Not *MsgPackData - ProcedureReturn 0 - EndIf - - If Not BakaShrot_WritePacketBase(*Push, *MsgPackData) - Goto EncodeFailed - EndIf - - If MsgPackWriteString(*MsgPackData, *Push\Topic) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteString(*MsgPackData, *Push\JsonData) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If *Push\UploadId < 0 Or MsgPackWriteInteger(*MsgPackData, *Push\UploadId) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - ; Frees *MsgPackData on success, leaves it untouched on failure. - *Buffer = MsgPackFinalize(*MsgPackData) - If Not *Buffer - Goto EncodeFailed - EndIf - - *OutSize\i = MemorySize(*Buffer) - ProcedureReturn *Buffer - - EncodeFailed: - MsgPackFree(*MsgPackData, #True) - ProcedureReturn 0 -EndProcedure - -; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct. -; *MsgPackData stays owned by the caller, and should be discarded on failure. -; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure. -Procedure.i BakaShrot_PushMessagePacket_Decode(*MsgPackData.MsgPackData) - Protected *Push.BakaShrot_PushMessage - - *Push = AllocateStructure(BakaShrot_PushMessage) - If Not *Push - ProcedureReturn 0 - EndIf - - ; The base parser doesn't check which packet it is, that's on us. - If Not BakaShrot_ReadPacketBase(*Push, *MsgPackData) Or *Push\PacketType <> #BakaShrot_PacketType_PushMessage - Goto DecodeFailed - EndIf - - ; Topic - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String - Goto DecodeFailed - EndIf - *Push\Topic = MsgPackReadString(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success - Goto DecodeFailed - EndIf - - ; JsonData - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String - Goto DecodeFailed - EndIf - *Push\JsonData = MsgPackReadString(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success - Goto DecodeFailed - EndIf - - ; UploadId - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - *Push\UploadId = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Push\UploadId < 0 - Goto DecodeFailed - EndIf - - ProcedureReturn *Push - - ; Everything read so far is tainted, drop it. - DecodeFailed: - FreeStructure(*Push) - ProcedureReturn 0 -EndProcedure diff --git a/Commons/Networking/Packets/QueryRequestPacket.pbi b/Commons/Networking/Packets/QueryRequestPacket.pbi deleted file mode 100644 index 060c5f3..0000000 --- a/Commons/Networking/Packets/QueryRequestPacket.pbi +++ /dev/null @@ -1,101 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: QueryRequestPacket.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; ... -; ============================================================================ - - -XIncludeFile "../Packets.pbi" - -; C2S, a raw SQL query to run read-only on the server's database. -; Must be a single SELECT (or WITH ... SELECT), anything after the first statement is ignored. -; Answered with a QueryResult or a RequestRefused. -Structure BakaShrot_QueryRequest Extends BakaShrot_PacketBase - Sql.s -EndStructure - - -; Encodes *Request into a freshly allocated buffer, its base fields are set by this procedure. -; *OutSize receives its size in bytes. -; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory. -Procedure.i BakaShrot_QueryRequestPacket_Encode(*Request.BakaShrot_QueryRequest, *OutSize.Integer) - Protected *MsgPackData.MsgPackData, *Buffer - - *Request\Magic = #BakaShrot_ProtocolMagic - *Request\Version = #BakaShrot_ProtocolVersion - *Request\PacketType = #BakaShrot_PacketType_QueryRequest - - *MsgPackData = MsgPackCreate(64) - If Not *MsgPackData - ProcedureReturn 0 - EndIf - - If Not BakaShrot_WritePacketBase(*Request, *MsgPackData) - Goto EncodeFailed - EndIf - - If MsgPackWriteString(*MsgPackData, *Request\Sql) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - ; Frees *MsgPackData on success, leaves it untouched on failure. - *Buffer = MsgPackFinalize(*MsgPackData) - If Not *Buffer - Goto EncodeFailed - EndIf - - *OutSize\i = MemorySize(*Buffer) - ProcedureReturn *Buffer - - EncodeFailed: - MsgPackFree(*MsgPackData, #True) - ProcedureReturn 0 -EndProcedure - -; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct. -; *MsgPackData stays owned by the caller, and should be discarded on failure. -; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure. -Procedure.i BakaShrot_QueryRequestPacket_Decode(*MsgPackData.MsgPackData) - Protected *Request.BakaShrot_QueryRequest - - *Request = AllocateStructure(BakaShrot_QueryRequest) - If Not *Request - ProcedureReturn 0 - EndIf - - ; The base parser doesn't check which packet it is, that's on us. - If Not BakaShrot_ReadPacketBase(*Request, *MsgPackData) Or *Request\PacketType <> #BakaShrot_PacketType_QueryRequest - Goto DecodeFailed - EndIf - - ; Sql - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String - Goto DecodeFailed - EndIf - *Request\Sql = MsgPackReadString(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success - Goto DecodeFailed - EndIf - - ProcedureReturn *Request - - ; Everything read so far is tainted, drop it. - DecodeFailed: - FreeStructure(*Request) - ProcedureReturn 0 -EndProcedure diff --git a/Commons/Networking/Packets/QueryResultPacket.pbi b/Commons/Networking/Packets/QueryResultPacket.pbi deleted file mode 100644 index b5f3c35..0000000 --- a/Commons/Networking/Packets/QueryResultPacket.pbi +++ /dev/null @@ -1,101 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: QueryResultPacket.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; ... -; ============================================================================ - - -XIncludeFile "../Packets.pbi" - -; S2C, answers a QueryRequest with its rows, as JSON: -; {"columns": ["name", ...], "rows": [["value", ...], ...]} -; Every value is a string, or null for NULL: PureBasic doesn't report SQLite's column types. -Structure BakaShrot_QueryResult Extends BakaShrot_PacketBase - JsonResult.s -EndStructure - - -; Encodes *Result into a freshly allocated buffer, its base fields are set by this procedure. -; *OutSize receives its size in bytes. -; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory. -Procedure.i BakaShrot_QueryResultPacket_Encode(*Result.BakaShrot_QueryResult, *OutSize.Integer) - Protected *MsgPackData.MsgPackData, *Buffer - - *Result\Magic = #BakaShrot_ProtocolMagic - *Result\Version = #BakaShrot_ProtocolVersion - *Result\PacketType = #BakaShrot_PacketType_QueryResult - - *MsgPackData = MsgPackCreate(64) - If Not *MsgPackData - ProcedureReturn 0 - EndIf - - If Not BakaShrot_WritePacketBase(*Result, *MsgPackData) - Goto EncodeFailed - EndIf - - If MsgPackWriteString(*MsgPackData, *Result\JsonResult) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - ; Frees *MsgPackData on success, leaves it untouched on failure. - *Buffer = MsgPackFinalize(*MsgPackData) - If Not *Buffer - Goto EncodeFailed - EndIf - - *OutSize\i = MemorySize(*Buffer) - ProcedureReturn *Buffer - - EncodeFailed: - MsgPackFree(*MsgPackData, #True) - ProcedureReturn 0 -EndProcedure - -; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct. -; *MsgPackData stays owned by the caller, and should be discarded on failure. -; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure. -Procedure.i BakaShrot_QueryResultPacket_Decode(*MsgPackData.MsgPackData) - Protected *Result.BakaShrot_QueryResult - - *Result = AllocateStructure(BakaShrot_QueryResult) - If Not *Result - ProcedureReturn 0 - EndIf - - ; The base parser doesn't check which packet it is, that's on us. - If Not BakaShrot_ReadPacketBase(*Result, *MsgPackData) Or *Result\PacketType <> #BakaShrot_PacketType_QueryResult - Goto DecodeFailed - EndIf - - ; JsonResult - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String - Goto DecodeFailed - EndIf - *Result\JsonResult = MsgPackReadString(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success - Goto DecodeFailed - EndIf - - ProcedureReturn *Result - - ; Everything read so far is tainted, drop it. - DecodeFailed: - FreeStructure(*Result) - ProcedureReturn 0 -EndProcedure diff --git a/Commons/Networking/Packets/ReplicateAttachmentChunkPacket.pbi b/Commons/Networking/Packets/ReplicateAttachmentChunkPacket.pbi deleted file mode 100644 index e0347cd..0000000 --- a/Commons/Networking/Packets/ReplicateAttachmentChunkPacket.pbi +++ /dev/null @@ -1,181 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: ReplicateAttachmentChunkPacket.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; ... -; ============================================================================ - - -XIncludeFile "../Packets.pbi" - -; P2S, part ChunkIndex of the attachment of Topic:Node#MessageId (names, never -; digits), a message the server already has, as MissingAttachments asked for. -; The size and SHA-256 came with the message (ReplicateMessages). -; Answered with a ChunkStored, or a RequestRefused. -Structure BakaShrot_ReplicateAttachmentChunk Extends BakaShrot_PacketBase - Topic.s - Node.s - MessageId.q - ChunkIndex.l - *Data - DataSize.l -EndStructure - - -; Encodes *Chunk into a freshly allocated buffer, its base fields are set by this procedure. -; *OutSize receives its size in bytes. -; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory. -Procedure.i BakaShrot_ReplicateAttachmentChunkPacket_Encode(*Chunk.BakaShrot_ReplicateAttachmentChunk, *OutSize.Integer) - Protected *MsgPackData.MsgPackData, *Buffer - - *Chunk\Magic = #BakaShrot_ProtocolMagic - *Chunk\Version = #BakaShrot_ProtocolVersion - *Chunk\PacketType = #BakaShrot_PacketType_ReplicateAttachmentChunk - - If Not BakaShrot_IsValidName(*Chunk\Topic) Or Not BakaShrot_IsValidName(*Chunk\Node) Or *Chunk\MessageId < 1 Or *Chunk\ChunkIndex < 0 Or *Chunk\ChunkIndex > #BakaShrot_MaxAttachmentChunks Or Not *Chunk\Data Or *Chunk\DataSize < 1 Or *Chunk\DataSize > #BakaShrot_AttachmentChunkSize - ProcedureReturn 0 - EndIf - - *MsgPackData = MsgPackCreate(#BakaShrot_AttachmentChunkSize + 256) - If Not *MsgPackData - ProcedureReturn 0 - EndIf - - If Not BakaShrot_WritePacketBase(*Chunk, *MsgPackData) - Goto EncodeFailed - EndIf - - If MsgPackWriteString(*MsgPackData, *Chunk\Topic) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteString(*MsgPackData, *Chunk\Node) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteInteger(*MsgPackData, *Chunk\MessageId) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteInteger(*MsgPackData, *Chunk\ChunkIndex) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteBinary(*MsgPackData, *Chunk\Data, *Chunk\DataSize) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - ; Frees *MsgPackData on success, leaves it untouched on failure. - *Buffer = MsgPackFinalize(*MsgPackData) - If Not *Buffer - Goto EncodeFailed - EndIf - - *OutSize\i = MemorySize(*Buffer) - ProcedureReturn *Buffer - - EncodeFailed: - MsgPackFree(*MsgPackData, #True) - ProcedureReturn 0 -EndProcedure - -; Frees a decoded *Chunk and the data it holds. -Procedure BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk.BakaShrot_ReplicateAttachmentChunk) - If Not *Chunk - ProcedureReturn - EndIf - If *Chunk\Data - FreeMemory(*Chunk\Data) - EndIf - FreeStructure(*Chunk) -EndProcedure - -; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct. -; *MsgPackData stays owned by the caller, and should be discarded on failure. -; Returns 0 on failure, the caller owns the returned struct - free it with BakaShrot_ReplicateAttachmentChunkPacket_Free(). -Procedure.i BakaShrot_ReplicateAttachmentChunkPacket_Decode(*MsgPackData.MsgPackData) - Protected *Chunk.BakaShrot_ReplicateAttachmentChunk, Value.q - - *Chunk = AllocateStructure(BakaShrot_ReplicateAttachmentChunk) - If Not *Chunk - ProcedureReturn 0 - EndIf - - ; The base parser doesn't check which packet it is, that's on us. - If Not BakaShrot_ReadPacketBase(*Chunk, *MsgPackData) Or *Chunk\PacketType <> #BakaShrot_PacketType_ReplicateAttachmentChunk - Goto DecodeFailed - EndIf - - ; Topic - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String - Goto DecodeFailed - EndIf - *Chunk\Topic = MsgPackReadString(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidName(*Chunk\Topic) - Goto DecodeFailed - EndIf - - ; Node - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String - Goto DecodeFailed - EndIf - *Chunk\Node = MsgPackReadString(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidName(*Chunk\Node) - Goto DecodeFailed - EndIf - - ; MessageId - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - Value = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 1 - Goto DecodeFailed - EndIf - *Chunk\MessageId = Value - - ; ChunkIndex - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - Value = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > #BakaShrot_MaxAttachmentChunks - Goto DecodeFailed - EndIf - *Chunk\ChunkIndex = Value - - ; Data - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary - Goto DecodeFailed - EndIf - ; A copy, freed with the packet (_Free()). - *Chunk\Data = MsgPackCopyBinary(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not *Chunk\Data - Goto DecodeFailed - EndIf - *Chunk\DataSize = MemorySize(*Chunk\Data) - If *Chunk\DataSize > #BakaShrot_AttachmentChunkSize - Goto DecodeFailed - EndIf - - ProcedureReturn *Chunk - - ; Everything read so far is tainted, drop it. - DecodeFailed: - BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk) - ProcedureReturn 0 -EndProcedure diff --git a/Commons/Networking/Packets/ReplicateMessagesPacket.pbi b/Commons/Networking/Packets/ReplicateMessagesPacket.pbi deleted file mode 100644 index 7bc287b..0000000 --- a/Commons/Networking/Packets/ReplicateMessagesPacket.pbi +++ /dev/null @@ -1,242 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: ReplicateMessagesPacket.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; ... -; ============================================================================ - - -XIncludeFile "../Packets.pbi" - -; One message of a ReplicateMessages batch. -; PushedAt: when it was pushed to its origin (Packets.pbi), stored as is. -; AttachmentSize, AttachmentSha256: its attachment's, 0 for none. The data -; itself follows on its own, once the messages are caught up -; (MissingAttachments, ReplicateAttachmentChunk). -Structure BakaShrot_ReplicatedMessage - MessageId.q - PushedAt.q - JsonData.s - AttachmentSize.q - AttachmentSha256.a[#BakaShrot_Sha256Size] -EndStructure - -; Most messages a batch may carry, whatever the sender's PeerBatchSize. -; #BakaShrot_ReplicateBatchBytes usually stops a batch well before that. -#BakaShrot_MaxReplicateBatch = 10000 - -; About how big a batch gets: messages are added while they fit in it, and -; a bigger one goes alone (up to #BakaShrot_MaxMessageSize). Small enough to -; keep each batch's transaction and memory short, like when 64 KB was the -; biggest packet. -#BakaShrot_ReplicateBatchBytes = 65536 - -; Encoded size of a batch's own fields, and of each message on top of its -; JSON, rounded up. Used to stop a batch before it gets over #BakaShrot_MaxPacketSize. -#BakaShrot_ReplicateBatchOverhead = 64 + 2 * (#BakaShrot_MaxNameLength + 2) -#BakaShrot_ReplicateMessageOverhead = 70 - -; Peer -> Server, messages the server is missing for one topic/node, in -; message id order, with the message ids they were stored under on their -; origin. Topic and Node are names, never ids (Commons/Networking/Names.pbi): -; the server stores them under its own ids for those names, and refuses -; names it doesn't know. -; On the wire: topic, node, message count, then each message's id, PushedAt, -; JSON, attachment size and SHA-256. -; Answered with a MessagePushed carrying the last message's id, or a RequestRefused. -Structure BakaShrot_ReplicateMessages Extends BakaShrot_PacketBase - Topic.s - Node.s - List Messages.BakaShrot_ReplicatedMessage() -EndStructure - - -; Encodes *Batch into a freshly allocated buffer, its base fields are set by this procedure. -; *OutSize receives its size in bytes. -; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory. -Procedure.i BakaShrot_ReplicateMessagesPacket_Encode(*Batch.BakaShrot_ReplicateMessages, *OutSize.Integer) - Protected *MsgPackData.MsgPackData, *Buffer - - *Batch\Magic = #BakaShrot_ProtocolMagic - *Batch\Version = #BakaShrot_ProtocolVersion - *Batch\PacketType = #BakaShrot_PacketType_ReplicateMessages - - If ListSize(*Batch\Messages()) < 1 Or ListSize(*Batch\Messages()) > #BakaShrot_MaxReplicateBatch - ProcedureReturn 0 - EndIf - - *MsgPackData = MsgPackCreate(256) - If Not *MsgPackData - ProcedureReturn 0 - EndIf - - If Not BakaShrot_WritePacketBase(*Batch, *MsgPackData) - Goto EncodeFailed - EndIf - - If MsgPackWriteString(*MsgPackData, *Batch\Topic) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteString(*MsgPackData, *Batch\Node) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - ; Messages - If MsgPackWriteInteger(*MsgPackData, ListSize(*Batch\Messages())) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - ForEach *Batch\Messages() - If MsgPackWriteInteger(*MsgPackData, *Batch\Messages()\MessageId) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - If MsgPackWriteInteger(*MsgPackData, *Batch\Messages()\PushedAt) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - If MsgPackWriteString(*MsgPackData, *Batch\Messages()\JsonData) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - If MsgPackWriteInteger(*MsgPackData, *Batch\Messages()\AttachmentSize) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - ; Empty without an attachment. - If *Batch\Messages()\AttachmentSize > 0 - If MsgPackWriteBinary(*MsgPackData, @*Batch\Messages()\AttachmentSha256[0], #BakaShrot_Sha256Size) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - ElseIf MsgPackWriteBinary(*MsgPackData, @*Batch\Messages()\AttachmentSha256[0], 0) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - Next - - ; Frees *MsgPackData on success, leaves it untouched on failure. - *Buffer = MsgPackFinalize(*MsgPackData) - If Not *Buffer - Goto EncodeFailed - EndIf - - *OutSize\i = MemorySize(*Buffer) - ProcedureReturn *Buffer - - EncodeFailed: - MsgPackFree(*MsgPackData, #True) - ProcedureReturn 0 -EndProcedure - -; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct. -; Message ids must be 1 or more, and strictly increasing. -; *MsgPackData stays owned by the caller, and should be discarded on failure. -; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure. -Procedure.i BakaShrot_ReplicateMessagesPacket_Decode(*MsgPackData.MsgPackData) - Protected *Batch.BakaShrot_ReplicateMessages - Protected Value.q, Count.q, i.q, PreviousMessageId.q, ReadSize.q - - *Batch = AllocateStructure(BakaShrot_ReplicateMessages) - If Not *Batch - ProcedureReturn 0 - EndIf - - ; The base parser doesn't check which packet it is, that's on us. - If Not BakaShrot_ReadPacketBase(*Batch, *MsgPackData) Or *Batch\PacketType <> #BakaShrot_PacketType_ReplicateMessages - Goto DecodeFailed - EndIf - - ; Topic - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String - Goto DecodeFailed - EndIf - *Batch\Topic = MsgPackReadString(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidName(*Batch\Topic) - Goto DecodeFailed - EndIf - - ; Node - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String - Goto DecodeFailed - EndIf - *Batch\Node = MsgPackReadString(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidName(*Batch\Node) - Goto DecodeFailed - EndIf - - ; Message count - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - Count = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Count < 1 Or Count > #BakaShrot_MaxReplicateBatch - Goto DecodeFailed - EndIf - - ; Messages - PreviousMessageId = 0 - For i = 1 To Count - AddElement(*Batch\Messages()) - - ; MessageId - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - *Batch\Messages()\MessageId = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Batch\Messages()\MessageId <= PreviousMessageId - Goto DecodeFailed - EndIf - PreviousMessageId = *Batch\Messages()\MessageId - - ; PushedAt - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - *Batch\Messages()\PushedAt = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidTimestamp(*Batch\Messages()\PushedAt) - Goto DecodeFailed - EndIf - - ; JsonData - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String - Goto DecodeFailed - EndIf - *Batch\Messages()\JsonData = MsgPackReadString(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success - Goto DecodeFailed - EndIf - ; AttachmentSize - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - *Batch\Messages()\AttachmentSize = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Batch\Messages()\AttachmentSize < 0 Or *Batch\Messages()\AttachmentSize > #BakaShrot_MaxAttachmentSize - Goto DecodeFailed - EndIf - - ; AttachmentSha256: 32 bytes with an attachment, empty without. - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary - Goto DecodeFailed - EndIf - ReadSize = MsgPackReadBinary(*MsgPackData, @*Batch\Messages()\AttachmentSha256[0], #BakaShrot_Sha256Size) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or (ReadSize <> #BakaShrot_Sha256Size And *Batch\Messages()\AttachmentSize > 0) Or (ReadSize <> 0 And *Batch\Messages()\AttachmentSize = 0) - Goto DecodeFailed - EndIf - Next - - ProcedureReturn *Batch - - ; Everything read so far is tainted, drop it. - DecodeFailed: - FreeStructure(*Batch) - ProcedureReturn 0 -EndProcedure diff --git a/Commons/Networking/Packets/RequestRefusedPacket.pbi b/Commons/Networking/Packets/RequestRefusedPacket.pbi deleted file mode 100644 index c48d8c0..0000000 --- a/Commons/Networking/Packets/RequestRefusedPacket.pbi +++ /dev/null @@ -1,121 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: RequestRefusedPacket.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; ... -; ============================================================================ - - -XIncludeFile "../Packets.pbi" - -; S2C, answers a request the server won't fulfill, the connection stays open. -; Code: what kind of refusal, 1-#BakaShrot_Refused_Max, one of the -; #BakaShrot_Refused_* in Client/BakaShrot_ErrorCodes.pbi: what clients act -; on (protocol 6). Reason is only meant for logs and humans. -Structure BakaShrot_RequestRefused Extends BakaShrot_PacketBase - Code.l - Reason.s -EndStructure - - -; Encodes *Refused into a freshly allocated buffer, its base fields are set by this procedure. -; *OutSize receives its size in bytes. -; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory. -Procedure.i BakaShrot_RequestRefusedPacket_Encode(*Refused.BakaShrot_RequestRefused, *OutSize.Integer) - Protected *MsgPackData.MsgPackData, *Buffer - - *Refused\Magic = #BakaShrot_ProtocolMagic - *Refused\Version = #BakaShrot_ProtocolVersion - *Refused\PacketType = #BakaShrot_PacketType_RequestRefused - - If Not BakaShrot_IsRefusalCode(*Refused\Code) - ProcedureReturn 0 - EndIf - - *MsgPackData = MsgPackCreate(64) - If Not *MsgPackData - ProcedureReturn 0 - EndIf - - If Not BakaShrot_WritePacketBase(*Refused, *MsgPackData) - Goto EncodeFailed - EndIf - - If MsgPackWriteInteger(*MsgPackData, *Refused\Code) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteString(*MsgPackData, *Refused\Reason) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - ; Frees *MsgPackData on success, leaves it untouched on failure. - *Buffer = MsgPackFinalize(*MsgPackData) - If Not *Buffer - Goto EncodeFailed - EndIf - - *OutSize\i = MemorySize(*Buffer) - ProcedureReturn *Buffer - - EncodeFailed: - MsgPackFree(*MsgPackData, #True) - ProcedureReturn 0 -EndProcedure - -; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct. -; *MsgPackData stays owned by the caller, and should be discarded on failure. -; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure. -Procedure.i BakaShrot_RequestRefusedPacket_Decode(*MsgPackData.MsgPackData) - Protected *Refused.BakaShrot_RequestRefused, Value.q - - *Refused = AllocateStructure(BakaShrot_RequestRefused) - If Not *Refused - ProcedureReturn 0 - EndIf - - ; The base parser doesn't check which packet it is, that's on us. - If Not BakaShrot_ReadPacketBase(*Refused, *MsgPackData) Or *Refused\PacketType <> #BakaShrot_PacketType_RequestRefused - Goto DecodeFailed - EndIf - - ; Code - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - Value = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsRefusalCode(Value) - Goto DecodeFailed - EndIf - *Refused\Code = Value - - ; Reason - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String - Goto DecodeFailed - EndIf - *Refused\Reason = MsgPackReadString(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success - Goto DecodeFailed - EndIf - - ProcedureReturn *Refused - - ; Everything read so far is tainted, drop it. - DecodeFailed: - FreeStructure(*Refused) - ProcedureReturn 0 -EndProcedure diff --git a/Commons/Networking/Packets/ResolveNamePacket.pbi b/Commons/Networking/Packets/ResolveNamePacket.pbi deleted file mode 100644 index a0b2bb7..0000000 --- a/Commons/Networking/Packets/ResolveNamePacket.pbi +++ /dev/null @@ -1,124 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: ResolveNamePacket.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; ... -; ============================================================================ - - -XIncludeFile "../Packets.pbi" - -; What a ResolveName / NameResolved is about. -#BakaShrot_NameKind_Topic = 1 -#BakaShrot_NameKind_Node = 2 - -; C2S, asks for the server's id and name of a topic or node. -; Kind: #BakaShrot_NameKind_Topic or #BakaShrot_NameKind_Node. -; Ref: a name or an id in digits (Commons/Networking/Names.pbi). -; Answered with a NameResolved, or a RequestRefused if the server doesn't -; know it, or if it's a topic the client may neither push to nor read -; (unless it may query, which reads everything anyway). -Structure BakaShrot_ResolveName Extends BakaShrot_PacketBase - Kind.l - Ref.s -EndStructure - - -; Encodes *Request into a freshly allocated buffer, its base fields are set by this procedure. -; *OutSize receives its size in bytes. -; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory. -Procedure.i BakaShrot_ResolveNamePacket_Encode(*Request.BakaShrot_ResolveName, *OutSize.Integer) - Protected *MsgPackData.MsgPackData, *Buffer - - *Request\Magic = #BakaShrot_ProtocolMagic - *Request\Version = #BakaShrot_ProtocolVersion - *Request\PacketType = #BakaShrot_PacketType_ResolveName - - *MsgPackData = MsgPackCreate(64) - If Not *MsgPackData - ProcedureReturn 0 - EndIf - - If Not BakaShrot_WritePacketBase(*Request, *MsgPackData) - Goto EncodeFailed - EndIf - - If MsgPackWriteInteger(*MsgPackData, *Request\Kind) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteString(*MsgPackData, *Request\Ref) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - ; Frees *MsgPackData on success, leaves it untouched on failure. - *Buffer = MsgPackFinalize(*MsgPackData) - If Not *Buffer - Goto EncodeFailed - EndIf - - *OutSize\i = MemorySize(*Buffer) - ProcedureReturn *Buffer - - EncodeFailed: - MsgPackFree(*MsgPackData, #True) - ProcedureReturn 0 -EndProcedure - -; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct. -; *MsgPackData stays owned by the caller, and should be discarded on failure. -; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure. -Procedure.i BakaShrot_ResolveNamePacket_Decode(*MsgPackData.MsgPackData) - Protected *Request.BakaShrot_ResolveName - Protected Value.q - - *Request = AllocateStructure(BakaShrot_ResolveName) - If Not *Request - ProcedureReturn 0 - EndIf - - ; The base parser doesn't check which packet it is, that's on us. - If Not BakaShrot_ReadPacketBase(*Request, *MsgPackData) Or *Request\PacketType <> #BakaShrot_PacketType_ResolveName - Goto DecodeFailed - EndIf - - ; Kind - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - Value = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or (Value <> #BakaShrot_NameKind_Topic And Value <> #BakaShrot_NameKind_Node) - Goto DecodeFailed - EndIf - *Request\Kind = Value - - ; Ref - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String - Goto DecodeFailed - EndIf - *Request\Ref = MsgPackReadString(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success - Goto DecodeFailed - EndIf - - ProcedureReturn *Request - - ; Everything read so far is tainted, drop it. - DecodeFailed: - FreeStructure(*Request) - ProcedureReturn 0 -EndProcedure diff --git a/Commons/Networking/Packets/SyncStatePacket.pbi b/Commons/Networking/Packets/SyncStatePacket.pbi deleted file mode 100644 index ed8032c..0000000 --- a/Commons/Networking/Packets/SyncStatePacket.pbi +++ /dev/null @@ -1,296 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: SyncStatePacket.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; ... -; ============================================================================ - - -XIncludeFile "../Packets.pbi" - -; Highest message id a node has for a topic/node id combination. -Structure BakaShrot_SyncPair - TopicId.l - NodeId.l - MessageId.q -EndStructure - -; One of the sender's ids, and what it's called: its name, or its id in -; digits if it has none (Commons/Networking/Names.pbi). -Structure BakaShrot_SyncName - Id.l - Name.s -EndStructure - -; Biggest lists accepted, the packet size limit keeps the real ones well under it. -#BakaShrot_MaxSyncTopics = 65536 -#BakaShrot_MaxSyncNodes = 65536 -#BakaShrot_MaxSyncPairs = 65536 -#BakaShrot_MaxSyncPatterns = 4096 - -; Server -> Peer, answers a SyncStateRequest, at every check-in. Ids are the -; sender's own, names are what the peer matches them by: each server has its -; own ids. Only named topics and nodes replicate, and only those named on -; both servers: this is how the peer learns which names this server knows, -; so it never sends anything this server would refuse. -; Topics: the named topics it takes from this peer (its AcceptTopics). -; Nodes: the named nodes it takes from this peer (its AcceptNodes). -; TopicPatterns, NodePatterns: the wildcards ("*", "sensors.*") of its -; AcceptTopics / AcceptNodes: it also takes names it doesn't have yet if -; they match one (Commons/Networking/Names.pbi). -; Pairs: the highest message id it has for each topic/node of those. -; A combination that isn't listed has no message yet. -; Names are names, never ids in digits. -; On the wire: topic count, each topic's id and name, node count, each -; node's id and name, topic pattern count, each pattern, node pattern -; count, each pattern, pair count, then each pair's topic id, node id and -; message id. -Structure BakaShrot_SyncState Extends BakaShrot_PacketBase - List Topics.BakaShrot_SyncName() - List Nodes.BakaShrot_SyncName() - List TopicPatterns.s() - List NodePatterns.s() - List Pairs.BakaShrot_SyncPair() -EndStructure - - -; Writes a list of ids and names, with its count first. -Procedure.i BakaShrot_SyncStatePacket_WriteNames(*MsgPackData.MsgPackData, List Names.BakaShrot_SyncName()) - If MsgPackWriteInteger(*MsgPackData, ListSize(Names())) <> #MsgPack_Error_Success - ProcedureReturn #False - EndIf - ForEach Names() - If MsgPackWriteInteger(*MsgPackData, Names()\Id) <> #MsgPack_Error_Success - ProcedureReturn #False - EndIf - If MsgPackWriteString(*MsgPackData, Names()\Name) <> #MsgPack_Error_Success - ProcedureReturn #False - EndIf - Next - ProcedureReturn #True -EndProcedure - - -; Writes a list of patterns, with its count first. -Procedure.i BakaShrot_SyncStatePacket_WritePatterns(*MsgPackData.MsgPackData, List Patterns.s()) - If MsgPackWriteInteger(*MsgPackData, ListSize(Patterns())) <> #MsgPack_Error_Success - ProcedureReturn #False - EndIf - ForEach Patterns() - If MsgPackWriteString(*MsgPackData, Patterns()) <> #MsgPack_Error_Success - ProcedureReturn #False - EndIf - Next - ProcedureReturn #True -EndProcedure - - -; Encodes *State into a freshly allocated buffer, its base fields are set by this procedure. -; *OutSize receives its size in bytes. -; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory. -Procedure.i BakaShrot_SyncStatePacket_Encode(*State.BakaShrot_SyncState, *OutSize.Integer) - Protected *MsgPackData.MsgPackData, *Buffer - - *State\Magic = #BakaShrot_ProtocolMagic - *State\Version = #BakaShrot_ProtocolVersion - *State\PacketType = #BakaShrot_PacketType_SyncState - - If ListSize(*State\Topics()) > #BakaShrot_MaxSyncTopics Or ListSize(*State\Nodes()) > #BakaShrot_MaxSyncNodes Or ListSize(*State\Pairs()) > #BakaShrot_MaxSyncPairs - ProcedureReturn 0 - EndIf - If ListSize(*State\TopicPatterns()) > #BakaShrot_MaxSyncPatterns Or ListSize(*State\NodePatterns()) > #BakaShrot_MaxSyncPatterns - ProcedureReturn 0 - EndIf - - *MsgPackData = MsgPackCreate(64) - If Not *MsgPackData - ProcedureReturn 0 - EndIf - - If Not BakaShrot_WritePacketBase(*State, *MsgPackData) - Goto EncodeFailed - EndIf - - - If Not BakaShrot_SyncStatePacket_WriteNames(*MsgPackData, *State\Topics()) - Goto EncodeFailed - EndIf - - If Not BakaShrot_SyncStatePacket_WriteNames(*MsgPackData, *State\Nodes()) - Goto EncodeFailed - EndIf - - If Not BakaShrot_SyncStatePacket_WritePatterns(*MsgPackData, *State\TopicPatterns()) - Goto EncodeFailed - EndIf - - If Not BakaShrot_SyncStatePacket_WritePatterns(*MsgPackData, *State\NodePatterns()) - Goto EncodeFailed - EndIf - - ; Pairs - If MsgPackWriteInteger(*MsgPackData, ListSize(*State\Pairs())) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - ForEach *State\Pairs() - If MsgPackWriteInteger(*MsgPackData, *State\Pairs()\TopicId) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - If MsgPackWriteInteger(*MsgPackData, *State\Pairs()\NodeId) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - If MsgPackWriteInteger(*MsgPackData, *State\Pairs()\MessageId) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - Next - - ; Frees *MsgPackData on success, leaves it untouched on failure. - *Buffer = MsgPackFinalize(*MsgPackData) - If Not *Buffer - Goto EncodeFailed - EndIf - - *OutSize\i = MemorySize(*Buffer) - ProcedureReturn *Buffer - - EncodeFailed: - MsgPackFree(*MsgPackData, #True) - ProcedureReturn 0 -EndProcedure - -; Reads one integer within Minimum-Maximum into *Value\q. -; Returns #False if it's not an integer, couldn't be read, or is out of range. -Procedure.i BakaShrot_SyncStatePacket_ReadInteger(*MsgPackData.MsgPackData, *Value.Quad, Minimum.q, Maximum.q) - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - ProcedureReturn #False - EndIf - *Value\q = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Value\q < Minimum Or *Value\q > Maximum - ProcedureReturn #False - EndIf - ProcedureReturn #True -EndProcedure - -; Reads a list of ids and names, with its count first. Every name must be a -; valid name, not an id in digits. -; Returns #False if anything is invalid. -Procedure.i BakaShrot_SyncStatePacket_ReadNames(*MsgPackData.MsgPackData, List Names.BakaShrot_SyncName(), MaxCount.i) - Protected Count.q, Value.q, i.q - - If Not BakaShrot_SyncStatePacket_ReadInteger(*MsgPackData, @Count, 0, MaxCount) - ProcedureReturn #False - EndIf - For i = 1 To Count - AddElement(Names()) - If Not BakaShrot_SyncStatePacket_ReadInteger(*MsgPackData, @Value, 0, #BakaShrot_MaxId) - ProcedureReturn #False - EndIf - Names()\Id = Value - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String - ProcedureReturn #False - EndIf - Names()\Name = MsgPackReadString(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidName(Names()\Name) - ProcedureReturn #False - EndIf - Next - ProcedureReturn #True -EndProcedure - -; Reads a list of patterns, with its count first. Each one must be a valid -; pattern, see Commons/Networking/Names.pbi. -; Returns #False if anything is invalid. -Procedure.i BakaShrot_SyncStatePacket_ReadPatterns(*MsgPackData.MsgPackData, List Patterns.s()) - Protected Count.q, i.q - - If Not BakaShrot_SyncStatePacket_ReadInteger(*MsgPackData, @Count, 0, #BakaShrot_MaxSyncPatterns) - ProcedureReturn #False - EndIf - For i = 1 To Count - AddElement(Patterns()) - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String - ProcedureReturn #False - EndIf - Patterns() = MsgPackReadString(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidPattern(Patterns()) - ProcedureReturn #False - EndIf - Next - ProcedureReturn #True -EndProcedure - -; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct. -; *MsgPackData stays owned by the caller, and should be discarded on failure. -; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure. -Procedure.i BakaShrot_SyncStatePacket_Decode(*MsgPackData.MsgPackData) - Protected *State.BakaShrot_SyncState - Protected Count.q, Value.q, i.q - - *State = AllocateStructure(BakaShrot_SyncState) - If Not *State - ProcedureReturn 0 - EndIf - - ; The base parser doesn't check which packet it is, that's on us. - If Not BakaShrot_ReadPacketBase(*State, *MsgPackData) Or *State\PacketType <> #BakaShrot_PacketType_SyncState - Goto DecodeFailed - EndIf - - - If Not BakaShrot_SyncStatePacket_ReadNames(*MsgPackData, *State\Topics(), #BakaShrot_MaxSyncTopics) - Goto DecodeFailed - EndIf - - If Not BakaShrot_SyncStatePacket_ReadNames(*MsgPackData, *State\Nodes(), #BakaShrot_MaxSyncNodes) - Goto DecodeFailed - EndIf - - If Not BakaShrot_SyncStatePacket_ReadPatterns(*MsgPackData, *State\TopicPatterns()) - Goto DecodeFailed - EndIf - - If Not BakaShrot_SyncStatePacket_ReadPatterns(*MsgPackData, *State\NodePatterns()) - Goto DecodeFailed - EndIf - - ; Pairs - If Not BakaShrot_SyncStatePacket_ReadInteger(*MsgPackData, @Count, 0, #BakaShrot_MaxSyncPairs) - Goto DecodeFailed - EndIf - For i = 1 To Count - AddElement(*State\Pairs()) - If Not BakaShrot_SyncStatePacket_ReadInteger(*MsgPackData, @Value, 0, #BakaShrot_MaxId) - Goto DecodeFailed - EndIf - *State\Pairs()\TopicId = Value - If Not BakaShrot_SyncStatePacket_ReadInteger(*MsgPackData, @Value, 0, #BakaShrot_MaxId) - Goto DecodeFailed - EndIf - *State\Pairs()\NodeId = Value - If Not BakaShrot_SyncStatePacket_ReadInteger(*MsgPackData, @Value, 1, 9223372036854775807) - Goto DecodeFailed - EndIf - *State\Pairs()\MessageId = Value - Next - - ProcedureReturn *State - - ; Everything read so far is tainted, drop it. - DecodeFailed: - FreeStructure(*State) - ProcedureReturn 0 -EndProcedure diff --git a/Commons/Networking/Packets/SyncStateRequestPacket.pbi b/Commons/Networking/Packets/SyncStateRequestPacket.pbi deleted file mode 100644 index a75550f..0000000 --- a/Commons/Networking/Packets/SyncStateRequestPacket.pbi +++ /dev/null @@ -1,82 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: SyncStateRequestPacket.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; ... -; ============================================================================ - - -XIncludeFile "../Packets.pbi" - -; Peer -> Server, asks for the server's sync state, to know which messages it's missing. -; Answered with a SyncState or a RequestRefused. Only carries the base fields. -Structure BakaShrot_SyncStateRequest Extends BakaShrot_PacketBase -EndStructure - - -; Encodes *Request into a freshly allocated buffer, its base fields are set by this procedure. -; *OutSize receives its size in bytes. -; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory. -Procedure.i BakaShrot_SyncStateRequestPacket_Encode(*Request.BakaShrot_SyncStateRequest, *OutSize.Integer) - Protected *MsgPackData.MsgPackData, *Buffer - - *Request\Magic = #BakaShrot_ProtocolMagic - *Request\Version = #BakaShrot_ProtocolVersion - *Request\PacketType = #BakaShrot_PacketType_SyncStateRequest - - *MsgPackData = MsgPackCreate(16) - If Not *MsgPackData - ProcedureReturn 0 - EndIf - - If Not BakaShrot_WritePacketBase(*Request, *MsgPackData) - Goto EncodeFailed - EndIf - - ; Frees *MsgPackData on success, leaves it untouched on failure. - *Buffer = MsgPackFinalize(*MsgPackData) - If Not *Buffer - Goto EncodeFailed - EndIf - - *OutSize\i = MemorySize(*Buffer) - ProcedureReturn *Buffer - - EncodeFailed: - MsgPackFree(*MsgPackData, #True) - ProcedureReturn 0 -EndProcedure - -; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct. -; *MsgPackData stays owned by the caller, and should be discarded on failure. -; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure. -Procedure.i BakaShrot_SyncStateRequestPacket_Decode(*MsgPackData.MsgPackData) - Protected *Request.BakaShrot_SyncStateRequest - - *Request = AllocateStructure(BakaShrot_SyncStateRequest) - If Not *Request - ProcedureReturn 0 - EndIf - - ; The base parser doesn't check which packet it is, that's on us. - If Not BakaShrot_ReadPacketBase(*Request, *MsgPackData) Or *Request\PacketType <> #BakaShrot_PacketType_SyncStateRequest - FreeStructure(*Request) - ProcedureReturn 0 - EndIf - - ProcedureReturn *Request -EndProcedure diff --git a/Commons/Networking/Packets/UploadChunkPacket.pbi b/Commons/Networking/Packets/UploadChunkPacket.pbi deleted file mode 100644 index 5c639de..0000000 --- a/Commons/Networking/Packets/UploadChunkPacket.pbi +++ /dev/null @@ -1,151 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: UploadChunkPacket.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; ... -; ============================================================================ - - -XIncludeFile "../Packets.pbi" - -; C2S, the next part of an upload: ChunkIndex (0 for the first) of UploadId. -; Answered with a ChunkStored, or a RequestRefused (the upload is then dropped). -Structure BakaShrot_UploadChunk Extends BakaShrot_PacketBase - UploadId.q - ChunkIndex.l - *Data - DataSize.l -EndStructure - - -; Encodes *Chunk into a freshly allocated buffer, its base fields are set by this procedure. -; *OutSize receives its size in bytes. -; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory. -Procedure.i BakaShrot_UploadChunkPacket_Encode(*Chunk.BakaShrot_UploadChunk, *OutSize.Integer) - Protected *MsgPackData.MsgPackData, *Buffer - - *Chunk\Magic = #BakaShrot_ProtocolMagic - *Chunk\Version = #BakaShrot_ProtocolVersion - *Chunk\PacketType = #BakaShrot_PacketType_UploadChunk - - If *Chunk\UploadId < 1 Or *Chunk\ChunkIndex < 0 Or *Chunk\ChunkIndex > #BakaShrot_MaxAttachmentChunks Or Not *Chunk\Data Or *Chunk\DataSize < 1 Or *Chunk\DataSize > #BakaShrot_AttachmentChunkSize - ProcedureReturn 0 - EndIf - - *MsgPackData = MsgPackCreate(#BakaShrot_AttachmentChunkSize + 256) - If Not *MsgPackData - ProcedureReturn 0 - EndIf - - If Not BakaShrot_WritePacketBase(*Chunk, *MsgPackData) - Goto EncodeFailed - EndIf - - If MsgPackWriteInteger(*MsgPackData, *Chunk\UploadId) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteInteger(*MsgPackData, *Chunk\ChunkIndex) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteBinary(*MsgPackData, *Chunk\Data, *Chunk\DataSize) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - ; Frees *MsgPackData on success, leaves it untouched on failure. - *Buffer = MsgPackFinalize(*MsgPackData) - If Not *Buffer - Goto EncodeFailed - EndIf - - *OutSize\i = MemorySize(*Buffer) - ProcedureReturn *Buffer - - EncodeFailed: - MsgPackFree(*MsgPackData, #True) - ProcedureReturn 0 -EndProcedure - -; Frees a decoded *Chunk and the data it holds. -Procedure BakaShrot_UploadChunkPacket_Free(*Chunk.BakaShrot_UploadChunk) - If Not *Chunk - ProcedureReturn - EndIf - If *Chunk\Data - FreeMemory(*Chunk\Data) - EndIf - FreeStructure(*Chunk) -EndProcedure - -; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct. -; *MsgPackData stays owned by the caller, and should be discarded on failure. -; Returns 0 on failure, the caller owns the returned struct - free it with BakaShrot_UploadChunkPacket_Free(). -Procedure.i BakaShrot_UploadChunkPacket_Decode(*MsgPackData.MsgPackData) - Protected *Chunk.BakaShrot_UploadChunk, Value.q - - *Chunk = AllocateStructure(BakaShrot_UploadChunk) - If Not *Chunk - ProcedureReturn 0 - EndIf - - ; The base parser doesn't check which packet it is, that's on us. - If Not BakaShrot_ReadPacketBase(*Chunk, *MsgPackData) Or *Chunk\PacketType <> #BakaShrot_PacketType_UploadChunk - Goto DecodeFailed - EndIf - - ; UploadId - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - Value = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 1 - Goto DecodeFailed - EndIf - *Chunk\UploadId = Value - - ; ChunkIndex - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - Value = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > #BakaShrot_MaxAttachmentChunks - Goto DecodeFailed - EndIf - *Chunk\ChunkIndex = Value - - ; Data - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary - Goto DecodeFailed - EndIf - ; A copy, freed with the packet (_Free()). - *Chunk\Data = MsgPackCopyBinary(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not *Chunk\Data - Goto DecodeFailed - EndIf - *Chunk\DataSize = MemorySize(*Chunk\Data) - If *Chunk\DataSize > #BakaShrot_AttachmentChunkSize - Goto DecodeFailed - EndIf - - ProcedureReturn *Chunk - - ; Everything read so far is tainted, drop it. - DecodeFailed: - BakaShrot_UploadChunkPacket_Free(*Chunk) - ProcedureReturn 0 -EndProcedure diff --git a/Commons/Networking/Packets/UploadStartPacket.pbi b/Commons/Networking/Packets/UploadStartPacket.pbi deleted file mode 100644 index 6f70dbe..0000000 --- a/Commons/Networking/Packets/UploadStartPacket.pbi +++ /dev/null @@ -1,138 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: UploadStartPacket.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; ... -; ============================================================================ - - -XIncludeFile "../Packets.pbi" - -; C2S, starts uploading an attachment, before pushing the message it goes with -; (PushMessage's UploadId): Size bytes (1 to #BakaShrot_MaxAttachmentSize, and the -; server's [BakaShrot.Server] MaxAttachmentSize), whose SHA-256 is Sha256. -; Topic: where the message will be pushed, as PushMessage's: "" for the client's -; own. The client's PushTopics must allow it. -; Answered with an UploadStarted, or a RequestRefused. -Structure BakaShrot_UploadStart Extends BakaShrot_PacketBase - Topic.s - Size.q - Sha256.a[#BakaShrot_Sha256Size] -EndStructure - - -; Encodes *Start into a freshly allocated buffer, its base fields are set by this procedure. -; *OutSize receives its size in bytes. -; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory. -Procedure.i BakaShrot_UploadStartPacket_Encode(*Start.BakaShrot_UploadStart, *OutSize.Integer) - Protected *MsgPackData.MsgPackData, *Buffer - - *Start\Magic = #BakaShrot_ProtocolMagic - *Start\Version = #BakaShrot_ProtocolVersion - *Start\PacketType = #BakaShrot_PacketType_UploadStart - - If *Start\Size < 1 Or *Start\Size > #BakaShrot_MaxAttachmentSize - ProcedureReturn 0 - EndIf - - *MsgPackData = MsgPackCreate(64) - If Not *MsgPackData - ProcedureReturn 0 - EndIf - - If Not BakaShrot_WritePacketBase(*Start, *MsgPackData) - Goto EncodeFailed - EndIf - - If MsgPackWriteString(*MsgPackData, *Start\Topic) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteInteger(*MsgPackData, *Start\Size) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteBinary(*MsgPackData, @*Start\Sha256[0], #BakaShrot_Sha256Size) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - ; Frees *MsgPackData on success, leaves it untouched on failure. - *Buffer = MsgPackFinalize(*MsgPackData) - If Not *Buffer - Goto EncodeFailed - EndIf - - *OutSize\i = MemorySize(*Buffer) - ProcedureReturn *Buffer - - EncodeFailed: - MsgPackFree(*MsgPackData, #True) - ProcedureReturn 0 -EndProcedure - -; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct. -; *MsgPackData stays owned by the caller, and should be discarded on failure. -; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure. -Procedure.i BakaShrot_UploadStartPacket_Decode(*MsgPackData.MsgPackData) - Protected *Start.BakaShrot_UploadStart, Value.q, ReadSize.q - - *Start = AllocateStructure(BakaShrot_UploadStart) - If Not *Start - ProcedureReturn 0 - EndIf - - ; The base parser doesn't check which packet it is, that's on us. - If Not BakaShrot_ReadPacketBase(*Start, *MsgPackData) Or *Start\PacketType <> #BakaShrot_PacketType_UploadStart - Goto DecodeFailed - EndIf - - ; Topic - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String - Goto DecodeFailed - EndIf - *Start\Topic = MsgPackReadString(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success - Goto DecodeFailed - EndIf - - ; Size - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - Value = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 1 Or Value > #BakaShrot_MaxAttachmentSize - Goto DecodeFailed - EndIf - *Start\Size = Value - - ; Sha256 - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary - Goto DecodeFailed - EndIf - ; Anything bigger than the struct's array is rejected by MsgPackReadBinary, anything smaller by the size check. - ReadSize = MsgPackReadBinary(*MsgPackData, @*Start\Sha256[0], #BakaShrot_Sha256Size) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or ReadSize <> #BakaShrot_Sha256Size - Goto DecodeFailed - EndIf - - ProcedureReturn *Start - - ; Everything read so far is tainted, drop it. - DecodeFailed: - FreeStructure(*Start) - ProcedureReturn 0 -EndProcedure diff --git a/Commons/Networking/Packets/UploadStartedPacket.pbi b/Commons/Networking/Packets/UploadStartedPacket.pbi deleted file mode 100644 index 39fecc4..0000000 --- a/Commons/Networking/Packets/UploadStartedPacket.pbi +++ /dev/null @@ -1,120 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: UploadStartedPacket.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; ... -; ============================================================================ - - -XIncludeFile "../Packets.pbi" - -; S2C, answers an UploadStart: send the data with UploadChunks for UploadId, in -; order, ChunkSize bytes each (the last one what's left). -Structure BakaShrot_UploadStarted Extends BakaShrot_PacketBase - UploadId.q - ChunkSize.l -EndStructure - - -; Encodes *Started into a freshly allocated buffer, its base fields are set by this procedure. -; *OutSize receives its size in bytes. -; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory. -Procedure.i BakaShrot_UploadStartedPacket_Encode(*Started.BakaShrot_UploadStarted, *OutSize.Integer) - Protected *MsgPackData.MsgPackData, *Buffer - - *Started\Magic = #BakaShrot_ProtocolMagic - *Started\Version = #BakaShrot_ProtocolVersion - *Started\PacketType = #BakaShrot_PacketType_UploadStarted - - If *Started\UploadId < 1 Or *Started\ChunkSize < 1 Or *Started\ChunkSize > #BakaShrot_AttachmentChunkSize - ProcedureReturn 0 - EndIf - - *MsgPackData = MsgPackCreate(64) - If Not *MsgPackData - ProcedureReturn 0 - EndIf - - If Not BakaShrot_WritePacketBase(*Started, *MsgPackData) - Goto EncodeFailed - EndIf - - If MsgPackWriteInteger(*MsgPackData, *Started\UploadId) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - If MsgPackWriteInteger(*MsgPackData, *Started\ChunkSize) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - - ; Frees *MsgPackData on success, leaves it untouched on failure. - *Buffer = MsgPackFinalize(*MsgPackData) - If Not *Buffer - Goto EncodeFailed - EndIf - - *OutSize\i = MemorySize(*Buffer) - ProcedureReturn *Buffer - - EncodeFailed: - MsgPackFree(*MsgPackData, #True) - ProcedureReturn 0 -EndProcedure - -; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct. -; *MsgPackData stays owned by the caller, and should be discarded on failure. -; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure. -Procedure.i BakaShrot_UploadStartedPacket_Decode(*MsgPackData.MsgPackData) - Protected *Started.BakaShrot_UploadStarted, Value.q - - *Started = AllocateStructure(BakaShrot_UploadStarted) - If Not *Started - ProcedureReturn 0 - EndIf - - ; The base parser doesn't check which packet it is, that's on us. - If Not BakaShrot_ReadPacketBase(*Started, *MsgPackData) Or *Started\PacketType <> #BakaShrot_PacketType_UploadStarted - Goto DecodeFailed - EndIf - - ; UploadId - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - Value = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 1 - Goto DecodeFailed - EndIf - *Started\UploadId = Value - - ; ChunkSize - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer - Goto DecodeFailed - EndIf - Value = MsgPackReadInteger(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 1 Or Value > #BakaShrot_AttachmentChunkSize - Goto DecodeFailed - EndIf - *Started\ChunkSize = Value - - ProcedureReturn *Started - - ; Everything read so far is tainted, drop it. - DecodeFailed: - FreeStructure(*Started) - ProcedureReturn 0 -EndProcedure diff --git a/Commons/Networking/SocketWait.pbi b/Commons/Networking/SocketWait.pbi deleted file mode 100644 index 65edc5b..0000000 --- a/Commons/Networking/SocketWait.pbi +++ /dev/null @@ -1,141 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: SocketWait.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; BakaShrot Socket waits -; -; Sleeps until one of a few sockets has something to read (data, a new -; connection, or a disconnect), instead of polling NetworkClientEvent() / -; NetworkServerEvent() with Delay(): -; BakaShrot_SocketSet_Clear(@Set) -; BakaShrot_SocketSet_Add(@Set, ConnectionID(Connection)) ; or ServerID() -; BakaShrot_SocketSet_Wait(@Set, TimeoutMs) -; ... then NetworkClientEvent() / NetworkServerEvent() as usual. -; Only call it once those returned #PB_NetworkEvent_None: PureBasic may -; already hold events it hasn't returned yet, that select() can't see. -; -; Windows: select() from ws2_32. Elsewhere: a plain Delay(1) for now. -; ============================================================================ - -; Most sockets in one wait, the others are left out (they're still served, -; just with up to TimeoutMs of delay). -#BakaShrot_SocketSet_MaxSockets = 1024 - - -CompilerIf #PB_Compiler_OS = #PB_OS_Windows - - ; Same layout as Winsock's fd_set, with a bigger array: Winsock reads - ; Count entries, whatever FD_SETSIZE says. - Structure BakaShrot_SocketSet - Count.l - CompilerIf #PB_Compiler_Processor = #PB_Processor_x64 - Padding.l - CompilerEndIf - Sockets.i[#BakaShrot_SocketSet_MaxSockets] - EndStructure - - Structure BakaShrot_TimeVal - Seconds.l - Microseconds.l - EndStructure - - Prototype.l BakaShrot_Select_Prototype(Ignored.l, *ReadSet, *WriteSet, *ErrorSet, *Timeout) - - Global BakaShrot_Select.BakaShrot_Select_Prototype = 0 - Global BakaShrot_SelectLoaded.i = #False - Global BakaShrot_SelectMutex.i = CreateMutex() - - Procedure BakaShrot_SocketSet_Load() - Protected Library.i - - LockMutex(BakaShrot_SelectMutex) - If Not BakaShrot_SelectLoaded - Library = OpenLibrary(#PB_Any, "ws2_32.dll") - If Library - BakaShrot_Select = GetFunction(Library, "select") - EndIf - BakaShrot_SelectLoaded = #True - EndIf - UnlockMutex(BakaShrot_SelectMutex) - EndProcedure - - Procedure BakaShrot_SocketSet_Clear(*Set.BakaShrot_SocketSet) - *Set\Count = 0 - EndProcedure - - Procedure BakaShrot_SocketSet_Add(*Set.BakaShrot_SocketSet, Socket.i) - If Socket And *Set\Count < #BakaShrot_SocketSet_MaxSockets - *Set\Sockets[*Set\Count] = Socket - *Set\Count + 1 - EndIf - EndProcedure - - ; Waits until a socket of *Set is readable, for up to TimeoutMs. - ; Returns #True if one is (or select() failed, to be safe), #False if it - ; timed out. *Set is overwritten, clear and fill it again before reusing it. - Procedure.i BakaShrot_SocketSet_Wait(*Set.BakaShrot_SocketSet, TimeoutMs.i) - Protected Timeout.BakaShrot_TimeVal, Result.l - - If Not BakaShrot_SelectLoaded - BakaShrot_SocketSet_Load() - EndIf - If Not BakaShrot_Select Or *Set\Count = 0 - Delay(1) - ProcedureReturn #True - EndIf - - Timeout\Seconds = TimeoutMs / 1000 - Timeout\Microseconds = (TimeoutMs % 1000) * 1000 - Result = BakaShrot_Select(0, *Set, 0, 0, @Timeout) - If Result < 0 - ; A socket closed meanwhile by another thread, most likely. - Delay(1) - ProcedureReturn #True - EndIf - ProcedureReturn Bool(Result > 0) - EndProcedure - -CompilerElse - - Structure BakaShrot_SocketSet - Count.l - EndStructure - - Procedure BakaShrot_SocketSet_Clear(*Set.BakaShrot_SocketSet) - *Set\Count = 0 - EndProcedure - - Procedure BakaShrot_SocketSet_Add(*Set.BakaShrot_SocketSet, Socket.i) - *Set\Count + 1 - EndProcedure - - Procedure.i BakaShrot_SocketSet_Wait(*Set.BakaShrot_SocketSet, TimeoutMs.i) - Delay(1) - ProcedureReturn #True - EndProcedure - -CompilerEndIf - - -; Waits until Socket is readable, for up to TimeoutMs. -Procedure.i BakaShrot_WaitSocket(Socket.i, TimeoutMs.i) - Protected Set.BakaShrot_SocketSet - - BakaShrot_SocketSet_Clear(@Set) - BakaShrot_SocketSet_Add(@Set, Socket) - ProcedureReturn BakaShrot_SocketSet_Wait(@Set, TimeoutMs) -EndProcedure diff --git a/Commons/Threading/Signal.pbi b/Commons/Threading/Signal.pbi deleted file mode 100644 index d60cbe1..0000000 --- a/Commons/Threading/Signal.pbi +++ /dev/null @@ -1,86 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: Signal.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; BakaShrot Signal -; -; Wakes up a thread waiting for something, instead of it polling with Delay(): -; Waiter: BakaShrot_Signal_Wait(Signal, TimeoutMs), then checks for work. -; Waker: does the work's setup, then BakaShrot_Signal_Set(Signal). -; Signals don't stack: several Set() before a Wait() wake it once, so the -; waiter must handle everything that's there once woken. A Set() before the -; Wait() isn't lost, the Wait() returns right away. -; -; Windows: an auto-reset event. Elsewhere: a semaphore polled every ms, until -; something better is needed there. -; ============================================================================ - -CompilerIf #PB_Compiler_OS = #PB_OS_Windows - - ; Returns 0 on failure. - Procedure.i BakaShrot_Signal_Create() - ; Auto-reset, not set. - ProcedureReturn CreateEvent_(0, #False, #False, 0) - EndProcedure - - Procedure BakaShrot_Signal_Set(Signal.i) - SetEvent_(Signal) - EndProcedure - - ; Waits until Signal is set, for up to TimeoutMs. - ; Returns #True if it was set, #False if it timed out. - Procedure.i BakaShrot_Signal_Wait(Signal.i, TimeoutMs.i) - ; WAIT_OBJECT_0 - ProcedureReturn Bool(WaitForSingleObject_(Signal, TimeoutMs) = 0) - EndProcedure - - Procedure BakaShrot_Signal_Free(Signal.i) - CloseHandle_(Signal) - EndProcedure - -CompilerElse - - Procedure.i BakaShrot_Signal_Create() - ProcedureReturn CreateSemaphore(0) - EndProcedure - - Procedure BakaShrot_Signal_Set(Signal.i) - SignalSemaphore(Signal) - EndProcedure - - Procedure.i BakaShrot_Signal_Wait(Signal.i, TimeoutMs.i) - Protected StartTime.i = ElapsedMilliseconds() - - Repeat - If TrySemaphore(Signal) - ; Doesn't stack, like the Windows version. - While TrySemaphore(Signal) - Wend - ProcedureReturn #True - EndIf - If ElapsedMilliseconds() - StartTime >= TimeoutMs - ProcedureReturn #False - EndIf - Delay(1) - ForEver - EndProcedure - - Procedure BakaShrot_Signal_Free(Signal.i) - FreeSemaphore(Signal) - EndProcedure - -CompilerEndIf diff --git a/Design/Attachments.md b/Design/Attachments.md deleted file mode 100644 index 26b68bc..0000000 --- a/Design/Attachments.md +++ /dev/null @@ -1,162 +0,0 @@ -# Attachments - -A message can have **one attachment**: any bytes (a file, a photo, a dump), -of any size up to the server's `MaxAttachmentSize` (default 1 GB, at most -1 TB). Most messages have none. The message's JSON can say what it is: the -attachment itself has no name or type, only its size and SHA-256. - -Protocol version 4. Code: `Server/Storage/Attachments.pbi` (storage), -`Server/Networking/Networking.pbi` (requests), `Server/Networking/Peers.pbi` -(replication), `Client/BakaShrot_Client.pbi` (DLL). - -## The rules - -- **Sent and stored in parts** of 1 MB (`#BakaShrot_AttachmentChunkSize`, the - last one what's left), one request each: neither end ever holds a whole - attachment in memory (a 512 MB one: the server peaked at 15 MB). -- **Checked with its SHA-256**, given before the first part: the server - checks it once all parts are in (uploads and replicated ones alike), the - client when it reads one back. -- **A message is only stored once all of its attachment is.** The client - uploads it first, then pushes the message with the upload's id: readers - never see a message whose attachment is missing on the server it was - pushed to. Messages stay immutable. -- **Replicated after the messages**, separately: a peer gets the message - first (with the attachment's size and SHA-256), then its data once the - messages are caught up. So on the other servers, a message can be there - before its attachment: `AttachmentReady` tells. -- **Deleted with its message** (the retention): its parts go a few at a - time, in the background. - -## Pushing one - -``` -C -> S UploadStart(topic, size, sha256) same permissions as pushing to that - topic, size <= MaxAttachmentSize -S -> C UploadStarted(upload id, 1 MB) -C -> S UploadChunk(upload id, 0, data) in order, each the right size -S -> C ChunkStored(received, complete 0) - ... -C -> S UploadChunk(upload id, last, data) - server: reads all of it back, checks the SHA-256 (or drops it, refused) -S -> C ChunkStored(received = size, complete 1) -C -> S PushMessage(topic, json, upload id) - server: the upload must be this client's (its node), for that topic, - complete: the message and its attachment are stored together -S -> C MessagePushed(id) -``` - -- An upload belongs to the client's node and the topic it was started for. -- One not pushed within `UploadTimeout` seconds (default 3600) is deleted. -- A refused part doesn't drop the upload; a SHA-256 mismatch does. -- The DLL does all of it in `BakaShrot_PushMessageWithFile()` / - `_WithData()`; it reads a file twice (the SHA-256 first). - -## Reading one - -``` -C -> S GetAttachment(topic, node, message id, part) same permissions as reading -S -> C AttachmentChunk(ids, message id, size, sha256, part, data) -``` - -Any part, in any order (the DLL reads them in order). Refused if the -message has none, or if it isn't all on this server yet (replicated after -its message), or isn't kept here (bigger than this server's -`MaxAttachmentSize`). - -## Replicating - -On its link to a peer, at every check-in, once the messages are sent -(`Design/Packets.md`, Replication): - -``` -P -> S MissingAttachmentsRequest -S -> P MissingAttachments([(topic, node, message id, next part)]) - up to 256 attachments of messages S has, - from what it takes from P, not all here - P: for each one it has, all of it, and sends S (SendTopics/SendNodes): -P -> S ReplicateAttachmentChunk(topic, node, message id, part, data) -S -> P ChunkStored(received, complete) - ... from the part S asked for: resumes after a dropped link - S: once all of it is in, checks the SHA-256 its message came with: - ready, or dropped and asked for again from the start -``` - -- A server relays what it has: an attachment that isn't on P either is - skipped, S asks again at the next check-in, maybe of another peer. -- An attachment bigger than S's `MaxAttachmentSize` is marked not kept - when its message arrives: S never asks for it. -- A message skipped on arrival (past S's max age) has no attachment row: - never asked for either. - -## Storage (schema v7, `db_schema_v7.dbml`) - -| Table | What | -|---|---| -| `attachments` | A message's: size, SHA-256, its blob once any of it is here, state: 0 missing, 1 receiving, 2 ready, 3 not kept. | -| `blobs` | The data of one attachment: whose (topic, node), size, SHA-256, bytes received, state: 0 receiving, 1 complete (an upload waiting for its message), 2 attached, 3 to delete. | -| `blob_chunks` | Its parts, 1 MB each, by (blob, index). | - -- Triggers: deleting a message deletes its `attachments` row, which marks - its blob to delete. The retention thread (`Retention.pbi`) deletes those - parts 32 at a time, along with uploads past `UploadTimeout`, every - `RetentionInterval` seconds, retention rules or not. -- Parts are written through the writer (each one its own transaction), read - on each thread's own connection. -- SQLite reuses the freed pages; `vacuum` gives the space back to the disk. - -## In the clients - -| | DLL | Python | Tools | -|---|---|---|---| -| Push with one | `BakaShrot_PushMessageWithFile(Topic, Json, Path)`, `_WithData(Topic, Json, *Data, Size)` | `push(data, topic, attachment=bytes or path)` | `PushMessage -a ` | -| Does a message have one | `BakaShrot_GetMessageAttachmentSize()`, `BakaShrot_IsMessageAttachmentReady()` | `Message.attachment_size`, `.attachment_ready` | `GetLatestMessage` prints it | -| Read one | `BakaShrot_SaveAttachment(Topic, Node, Id, Path)`, `_LoadAttachment()` + `_GetAttachmentData()` | `save_attachment()`, `get_attachment()` | `GetAttachment ` | - -## Speed - -On one machine (i5-13500, localhost, PB 5.73): 5 MB up in ~80 ms and down -in ~65 ms through the tools; 512 MB up in 8.5 s (SHA-256 on both ends -included) and down in 3.9 s. One part per round trip: over a slow link, -latency adds up (1000 round trips per GB). - -## Tested - -- `Tests/Attachments-Test.ps1` (39 checks, two servers, ports 12410-12411): - one part, several, an exact multiple, one byte; none; replicated - identical; not kept past the other server's limit; too big to push; - deleted with its message, parts included. -- `Tests/AttachmentEdges-Test.ps1` (51 checks, ports 12413-12414), with a - raw protocol client (`Tests/AttachmentEdgeClient.pb`) for what the DLL - never sends: - - a wrong SHA-256: refused at the last part, the upload dropped, pushing - with it refused; - - parts out of order, of the wrong size, repeated, past the end, from - another client: refused, the upload goes on; - - someone else's upload, the wrong topic, attached twice, an unknown id, - too big, a topic the client may not push to or read: refused, the - connection stays up; - - uploads left behind (half sent, complete but never pushed): kept within - `UploadTimeout`, deleted past it (10.7 s for 10), then refused; - - replication resuming: the receiver killed at ~45 MB of 400 MB, - restarted: what it had committed is still there, the sender goes on - from that part, the result is identical; - - a byte flipped in the sender's database: the client refuses it - (SHA-256), the peer drops it, serves nothing, and asks again. -- `check_bakashrot.py` (Python): bytes and files, round trips, refusals. - -## Not done - -- **Resuming an upload** after a dropped connection: the parts are kept - until `UploadTimeout`, but the DLL starts over. (Replication resumes.) -- **Several parts in flight**, for links with high latency. -- **A corrupted copy is sent again and again.** If a server's own stored - copy is damaged (disk, a bug), its peers drop it at every check-in and - ask again: the whole attachment is re-sent every `PeerSyncInterval` - (6 times in 6 s in the test). The server itself never notices, it serves - the damaged parts to clients too (they refuse them, by their SHA-256). - Fix: when a peer answers "doesn't match", the sender checks its own copy - (`HashStorageBlob()`); if it's damaged, it marks it missing, so it gets a - good one back from another peer, and stops sending it. Details, and how - the test should change: `Notes.md`, open item 3. -- **No deduplication**: the same file attached twice is stored twice. diff --git a/Design/Cryptography.md b/Design/Cryptography.md deleted file mode 100644 index 2f216b9..0000000 --- a/Design/Cryptography.md +++ /dev/null @@ -1,226 +0,0 @@ -# Cryptography - what's done, what isn't - -Status (protocol 3, 2026-11-08): every connection is encrypted and -authenticated, and both ends prove who they are. - -- The client seals its Hello for the server's public key: only that server - can read it, and nobody watching learns who connects. -- Both ends make a key pair for this connection, sign the exchange with - their identity keys, and get the connection's keys from it. -- Everything after the ChallengeRequest is encrypted, both ways. - -Still not done: messages aren't signed by the node that wrote them, and -keys sit in plain-text ini files (see the end). - -## Library - -- **libsodium 1.0.22**, the official MSVC release's dynamic build. - - `Build.ps1` extracts it from `Libs/libsodium-1.0.22-msvc.zip` to - `Libs/libsodium/{x64,x86}/`, and copies `libsodium.dll` next to the - programs. - - Linux would link `-lsodium` instead (untested). - - It needs the Visual C++ runtime (`vcruntime140.dll`), packaged with the - release from `Libs/redist/` (`Libs/redist/README.md`). -- **Wrappers:** `Commons/Cryptography/Libsodium.pbi` is the only file that - imports it. On top of it, nothing else calls libsodium: - - `Cipher.pbi`: encrypting and decrypting buffers with a connection's keys. - - `Session.pbi`: the handshake's part, the sealed Hello and the key - exchange. - - The handshake itself, what's signed and in which order, is in - `Commons/Networking/Connections.pbi`. -- **Imported functions:** - -| libsodium | Wrapper | Notes | -|---|---|---| -| `sodium_init` | `InitCryptography()` | Called before any use; repeated calls are fine. | -| `crypto_sign_keypair` | `GenerateKeyPair()` | Used by `Tools/BakaShrotGenerateKeyPairs`. | -| `crypto_sign_detached` | `EncodeData()`, `BakaShrot_SignHandshake()` | **Signs**, the name `EncodeData` is wrong. | -| `crypto_sign_verify_detached` | `DecodeData()`, `BakaShrot_VerifyHandshake()` | **Verifies**, the name `DecodeData` is wrong. | -| `crypto_sign_ed25519_sk_to_pk` | `GetPublicKeyFromPrivateKey()` | Lets a server only keep its private key in its config. | -| `crypto_sign_ed25519_pk_to_curve25519` / `_sk_to_curve25519` | `BakaShrot_Session_SealHello()` / `_LoadHelloKeys()` | The X25519 key of an Ed25519 identity, for the sealed Hello. | -| `crypto_box_seal` / `_seal_open` | `BakaShrot_Session_SealHello()` / `_OpenHello()` | The Hello, sealed for the server. | -| `crypto_kx_keypair` | `BakaShrot_Session_NewKeyPair()` | One per connection and end. | -| `crypto_kx_client_session_keys` / `_server_session_keys` | `BakaShrot_Session_StartClient()` / `_StartServer()` | A key per direction, into the cipher. | -| `crypto_aead_xchacha20poly1305_ietf_encrypt` / `_decrypt` | `BakaShrot_Cipher_Encrypt()`, `_EncryptTo()` / `_Decrypt()` | Every packet after the ChallengeRequest. | -| `crypto_aead_xchacha20poly1305_ietf_keygen` | `BakaShrot_Cipher_GenerateKey()` | Tests only, real keys come from the handshake. | -| `sodium_memzero` | `BakaShrot_Cipher_Clear()`, the `_Clear*()` of `Session.pbi` | Wipes keys. | - -- **Base64 helpers**, in `Libsodium.pbi`: - - `EncodeKeyToString()` encodes a key or signature. - - `DecodeKeyFromString()` refuses anything that doesn't decode to exactly - the expected size. - -## Keys - -- **Identity keys: Ed25519.** A private key is 64 bytes (libsodium's - format: the seed followed by the public key), a public key 32, a - signature 64. One key both signs and receives the sealed Hello (its X25519 - form, libsodium's conversion). -- **Stored as Base64 in ini files, in plain text:** - - A server's own key: `[BakaShrot] PrivateKey`. The server logs its - public key when it starts. - - Who it trusts: `[BakaShrot.Client.] PublicKeys` and - `[BakaShrot.Peer.] PublicKey`. The peer's is also the server it - expects at the other end of its link, so it's required. - - A client's: whatever the app passes to `BakaShrot_SetPrivateKey()`, - `BakaShrot_SetPublicKey()` and `BakaShrot_SetServerPublicKey()` (the - server's). The tools and `bakashrot.py` read them from `client.ini`: - `PrivateKey`, `PublicKey`, `ServerPublicKey`. -- **Connection keys: X25519**, made for each connection by both ends, the - secrets wiped once the cipher has its keys. So a recorded connection - can't be decrypted later, even with both identity keys (forward secrecy). -- **Generated** by `Tools/BakaShrotGenerateKeyPairs`, which `Build.ps1` runs - on every build. -- **Wiping:** - - Wiped from memory after use: BakaShrotGenerateKeyPairs; a server's key when it stops, and - its peer links'; every connection's keys when it ends. - - Not wiped: the client DLL's global copy of its private key, and the - config structures holding the Base64 text. -- **No rotation or revocation**, other than editing the configs and - restarting. - -## Randomness - -The challenge (32 bytes) and the nonce (32 bytes) come from PureBasic's -`OpenCryptRandom()` / `CryptRandomData()`, which use the OS's secure -generator. The connection key pairs and the sealed Hello's throwaway key -come from libsodium's. - -## The handshake - -See `Design/Packets.md` for the packets, `Connections.pbi` for the code. -The client knows the server's public key beforehand. - -1. **Hello, sealed** (`crypto_box_seal` for the server's key): the client's - node (the one it writes as), its Base64 public key, and the public half - of a key pair it made for this connection. -2. The server opens it (another server can't: abort), decodes the key and - checks that a `[BakaShrot.Client.]` has this `Node` and lists this - key. -3. **ChallengeRequest, in plain text:** a fresh random challenge and nonce, - the public half of the server's own pair for this connection, and the - server's signature of the transcript. -4. The client checks the signature with the server's public key: it's the - right server, and nobody swapped a half on the way. Both ends get the - connection's keys from both pairs (`crypto_kx`), every packet from here - on is encrypted (the cipher, below). -5. **ChallengeResponse:** the client signs the transcript, and echoes the - nonce. -6. The server checks the nonce is the one it issued for this connection, - and the signature against the key from the Hello. **AuthAccepted.** - -**The transcript** (`BakaShrot_HandshakeTranscript`, 208 bytes) is what -both sign: a label (`"BakaShrot3 srv"` or `"BakaShrot3 cli"`, padded to 16 -bytes, so one end's signature can't pass as the other's), the client's and -the server's identity keys, both halves, the challenge and the nonce. So -each signature only holds for this connection, between these two. - -What that gets, and why: -- **Only the right server gets anywhere.** The Hello is sealed for it, and - the client won't send anything else until the server signed this - connection's halves with the key the client expects. -- **Only the registered client authenticates.** Same as before: it signs - the challenge, now along with the halves. -- **Nobody in the middle.** Swapping a half breaks a signature; relaying - untouched gets the relay nothing, it doesn't have the secrets. -- **Replays fail.** A replayed Hello gets a fresh challenge and server half, - which the replayer can't answer: the client's half is the client's. A - replayed packet later fails the cipher's sequence check. -- **Hijacking an authenticated connection fails:** an injected packet - doesn't decrypt, the connection is aborted. -- **Hidden from someone watching:** who connects (sealed Hello) and - everything after the ChallengeRequest. Not hidden: that it's BakaShrot, - the server's half and signature, packet sizes and timing. - -The nonce is redundant with the challenge (both are fresh, random, and -signed), but it's harmless and kept as designed. - -## The cipher (`Commons/Cryptography/Cipher.pbi`) - -The crypto of the data itself, so no packet handler or framing code has to -do any: a `BakaShrot_Cipher` per connection holds the keys, then takes -buffers. `BakaShrot_ConnectionMetadata\Cipher`, set up by the handshake. - -- **`BakaShrot_Cipher_InitWithKeys(*Cipher, *SendKey, *ReceiveKey)`**: a key - per direction, as the handshake gives them (refuses the same key twice). - Or **`_Init(*Cipher, *Key, Role)`**, one key shared by both ends, `Role` - `#BakaShrot_Cipher_Client` or `#BakaShrot_Cipher_Server`. -- **`BakaShrot_Cipher_Encrypt(*Cipher, *Data, Size, *OutSize)`** returns a new - buffer: `[sequence number, 8 bytes][encrypted data][16-byte tag]`, 24 bytes - more than the data (`#BakaShrot_Cipher_Overhead`). `_EncryptTo()` writes it - into a given buffer (the frame, in `BakaShrot_SendPacket()`). -- **`BakaShrot_Cipher_Decrypt(*Cipher, *Sealed, Size, *OutSize)`** returns the - data in a new buffer, or 0: then abort the connection. -- **`BakaShrot_Cipher_Clear(*Cipher)`** wipes the keys once done. - -What it guarantees: nobody without the key reads, changes, forges or -truncates a buffer (XChaCha20-Poly1305, libsodium's AEAD), and nobody -replays, reorders, drops or reflects one: each carries its sequence number, -the receiver only takes the next one, and each direction has its own key -(or its own nonces with one key). Nonces never repeat within a key: a key is -only ever used for one connection. - -Why XChaCha20-Poly1305 with sequence numbers rather than -`crypto_secretstream_*`: same primitives, but the buffers stay independent -(no stream state beyond the counter), the format is simple to describe in -`Design/Packets.md`, and replay/reorder protection comes from the sequence -check, which TCP's ordering makes strict. - -**Where it's used:** in the framing, so the packets don't know about it. -`BakaShrot_SendPacket()` encrypts when given the connection's cipher (0 only -for the Hello and the ChallengeRequest), `BakaShrot_OpenFrame()` decrypts a -frame once the cipher is set up. On the server, the client's own thread -decrypts, outside the server's mutex; the listener only gathers bytes. -Frames are up to `#BakaShrot_MaxPacketSize + #BakaShrot_Cipher_Overhead` -once authenticated. - -## Tests - -- `Tests/CipherTest.pb` (56 checks, PB 5.73 and 6.40's C backend), without - sockets: - - The cipher: both directions, a bit flipped at every byte refused, cut - short, replayed, reordered, reflected to its sender or to another client - with the same key, another key, empty data, 16 MB (~33 ms both ways), - two keys, clearing, `_EncryptTo()`. - - The session: a sealed Hello only its server opens, without the identity - showing, tampered or cut short refused, an invalid server key refused; - the key exchange agrees both ways, a key per direction, the pairs wiped, - a swapped half or another connection's keys don't decrypt, an all-zero - half refused. -- `Tests/wire_check.py`, run by `Tests/Python-Test.ps1`: a proxy between - the client and the server records every byte. The pushed message, the - client's topic, node and public key never show up in it; a byte flipped - after the handshake drops the connection ("doesn't decrypt" in the - server's log); another server's public key can't connect ("isn't sealed - for this server"). -- `Tests/HandshakeTest.pb`: the handshake packets' fields, without crypto. -- Every end-to-end test (`Tests/*.ps1`, the release's smoke test) runs over - encrypted connections, peer links included. - -## What's NOT done (in rough order of importance) - -1. **Messages aren't signed by the node that first wrote them,** so - replicated data can't be verified: a peer is trusted with what it sends - (`Design/ReplicationIssues.md`, issue 3). -2. **Private keys sit in plain-text ini files.** -3. **No key rotation or revocation**, and no way to pin more than one key - for a server (to change it without a flag day). -4. **One identity key signs and opens sealed boxes** (its X25519 form). - libsodium supports it and it's a common pattern, but a separate key for - each would be cleaner. -5. **Anyone can make the server work a little:** each new connection costs - it opening a sealed box, a key pair and a signature before the client - proved anything (before: one signature check). Only the 4 KB handshake - limit and the timeout bound it, no rate limit. -6. **The client DLL doesn't wipe its private key**, nor the configs their - Base64 text. - -## Ideas for when it gets abstracted - -- **A small interface**, so libsodium can be swapped or wrapped without - touching the networking: `Sign`, `Verify`, `GenerateKeyPair`, - `PublicKeyFromPrivateKey`, `Random`, plus `Session.pbi` and `Cipher.pbi` - as they are. Rename `EncodeData`/`DecodeData` to `Sign`/`Verify` while at - it. -- **Per-message signatures** by the origin node, stored with the message and - checked on replication, for item 1. diff --git a/Design/Packets.md b/Design/Packets.md deleted file mode 100644 index 43c558f..0000000 --- a/Design/Packets.md +++ /dev/null @@ -1,362 +0,0 @@ -# Protocol - packets, flows and conventions - -Reference for working on BakaShrot's networking. Related docs: - -- `Design/Cryptography.md`: how the handshake proves both ends and sets up - the encryption, and what's still left. -- `Design/ReplicationIssues.md`: known replication problems, with a benchmark. -- `Design/StorageConcurrency.md`: the database threading problem and its - planned fix. - -## Where things live - -| What | Where | -|---|---| -| Packet base, type ids, limits | `Commons/Networking/Packets.pbi` | -| What a topic or node "ref" is: a name or an id | `Commons/Networking/Names.pbi` | -| Server: which name every id has, translating names to ids | `Server/Storage/Names.pbi` | -| One file per packet, with its `_Encode` and `_Decode` | `Commons/Networking/Packets/*.pbi` | -| Framing (and its encryption), connection metadata, the signed handshake transcript, `BakaShrot_GetPacketType` | `Commons/Networking/Connections.pbi` | -| Sealed Hello, key exchange; encrypting a buffer | `Commons/Cryptography/Session.pbi`, `Commons/Cryptography/Cipher.pbi` | -| Client side of the handshake, on any connection | `Commons/Networking/Outbound.pbi` | -| Server: listener, one thread per client, request handlers | `Server/Networking/Networking.pbi` | -| Server: links to peers, check-ins, sending missing messages and attachments | `Server/Networking/Peers.pbi` | -| Server: storing messages (the writer), attachments, deleting old ones | `Server/Storage/Writer.pbi`, `Attachments.pbi`, `Retention.pbi` | -| Server: its config, and the example one | `Server/Config/Config.pbi`, `Server/Config/schema.ini` | -| Server: the root thread, which stops and starts every worker (restart, vacuum) | `Server/Root.pbi` | -| Client DLL (one connection) | `Client/BakaShrot_Client.pbi`, used through `BakaShrot_Client_Prototypes.pbi` | -| Python client, over the DLL | `Interactors/Python/bakashrot.py` | -| Ready-to-run setups (configs, start scripts, a README each) | `Examples/`, listed in `Examples/README.md` | -| Tools: connecting through the DLL from an ini; ending (waits for Enter when started from Explorer) | `Tools/Common/ToolClient.pbi`, `Tools/Common/ToolConsole.pbi` | -| Tests of the packets alone, without sockets | `Tests/HandshakeTest.pb` | -| Tests of the cipher and the session crypto, without sockets | `Tests/CipherTest.pb` | -| What goes over the wire (a recording proxy) | `Tests/wire_check.py`, run by `Tests/Python-Test.ps1` | -| A raw protocol client, for what the DLL never sends | `Tests/AttachmentEdgeClient.pb`, run by `Tests/AttachmentEdges-Test.ps1` | -| Every end-to-end suite | `Tests/*.ps1`, listed in `CLAUDE.md` | - -## Transport and framing - -- **TCP, IPv4.** A server listens on `[BakaShrot.Server] Host:Port`. -- **Frames:** every packet is sent as one frame: its size as a **4-byte - little-endian** unsigned integer, followed by the packet itself. - - `BakaShrot_SendPacket()` sends a frame and loops until all of it is - sent. -- **Encryption:** the frame's content, not its size: - - Frame 1, the Hello: sealed for the server's public key - (`crypto_box_seal`, 48 bytes more). - - Frame 2, the ChallengeRequest: plain text, signed by the server. - - Every frame after it, both ways: encrypted with the connection's keys - (`Cipher.pbi`): `[sequence number, 8 bytes LE][encrypted packet][16-byte - tag]`, 24 bytes more. A frame that doesn't decrypt, or out of sequence, - aborts the connection. `BakaShrot_SendPacket()` encrypts when given - the cipher, `BakaShrot_OpenFrame()` decrypts once it's set up. - - `BakaShrot_Inbox_*` gathers received bytes and takes complete frames out - of them. -- **Limits:** - - A packet is 1 to `#BakaShrot_MaxHandshakePacketSize` (4 KB) bytes until - the other end is authenticated, then 1 to `#BakaShrot_MaxPacketSize` - (16 MB, plus the 24 bytes of encryption). A frame announcing anything - else is invalid, as soon as its - 4-byte size arrived. The server lifts it (`BakaShrot_Inbox_Lift()`) - before sending AuthAccepted, the client once it got it. So anyone can - connect, but only those with a key can make the other end hold big - frames. - - At most 2 frames' worth of data may wait, unread, in an inbox - (`BakaShrot_Inbox_MaxSize()`: ~8 KB, then ~32 MB). - - Breaking either limit aborts the connection. - - A pushed message is at most `#BakaShrot_MaxMessageSize` (16 MB - 4 KB) - of UTF-8, refused above (by the client DLL already), so a stored - message fits in every packet that carries one later: LatestMessage, a - ReplicateMessages batch of one, without the fields around it going over. -- **Encrypted and authenticated:** see `Design/Cryptography.md`. - -## Packet layout - -- **A packet is a plain sequence of MessagePack values**, not a map or an - array, read in order with PB-MessagePack: - 1. `Magic` (integer), always `#BakaShrot_ProtocolMagic` (`0x42534854`, - "BSHT"). - 2. `Version` (integer), always `#BakaShrot_ProtocolVersion` (6: - refusals carry a code; 5: the Hello carries the node only, the default - topic is the server's; 4: attachments; 3: the Hello sealed, a key per connection, everything - after the ChallengeRequest encrypted, times; 2 had topics and nodes by - name, in plain text; 1 had ids only). - 3. `PacketType` (integer), one of the ids below. - 4. The packet's own fields, in the order listed. -- **Encodings:** strings are UTF-8 MessagePack strings, the nonce a - MessagePack binary. -- **Decoding:** `BakaShrot_ReadPacketBase()` checks the magic, the version - and that the type is positive. Each `_Decode` then checks it's **its own** - type, and checks every field's MessagePack type, read error and range. - Anything wrong means the whole packet is rejected. -- **Not checked:** trailing data after the last field is ignored. - -### Topics and nodes: names and ids - -- **Each server has its own ids** (0-65535) for topics and nodes, and - gives them to the names: the config lists the topics - (`[BakaShrot.Topics]`), the nodes come from the sections that define - them (its own, its peers', its clients') and optionally - `[BakaShrot.Nodes]`; a name keeps the id the database has for it, a new - one gets the lowest free one (`Server/Storage/Names.pbi`). The **name is - what's shared**: "logs" can be 1 on one server and 200 on another. -- **A ref** is how a packet gives a topic or node: a name (1-64 of - `A-Z a-z 0-9 _ . -`, not only digits, any case), or an id in digits, - which always means that id on the receiving server. An unnamed topic or - node goes by its id in digits. -- **Clients** give refs in their requests, the server resolves them in its - own names. **Servers** send names to each other, never rely on ids - matching: the sync state maps the sender's ids to names, and the batches - carry names. -- **Only what's named on both servers replicates.** Unnamed topics and - nodes, and names the other server doesn't have, are dropped, unless the - receiver's `AcceptTopics` / `AcceptNodes` for that peer has a wildcard - (`*`, `sensors.*`; `AcceptNodes` is `*` by default) matching it: it's then added there with an id of its - own. The sync state lists every name the receiver takes, and its - wildcards, so the sender only sends those and nothing gets refused at - every check-in. - -### Packet types - -Direction: **C** client, **S** server, **P** peer, a server acting as a client -over its own link to another server. - -| Id | Packet | Dir | Fields, in order | Answered by | -|---|---|---|---|---| -| 0 | None | | Never valid. | | -| 1-3 | | | Used by the removed `AuthenticationPacket.pbi`, don't reuse. | | -| 4 | ClientHello | C→S | `ClientNode` str (ref, the node it writes as), `ClientPubKeyB64` str, `ClientSessionKey` bin (32 bytes). Sent sealed for the server's key | ChallengeRequest | -| 5 | ChallengeRequest | S→C | `ChallengeB64` str (32 bytes), `Nonce` bin (32 bytes), `ServerSessionKey` bin (32 bytes), `ServerSignature` bin (64 bytes, of the transcript). The last packet in plain text | ChallengeResponse | -| 6 | ChallengeResponse | C→S | `ChallengeResponseB64` str (64-byte signature of the transcript), `Nonce` bin (32 bytes) | AuthAccepted | -| 7 | AuthAccepted | S→C | None. | | -| 8 | PushMessage | C→S | `Topic` str (ref, "" for the client's own), `JsonData` str, `UploadId` int (its attachment, 0 for none) | MessagePushed / RequestRefused | -| 9 | MessagePushed | S→C | `MessageId` int ≥ 1 | | -| 10 | GetLatestMessage | C→S | `Topic` str (ref), `Node` str (ref) | LatestMessage / RequestRefused | -| 11 | LatestMessage | S→C | `TopicId`, `NodeId` int 0-65535 (the server's), `TopicName`, `NodeName` str (names, or ids in digits), `MessageId` int ≥ 1, `PushedAt` int (time, see below), `JsonData` str, `AttachmentSize` int (0 for none), `AttachmentReady` int 0/1 | | -| 12 | RequestRefused | S→C | `Code` int 1-99 (what kind, `#BakaShrot_Refused_*` in `Client/BakaShrot_ErrorCodes.pbi`: what clients act on), `Reason` str, for logs and humans | | -| 13 | SyncStateRequest | P→S | None. | SyncState / RequestRefused | -| 14 | SyncState | S→P | `TopicCount` int, then each topic's `Id` int and `Name` str (the named topics S takes from P); `NodeCount` int, then each node's `Id` and `Name` (the named nodes S takes from P); `TopicPatternCount` int, then each pattern str; `NodePatternCount` int, then each pattern str (S's wildcards for P, `*` included); `PairCount` int, then each pair's `TopicId`, `NodeId`, `MessageId`. Ids are S's own, names are never digits | | -| 15 | ReplicateMessages | P→S | `Topic` str, `Node` str (names, never digits), `Count` int 1-10000, then each message's `MessageId` int (≥ 1, strictly increasing), `PushedAt` int (as stored, from its origin), `JsonData` str, `AttachmentSize` int (0 for none) and `AttachmentSha256` bin (32 bytes, empty for none) | MessagePushed (last id) / RequestRefused | -| 16 | QueryRequest | C→S | `Sql` str | QueryResult / RequestRefused | -| 17 | QueryResult | S→C | `JsonResult` str: `{"columns":[...],"rows":[[...],...]}`, every value a string or null | | -| 18 | ResolveName | C→S | `Kind` int (1 topic, 2 node), `Ref` str | NameResolved / RequestRefused | -| 19 | NameResolved | S→C | `Kind` int, `Id` int 0-65535 (the server's), `Name` str ("" if unnamed) | | -| 20 | ListNames | C→S | `Kind` int (1 topics, 2 nodes) | NamesList | -| 21 | NamesList | S→C | `Kind` int, `Truncated` int 0/1, `Count` int, then each entry's `Id` int, `Name` str ("" if unnamed), `Origin` str ("config", "id") | | -| 22 | GetMessages | C→S | `Topic` str (ref), `Node` str (ref), `AfterMessageId` int ≥ 0, `Limit` int 1-10000 | Messages / RequestRefused | -| 23 | Messages | S→C | `TopicId`, `NodeId` int 0-65535 (the server's), `TopicName`, `NodeName` str (names, or ids in digits), `More` int 0/1, `Count` int 0-10000, then each message's `MessageId` int (≥ 1, strictly increasing, above `AfterMessageId`), `PushedAt` int, `JsonData` str, `AttachmentSize` int (0 for none) and `AttachmentReady` int 0/1 | | -| 24 | UploadStart | C→S | `Topic` str (ref, "" for the client's own), `Size` int 1-MaxAttachmentSize, `Sha256` bin (32 bytes) | UploadStarted / RequestRefused | -| 25 | UploadStarted | S→C | `UploadId` int ≥ 1, `ChunkSize` int (1 MB) | | -| 26 | UploadChunk | C→S | `UploadId` int, `ChunkIndex` int ≥ 0 (the next one), `Data` bin (1 MB, the last one what's left) | ChunkStored / RequestRefused | -| 27 | ChunkStored | S→C, S→P | `Received` int (bytes so far), `Complete` int 0/1 (all of it, SHA-256 checked) | | -| 28 | GetAttachment | C→S | `Topic`, `Node` str (refs), `MessageId` int ≥ 1, `ChunkIndex` int ≥ 0 | AttachmentChunk / RequestRefused | -| 29 | AttachmentChunk | S→C | `TopicId`, `NodeId` int (the server's), `MessageId` int, `Size` int, `Sha256` bin (32 bytes), `ChunkIndex` int, `Data` bin | | -| 30 | MissingAttachmentsRequest | P→S | None. | MissingAttachments / RequestRefused | -| 31 | MissingAttachments | S→P | `Count` int 0-256, then each one's `Topic`, `Node` str (names), `MessageId` int, `NextChunk` int | | -| 32 | ReplicateAttachmentChunk | P→S | `Topic`, `Node` str (names), `MessageId` int, `ChunkIndex` int (the next one), `Data` bin | ChunkStored / RequestRefused | - -**Attachments** (24-32, and the attachment fields): see -`Design/Attachments.md`. At most one per message, in parts of 1 MB, checked -with their SHA-256, replicated after their message. - -**Times** (`PushedAt`): milliseconds since 1970-01-01 00:00:00 UTC, 1 to -`#BakaShrot_MaxTimestamp` (9999-12-31), anything else aborts. A message is -stamped by the server it's pushed to, when the push arrives (its clock, not -the client's), and keeps that time on every server it's replicated to. - -## Rules - -- **One request at a time.** A client sends one request and waits for its - single answer before the next one. -- **Refuse or abort:** - - **Refuse** (RequestRefused, the connection stays open) for things that - are valid but not allowed: permissions, no message found, too big, - a failed query, a regular client sending replication packets. Each with - a code (`Client/BakaShrot_ErrorCodes.pbi`): NotAllowed, UnknownName, - NotFound, NotReady, TooBig, NoDefaultTopic, InvalidRequest, - DataMismatch, QueryFailed, ServerError. Clients get them from - `BakaShrot_GetLastError()` (the DLL) or `error.code` (Python), with - their own codes (100+) for what never reached the server or broke the - connection. - - **Abort** (the connection is closed) for anything malformed or out of - order: an invalid frame or packet, a packet type that isn't expected at - that point, an answer to a different request, a timeout during the - handshake. - - The client side applies the same rules to the answers it gets. -- **Timeouts:** - - The server gives a client `#BakaShrot_Net_HandshakeTimeout` (10 s) per - handshake step, then waits for requests forever. - - The client side (`Outbound.pbi`) waits `#BakaShrot_Outbound_Timeout` - (10 s) for each answer. -- **The identity is fixed by the handshake.** Requests never carry who sends - them; the server uses the authenticated topic and node. A push picks its - topic, never its node. - -## Flows - -### Handshake (every connection) - -``` - client: knows the server's Ed25519 public key (ServerPublicKey), - makes a key pair for this connection -C -> S ClientHello node (ref, the one it writes as) + Base64 public key - + the public half of the client's pair, - sealed for the server's public key - server: opens it (or aborts: not for this server), the node must - resolve to its id, the key must decode to 32 bytes, and one - [BakaShrot.Client.] must have this Node and list this key -S -> C ChallengeRequest fresh random challenge + nonce, the public half of - the server's pair, and the server's signature of - the transcript (in plain text) - client: the signature checks out with ServerPublicKey (or aborts) - both: the connection's keys, from both pairs (crypto_kx), the - pairs' secrets wiped; everything from here on is encrypted -C -> S ChallengeResponse the client's signature of the transcript, nonce echoed - server: nonce == the one issued, signature valid for the Hello's key -S -> C AuthAccepted status -> Authenticated -``` - -The transcript both sign (`BakaShrot_HandshakeTranscript`, 208 bytes): -a 16-byte label (`"BakaShrot3 srv"` or `"BakaShrot3 cli"`, zero-padded), -the client's and the server's Ed25519 public keys, the client's and the -server's session halves, the challenge, the nonce. - -- The status moves through New → Challenged → Authenticated, or Aborted / - Disconnected (`BakaShrot_ConnectionStatuses`). -- When authenticating, the server also records two things for the - connection: - - Its **permissions**, from the matching client section: `AllowRead`, - `AllowWrite`, `AllowQuery`, and the `PushTopics` / `ReadTopics` filters - (default: its `DefaultTopic`, nothing without one), and that - `DefaultTopic`: the topic of its pushes that don't name one. - - Whether it's a **peer**: its key and node match a - `[BakaShrot.Peer.]`, and then its `AcceptTopics`. - -### Client requests - -``` -PushMessage(t, json) AllowWrite, t in PushTopics ("" = its DefaultTopic, - refused without one), at most - #BakaShrot_MaxMessageSize. JSON or not: stored as - is, SQLite flags it in is_json - -> stored under t and the authenticated node with the - next message id, stamped with now (pushed_at) - -> MessagePushed(id) -GetLatestMessage(t, n) AllowRead, t in ReadTopics -> LatestMessage -GetMessages(t, n, after, AllowRead, t in ReadTopics -> Messages: those above - limit) after, in id order, at most limit, fewer once they - reach ~1 MB (#BakaShrot_MessagesBatchBytes, a - bigger one alone). None isn't a refusal. More = 1 - if others follow: ask again after the last id -ResolveName(kind, ref) topics: in PushTopics or ReadTopics, or AllowQuery - -> NameResolved(id, name) -ListNames(kind) topics: those in PushTopics or ReadTopics, all with - AllowQuery -> NamesList(entries) -QueryRequest(sql) AllowQuery -> QueryResult -``` - -**Raw queries** (`RunReadOnlyQuery()` in `Server/Storage/Storage.pbi`) are kept -read-only by three things: -1. The SQL must start with `SELECT` or `WITH`. -2. It runs on its own fresh connection with `PRAGMA query_only = ON`. Writes - fail, and turning the pragma off only affects that throwaway connection. -3. Only the first statement runs. - -Statements with no result columns are refused, and so are results over -10000 rows or too big for one packet. An error while reading the rows -refuses the whole query with SQLite's message, never a partial or empty -result: JSON functions over a row that isn't JSON give "malformed JSON", -add `is_json = 1` to the WHERE (or `CASE WHEN is_json THEN ... END`). PureBasic reports no column types for -SQLite, so values come back as strings. - -### Replication (between servers) - -Each server opens its own link to every `[BakaShrot.Peer.]`, -authenticates as itself (the peer must list it as a client), and retries -every `PeerRetryDelay` seconds when that fails or the link drops. On its own -link, every `PeerSyncInterval` seconds, starting right away: - -``` -P -> S SyncStateRequest -S -> P SyncState every name S takes from P (its AcceptTopics and - AcceptNodes for P), their wildcards, and - MAX(message_id) for each topic/node of those, in - S's ids - P: compares with its own state (GetSyncState()), matching by name, - drops what's unnamed on its side, or neither listed by S nor - matching one of S's wildcards (BakaShrot_Names_NoteDropped(), a - no-op for now), and for every pair in its SendTopics and - SendNodes for S that S is behind on (0 for a name S doesn't have - yet): -P -> S ReplicateMessages the topic and node names, the next missing messages - of that pair, in id order, with their original - message ids and pushed_at: up to PeerBatchSize of them, cut short - at about 64 KB (a bigger message goes alone) - S: resolves the names to its own ids, adds the ones a wildcard took, - refuses what it doesn't take (only if its config changed since - its sync state), see Server/Storage/Names.pbi -S -> P MessagePushed(id) the batch stored in one transaction with - INSERT OR IGNORE, the last id echoed - ... until caught up, or the first refusal for that pair - then the attachments of the messages S now has: -P -> S MissingAttachmentsRequest -S -> P MissingAttachments what S lacks, among what it takes from P -P -> S ReplicateAttachmentChunk ... -> S -> P ChunkStored, per part - (Design/Attachments.md) -``` - -- **Batch size:** `PeerBatchSize` is set on the sending side, in - `[BakaShrot.Server]` (default 100, clamped to 1-10000). -- **Size check:** the sender estimates a batch's size with - `#BakaShrot_ReplicateBatchOverhead` + `#BakaShrot_ReplicateMessageOverhead` - per message + the JSON's UTF-8 bytes, and stops adding messages before - it would go over `#BakaShrot_ReplicateBatchBytes` (64 KB, as when that - was the packet limit: short transactions, little memory). A message - bigger than that goes in a batch of its own. It also stops reading rows - from the database once it has about that much (`GetMessagesAfter()`). - -- **Both directions** are covered because each server pushes over the link - it opened itself. -- **Only peers may replicate:** a regular client sending a SyncStateRequest - or ReplicateMessages is refused with `Only peers can replicate`. -- **Unexpected packets:** a packet on a link outside a check-in drops the - link. -- **Retention:** each server deletes a topic's messages past its own - `[BakaShrot.Retention]` max age (`Server/Storage/Retention.pbi`), by their - pushed_at. The sync state comes from `node_heads`, which deleting leaves - alone: a server still says it has what it deleted, so peers don't send it - again. What a peer sends already past this server's max age isn't - stored, but counts as received the same way (still acknowledged). A - peer that links later only gets what the others still have. - -## Code conventions - -- **Encode:** `BakaShrot_Packet_Encode(*Struct, *OutSize.Integer)` sets - the base fields itself, and returns a new buffer (the caller frees it with - `FreeMemory`) or 0. -- **Decode:** `BakaShrot_Packet_Decode(*MsgPackData)` returns a new - struct (the caller frees it with `FreeStructure`) or 0. It reads a view - made with `MsgPackWrapMsgBuffer()`, which the caller frees with - `MsgPackFree(*View, #False)`. -- **Linear code:** each field is written or read top to bottom: check its - type, read it, check the error, check its range. No loops, except for - lists such as SyncState's. -- **Which decoder to use:** `BakaShrot_GetPacketType()` reads a received - packet's type, so a handler can pick the right `_Decode`. - -## Adding a packet - -1. Add its id to `BakaShrot_PacketTypes` in `Commons/Networking/Packets.pbi`. - Never reuse an id. -2. Add `Commons/Networking/Packets/Packet.pbi`, with its structure - (`Extends BakaShrot_PacketBase`), `_Encode` and `_Decode`, following an - existing one. -3. Include it from `Commons/Networking/Connections.pbi`, and add it to the - flow comment at the top of that file. -4. **Server side:** handle it in `BakaShrot_NetClient_HandleRequest()` - (`Server/Networking/Networking.pbi`), checking the permission or role - first. -5. **Client side:** add a `String()` procedure to the DLL with its - `A`/`W` exports if it takes strings, a prototype in - `BakaShrot_Client_Prototypes.pbi`, and a tool if useful. -6. Update this document's packet table and flows. diff --git a/Design/Release.md b/Design/Release.md deleted file mode 100644 index 84b3512..0000000 --- a/Design/Release.md +++ /dev/null @@ -1,244 +0,0 @@ -# Releases - smoke test, 1.0.0, CI/CD - -How releases are built and checked, what's missing before a 1.0.0, and what -to keep in mind when the builds move to CI/CD. Related docs: - -- `Notes.md`: where things stand, the open items. -- `Design/StorageConcurrency.md`: WAL, `synchronous`, the writer. -- `Design/Cryptography.md`: what the handshake and the encryption protect, - and what they don't. - -## Today - -`Release.ps1` builds with PureBasic 6.40's C backend (`/OPTIMIZER`) into -`Release\\` and zips it. `` is `-Version`, or -`-`, with `-dirty` if the tree has uncommitted changes (a -warning, not an error). - -Its smoke test, from the release folder, on one server with a throwaway -database: - -- generates keys with `BakaShrotGenerateKeyPairs.exe`, writes a server and a client config; -- pushes two messages, reads the latest back by name, reads both with - `BakaShrotGetMessages.exe`, resolves a name, queries them through the `messages` - view with `is_json = 1`; -- if `python` is on the PATH, reads them and pushes one with - `python\bakashrot.py`, then installs the wheel (`python\bakashrot-*.whl`, - built by `Interactors/Python/make_wheel.py`) with pip into a folder and - reads and pushes with it, from elsewhere and with no DLL path; -- pushes a 3 MB attachment with `BakaShrotPushMessage.exe -a` and reads it back - identical with `BakaShrotGetAttachment.exe`; -- then force-kills the server and deletes everything. - -The end-to-end tests in `Tests/` cover much more (names, replication, big -messages, GetMessages, the Python client, retention, attachments and their -edge cases), but against `Build\` (PB 5.73) and `BenchServer.exe`, not the -release. The list is in `CLAUDE.md`. - -## Fixed: the release needed the Visual C++ runtime - -**Fixed (2026-11-08):** `Libs/redist/x64/vcruntime140.dll` (from Visual -Studio's `VC\Redist` folder, see `Libs/redist/README.md`) is copied next to -the exes by `Release.ps1`, which refuses to build without it, and -`VERSION.txt` gives its version and "Windows 10 or later, 64-bit". Next to -the exe, it's found before an installed one (it isn't a KnownDLL). Still to -check once on a clean Windows (item 1 below). - -What it was: - -`libsodium.dll` (the official MSVC build) imports `vcruntime140.dll` and the -`api-ms-win-crt-*` DLLs: the **Visual C++ runtime**. The release didn't -ship it and `VERSION.txt` didn't say so: it worked on the build machine only -because the runtime is installed there, on a clean Windows -`BakaShrot_Server.exe`, `BakaShrot_Client.dll` and every tool would fail to -load. Our own exes and `sqlite3.dll` don't need it. The `api-ms-win-crt-*` -ones are the Universal CRT, part of Windows 10 and later. - -Checked with: `grep -a -o -i -E "(vcruntime[0-9_]*|msvcp[0-9_]*|api-ms-win-crt-[a-z0-9-]+)\.dll"` -on each binary of the release folder. - -## The 1.0.0 smoke test - -What `Release.ps1`'s test should also do, by importance. Most of it exists -in `Tests/` already, to be pointed at the release instead. - -1. **Run from the extracted zip**, in a fresh folder, not from the release - folder: proves the zip has everything. Once on a **clean Windows** - (Windows Sandbox is enough), which is where the runtime above shows up. -2. **Replication**: two servers from the release, same names with - different ids. Push on A, read it on B by name, same data, same message - id; and the other way around. -3. **Restart, picking up where it was** on its last run: - - kill a server (not a clean stop), start it again on the same database; - - the messages are still there, and the next push to a topic/node gets - the next id, not 1 again or one already used; - - with two servers: push on B while A is down, start A, A catches up on - what it missed, and B gets what was pushed to A before it went down if - B hadn't had it yet. - - That's how it's meant to work already, since nothing it needs lives - only in memory: the next message ids are read from the database the - first time a pair is pushed to (`Writer.pbi`), `node_heads` is kept by a - trigger in the same transaction as the messages, and every check-in - with a peer starts from both sync states, read from the databases. A - killed process loses nothing committed, whatever `Synchronous` says - (with `NORMAL`, a power loss or an OS crash can lose the last second). **Tested** by - `Tests/Restart-Test.ps1` (2026-11-09): kills with traffic in flight, - once in the middle of a catch-up, both directions, all hold. With - `BenchServer.exe` (the same server code plus a stop file), not the - release's exe itself. -4. **A clean shutdown**: the release server only stops from its console - (`quit`), so the test force-kills it, and the clean path never runs. - Needs a way to stop it without a console: a stop file like - `BenchServer.exe`'s, or a local admin connection (`Notes.md`, console - commands can't be scripted). Then check it stops within a few seconds, - with its last messages committed. On Linux, SIGTERM does it (2026-11-10, - checked through `docker stop`). -5. **Refusals**: - - an unknown public key, and a known one with the wrong private key: - not authenticated; - - a client given the wrong `ServerPublicKey`: can't connect (tested in - `Tests/wire_check.py`, not against the release); - - a frame over 4 KB before authenticating: cut right away; - - a client reading a topic outside its `ReadTopics`, pushing outside its - `PushTopics`, querying without `AllowQuery`: refused, and still - connected. -6. **`config.example.ini` loads**: fill in keys, start the server from it. - It's documentation, it drifts otherwise. -7. **The server's log is captured and checked**: no "Failed", "invalid", - "unexpected", "too much data" from the clients that are meant to work. - Today its output goes to a hidden console nobody reads. -8. **The data rules**: - - a non-JSON push is stored as is, with `is_json = 0`; - - a 1 MB message reads back whole, on both servers; - - a JSON query over non-JSON rows without `is_json = 1` is refused with - SQLite's error, not answered with no rows (fixed, see below). -9. **Every shipped tool runs once**: `BakaShrotList`, `BakaShrotGetMessages --follow` - (picks up a new push, exits 1 once the server is gone) aren't yet. -10. **Version hygiene**: - - `-Version 1.0.0` refuses a dirty tree instead of appending `-dirty`; - - the release commit is tagged (`v1.0.0`), the version comes from it; - - `VERSION.txt` gives the protocol version (5 now) and the runtime needed; - - the Python client is checked on the oldest version it claims (3.8), - not only on the latest (3.14 here). - -Order: 1-3 first (the runtime is fixed), they're what a real deployment hits -on day one. Then 5-8, cheap since `Tests/` has most of it. 4 with the -console item. - -## Fixed: a JSON query over non-JSON rows answered nothing, silently - -Item 8, it came up with every change about non-JSON messages. Fixed on -2026-11-08 (Windows). - -**What happened.** Since pushes aren't checked to be JSON anymore, the -`data` table holds both, flagged in `is_json`. SQLite's JSON functions -(`->>`, `json_extract()`, ...) raise an error on a row that isn't JSON -("malformed JSON"), and that ends the query: SQLite doing what it should. -But `RunReadOnlyQuery()` reads the rows with PureBasic's `NextDatabaseRow()`, -which returns `#False` both at the end of the rows and on an error, and -`DatabaseError()` stays empty after it. So the query counted as a success: -`{"rows": []}` for an aggregate (`SELECT COUNT(*) ... WHERE message_data ->> -'$.level' = 'warn'` gave no row at all), or only the rows read before the -first non-JSON one. A wrong answer that looked like a right one. - -**The fix** (`RunReadOnlyQuery()`, `Server/Storage/Storage.pbi`): once the -rows end, SQLite itself is asked, with `sqlite3_errcode()` on the -connection's handle (`DatabaseID()`), before `FinishDatabaseQuery()`. -`SQLITE_DONE` (or `SQLITE_ROW`/`SQLITE_OK`) means they really ended, -anything else is an error: the query is refused with `sqlite3_errmsg16()`'s -message, and a hint when it's about JSON: - - Query failed: malformed JSON (a row isn't JSON: add is_json = 1 to the WHERE) - -Why this one: -- **Safe:** nothing else changes. The rows are still read by PureBasic, the - query isn't touched, only what happens once they end. A false alarm - would refuse a good query, visibly; it can't hide a bad one anymore. -- **Small:** two functions of the same `sqlite3.dll` PureBasic loaded, like - `Writer.pbi` does, loaded once under a mutex. If they can't be found, - every query is refused rather than unchecked. -- **General:** any error that cut the rows short is caught the same way (a - write stopped by `query_only` in `DELETE ... RETURNING` too), not only - JSON. It replaces the `DatabaseError()` check, which may be shared - between threads anyway. - -Not done: having the server add `is_json = 1` to queries itself. It would -mean rewriting arbitrary SQL (subqueries, CTEs, joins), and a query that -wants the non-JSON rows too would get the wrong answer the other way. - -**Queries still need the clause** (or `CASE WHEN is_json THEN ... END`) to -run JSON functions over mixed rows: they're refused instead of wrong now. -`CASE WHEN` is the guaranteed form: with `AND is_json = 1`, SQLite doesn't -promise to test that term first. It does today for these queries, and if a -plan ever didn't, the query would be refused now, not answered wrong. - -**Not on Linux:** PureBasic's own SQLite is linked in there, not reachable -this way, so it keeps the `DatabaseError()` check that misses it. To do if -it's ever built there: `ImportC` the two functions, or read the rows with -SQLite's API like the writer. - -**Tested:** `Tests/BigMessages-Test.ps1`: an aggregate and a row-by-row -SELECT over mixed rows are refused with "malformed JSON"; non-JSON rows -read without JSON functions, `CASE WHEN is_json`, a query with really no -rows and a plain SQL error behave as before. - -## Before calling it 1.0 - -Not smoke-test items, but what the "1.0" label would promise. From -`Notes.md`'s open items: - -- ~~Clients and peers can't verify the server's identity.~~ Fixed - (protocol 3, `Design/Cryptography.md`). -- ~~No encryption, no per-packet authentication after the handshake.~~ - Fixed (protocol 3). -- Messages aren't signed by the node that first wrote them: a peer is - trusted with what it replicates (`Design/ReplicationIssues.md` #3). -- ~~`synchronous = NORMAL`: the last commits can be lost on a power loss.~~ - Decided: `[BakaShrot.Server] Synchronous`, `FULL` by default - (`Design/StorageConcurrency.md`). - -Either they're fixed, or they're documented limits of 1.0 (or it's a 0.9). - -## For CI/CD - -Notes for when the builds move to a pipeline. - -- **Toolchain:** - - PureBasic isn't freely downloadable: a self-hosted Windows runner with - a licensed install, or a private image. Compiler paths are parameters - (`Build.ps1 -Compiler`, `Release.ps1 -Compiler`), default to - `C:\Program Files\PureBasic_573\...` and `..._640\...`. - - Two compilers are in use: 5.73 for `Build\` and the tests, 6.40's C - backend for releases. Decide whether CI tests the release build (it - should, it's what ships), or both. - - Check out with submodules (`Includes/PB-MessagePack`). - - `Libs/` holds the libsodium and SQLite zips: pin them and check their - hashes in the pipeline. -- **Scripts that need changes first:** - - `Build.ps1` ends by running the server, which waits on its console: - needs a `-NoRun` switch. It also writes private keys into `Build\`, - which must never be published as an artifact. - - The tests use fixed ports (12399 for the release, 12401-12416 for - `Tests/`): parallel jobs on one runner collide, make them parameters - or pick free ones. - - One entry point that runs every test (`Tests/*.ps1`, the handshake - and cipher tests) and fails if any fails. Today each is run by hand. - - The release server needs a console, or it stops right away (no - console input). The smoke test gives it a hidden window: check that - works on the runner (a service account may not get a console), or do - item 4 first. -- **Environment:** - - Exes run from temp folders are blocked by the antivirus here, the - tests run them from `Build\`. A runner may differ either way. - - A clean-machine job, without the Visual C++ runtime, to catch missing - DLLs (see above). - - Python: 64-bit, the oldest claimed version (3.8) and the latest. -- **Versions and artifacts:** - - Releases from tags (`v1.0.0` -> `-Version 1.0.0`), refusing a dirty tree. - - Artifacts: the release zip, and a source zip. Not `Build\`. -- **Benchmarks** (`Tests/Bench/`): too noisy and long for every build. A - nightly or on-demand job, compared to a stored baseline with - `Compare-Runs.ps1`, failing only on a big drop. -- **Linux:** `Libsodium.pbi` and the writer have Linux paths, never built - or tested. A later job, once wanted. diff --git a/Design/ReplicationIssues.md b/Design/ReplicationIssues.md deleted file mode 100644 index 38c6a51..0000000 --- a/Design/ReplicationIssues.md +++ /dev/null @@ -1,174 +0,0 @@ -# Replication - known issues - -How it works now: see the top of `Server/Networking/Peers.pbi`. In short, every -`PeerSyncInterval` seconds a server asks each linked peer for its sync state -(the highest message id per topic/node id), and sends it the messages it's -behind on, with their original ids. Each peer does the same over its own link. - -Issues below are roughly ordered by how much they matter. - -## 1. Drift: the same message id with different content (ruled out by config) - -**The rule: a node pushes to one server.** Each client node has its -`[BakaShrot.Client.]` section (its `Node`) on one server only, the -one it pushes to; the other servers get its messages by replication. Then -every topic/node pair has a single writer and this can't happen. Reading -from any server is fine, only pushing matters. Breaking the rule isn't -detected: it's the config's to keep. - -**When it would happen:** the same topic/node id written to on two -servers, for example a client node registered on both, pushing to each -while they can't reach each other. - -**What happens:** both servers are at `1:2#1`, the link drops, then: - -| | Server A | Server B | -|---|---|---| -| Before | 1 | 1 | -| Client pushes to both | 1, 2a, 3a | 1, 2b | -| Once relinked | A is ahead, sends `#3a` | B isn't ahead, sends nothing | -| Result | 1, 2a, 3a | 1, 2b, 3a | - -- Only the max id is compared, so `#2a` vs `#2b` is never noticed. -- If both had sent the same id, `INSERT OR IGNORE` would keep the local one - and silently drop the other. -- The servers end up partially resynced, with a mixed history for that pair. - -**Possible fix, maybe someday:** authoritative servers. Each topic/node id -gets one server that's allowed to assign its message ids, and the others only -replicate it. Pushes for a pair not owned locally are refused, or forwarded. -A cheaper half-measure: detect drift by also comparing a hash of each -message (or of a range of them), and at least log it. - -## 2. ~~The peer isn't verified~~ (fixed 2026-11-08, protocol 3) - -It was: the handshake only proved the connecting side, the `PublicKey` in a -`[BakaShrot.Peer.]` section was never checked, so whatever answered on -the peer's address got this server's messages pushed to it. - -Now a link's Hello is sealed for the peer section's `PublicKey`, and the -peer must sign the handshake with the matching private key, or the link -fails; the link is encrypted (`Design/Cryptography.md`). A missing or -invalid `PublicKey` stops the server at start. The section's `Topic` and -`Node` are still only checked when the peer links to here. - -## 3. Peers are trusted completely - -A connection that authenticated with a peer's identity and key can replicate -messages for any topic/node id the receiver replicates, with any content. -Messages carry no proof of who first wrote them, so a compromised or buggy -peer can inject or overwrite history for nodes it doesn't own. (Overwrite -only in the sense of issue 1: it can't replace an id that's already stored.) - -**Fix:** sign each message with its originating node's key when it's first -stored, keep the signature with it, and verify it on replication. That needs -every server to know the public key of every node it replicates. - -## 4. Database concurrency (fixed) - -**Fixed 2026-11-06:** every link thread and client thread now has its own -database connection, see `Design/StorageConcurrency.md`. Kept below for the -record. - -The link threads used to read the database with the same unlocked handle as -the client threads. - -**Seen happening** (2026-11-06, benchmark with `PeerBatchSize = 1`): -1. Server 1's link thread was reading the messages to send. -2. At the same time, server 1's thread for server 2's incoming link was - reading the sync state for server 2's check-in. -3. Both went through the same handle, so a read came back empty while - messages were still left. Server 1 logged - `Sent 1424 messages ... it had up to #0` for a backlog of 5000, and the - check-in ended there. - -The next check-in picked up where it stopped, so nothing was lost here. But -the same collision during a write could have stored wrong data. - -## 5. Gaps aren't detected - -Only `MAX(message_id)` is compared. If a server has `1, 2, 5` for a pair (say -`3` and `4` were refused midway through a check-in), it reports `5` and never -gets `3` and `4`. Messages are sent in order and the sending stops at the -first refusal, so this needs something unusual, but nothing repairs it. - -**Fix:** send a count with the max (`COUNT(*) = MAX` means no gaps), and fall -back to comparing id ranges when they differ. - -## 6. Speed: batched since, the per-batch overhead remains - -**Benchmarks** (2026-11-06, both servers on localhost, PureBasic 5.73 x64, -SQLite 3.54.1). The same 5000 messages of ~28 bytes and 1000 of ~4 KB, sent -from scratch: - -| Version | 5000 small | 1000 x 4 KB | -|---|---|---| -| One message per packet (before batching) | 63.6 s, ~79 msg/s | 12.2 s, ~82 msg/s | -| `PeerBatchSize = 1` | ~69-87 msg/s | 12.0 s, ~83 msg/s | -| `PeerBatchSize = 100` (default) | 0.67 s, ~7500 msg/s | 0.94 s, ~1070 msg/s, ~4.3 MB/s | -| `PeerBatchSize = 1000` | 0.11 s, ~45000 msg/s | 1.48 s, ~680 msg/s | - -**Where the per-batch time goes,** measured before batching: - -- **~3.8 ms is SQLite**, one transaction synced to disk. The same inserts - inside one transaction take 0.014 ms each (5000 in 71 ms). Hence one - transaction per batch. -- **The rest is polling.** Both ends wait for packets in `Delay(5)` loops - (5.5 ms each on Windows, `Delay(1)` is 1.6 ms), and each batch waits for - its acknowledgement before the next one, so it pays a few of those per - round trip. - -**Big messages** don't gain from batch sizes over ~16: only that many 4 KB -messages fit in a ~64 KB batch (`#BakaShrot_ReplicateBatchBytes`). Since -2026-11-08 a batch stops reading rows once it has that much, so a big -`PeerBatchSize` no longer reads rows it then can't send. - -**Further fixes, if needed:** - -1. Keep the rows that didn't fit for the next batch instead of reading them - again. -2. ~~Wake the waiting thread when data arrives instead of polling with - `Delay(5)`.~~ Done 2026-11-07: client threads sleep on an event the - listener sets (`Commons/Threading/Signal.pbi`), the listener and the - outbound side sleep in `select()` (`Commons/Networking/SocketWait.pbi`). -3. Send the next batch before the previous one is acknowledged (a window). -4. ~~WAL mode~~ Done 2026-11-07, see `Design/StorageConcurrency.md`. - -**Since then** (2026-11-07, `Tests/Bench/Bench-Replication.ps1`, 4 servers in -a Y): the hub relays up to ~5700 msg/s of pushes to its leaves without -falling behind, sending at ~38000 msg/s while a catch-up runs. The lag is -now just the check-in wait, 4-6 s of pushes at every load (two check-ins for -leaf to leaf). A shorter `PeerSyncInterval` is what would lower it. - -~~**A message that's too big for a batch isn't replicated.**~~ Fixed -2026-11-08: pushes are capped at `#BakaShrot_MaxMessageSize`, 4 KB under the -16 MB packet limit, so one always fits in a batch of its own. - -## 7. Sync state size limit - -The whole sync state must fit in one packet: 16 MB since 2026-11-08 (was -64 KB, roughly 4000 topic/node pairs), so the counts are what limits it now, -65536 topics, nodes and pairs (`SyncStatePacket.pbi`). The replicated topics are also sent as a list, and -`ReplicatingTopicIds = 0-65535` expands to 65536 entries, which doesn't fit. - -**Fix:** send ranges instead of expanded lists, and page the pairs (for -example per topic). - -## 8. Two links per pair of servers - -With two servers listing each other as peers, there are two connections, and -each one is only used by its opener to push. That's what makes both -directions work, but it doubles the connections and the check-ins. Fine for -now. If it ever matters, one link could carry both directions. - -## 9. Messages for topics a server doesn't replicate - -The receiver lists the topics it replicates, and the sender only sends -those, so they're never sent. But a batch that arrives for another topic -anyway is refused, and that stops the pair's catch-up for that check-in. It only happens if the two servers disagree about the list -mid-check-in, for example after a config change. - -## 10. ~~Replicated messages aren't validated~~ - -Moot since 2026-11-08: pushed messages aren't checked to be JSON either, -both are stored as is and flagged by `is_json`. diff --git a/Design/StorageConcurrency.md b/Design/StorageConcurrency.md deleted file mode 100644 index 176cefa..0000000 --- a/Design/StorageConcurrency.md +++ /dev/null @@ -1,179 +0,0 @@ -# Storage concurrency - -Status (2026-11-07): **one connection per thread, WAL mode, a write mutex, -group commit, and a single writer connection with prepared statements are -done.** Full benchmark history: `Tests/Bench/Results-2026-11-07.md`. Ideas -not done yet: `Design/Suggestions.md`. - -## The writer (2026-11-07, `Server/Storage/Writer.pbi`) - -- **Every write goes through one connection,** opened by - `OpenStorageWriter()` when the workers start and closed by - `CloseStorageWriter()` once they're stopped (`Server/Root.pbi`). It's the - one exception to the rule below: shared, but only ever used while holding - the write mutex, so never by two threads at once. -- **Prepared statements, kept open,** through SQLite's own API - (`sqlite3_prepare16_v2`, `sqlite3_bind_*`, `sqlite3_step`), from the - same `sqlite3.dll` PureBasic loads: `DatabaseID()` is its `sqlite3` - handle. PureBasic prepares a statement again on every call. Windows only, - elsewhere the writer falls back to PureBasic's functions. -- **The next id of every topic/node id in memory,** instead of a - `MAX(message_id) + 1` in every insert: read from the database the first - time, raised by replicated messages, forgotten on any rollback. Only right - while this writer is the only one writing. -- **Checkpoints in a background thread,** every second, in PASSIVE rounds - that don't block anything, then a short one under the write mutex once - little is left, so the WAL can start over. The writer still checkpoints by - itself past 10,000 WAL frames, as a backstop when the thread can't keep up - (flat out). Without that backstop the WAL reached 700 MB and Windows - throttled the writes, up to 5 s for a push. -- **`node_heads`,** the highest message id of every topic/node id, kept by a - trigger on `data` (so even `BenchSeed` keeps it right). The sync state is - read from it: 0.5 ms instead of 167 ms at 2.4M rows, on every check-in. - Schema: `Server/Storage/db_schema_v3.dbml` (now `db_schema_v4.dbml`)`. -- **Measured:** ~25,700 -> ~34,300 msg/s for 4 servers, ~38,400 built with - PureBasic 6.40's C backend. p99 at 10 nodes x 50 msg/s: 13.6 -> 0.8 ms. - -## WAL and the write mutex (2026-11-07) - -- **WAL mode,** set by `SetupStorageDatabase()` (stored in the file), with - the config's `synchronous` on every connection (see below). Readers no - longer block the writer: a 0.5 s raw query used to stall pushes for - seconds and once made one fail with "database is locked", now pushes run - next to it at full speed. -- **`synchronous` is `[BakaShrot.Server] Synchronous`** since 2026-11-09, - `FULL` by default (it was `NORMAL`, fixed). The root sets - `BakaShrot_Storage_Synchronous` (`Storage.pbi`) before it opens any - connection. `OFF` is refused (a power loss could corrupt the file), - `EXTRA` too (the same as `FULL` in WAL mode, it only adds a directory - sync for the other journal modes). - - `FULL`: every commit flushes the WAL. An acknowledged push survives a - power loss or an OS crash. The flush is per transaction, so a group - commit's pushes share it. - - `NORMAL`: the WAL is only flushed at checkpoints (about every second, - `Writer.pbi`). The file can't get corrupted, but the last second or so - of commits before a power loss or an OS crash can be lost. Those - messages were acknowledged and maybe already replicated, so their ids - could be handed out again: drift (`ReplicationIssues.md` #1). - -### Measured (2026-11-09) - -`Bench-Replication.ps1 -Ramp "1x0,10x0,10x20" -Parts Ramp -Synchronous ...`, -4 servers in a Y, totals of the 4, one run each (±5-10%). On a VM whose -virtual disk flushes in 0.60 ms (p99 0.78 ms). - -| | OFF | NORMAL | FULL | EXTRA | -|---|---|---|---|---| -| 1 pusher per server, flat out: msg/s | 28,785 | 22,595 | 5,100 | 5,026 | -| ... push p50 / p99 | 0.1 / 0.8 ms | 0.1 / 0.8 ms | 0.7 / 5.3 ms | 0.7 / 3.3 ms | -| 10 pushers per server, flat out: msg/s | 42,854 | 33,870 | 17,207 | 17,763 | -| ... push p50 / p99 / max | 0.6 / 4.8 / 95 ms | 0.5 / 3.3 / 1,113 ms | 1.6 / 9.3 / 123 ms | 1.6 / 8.7 / 129 ms | -| 800 msg/s steady: push p50 / p99 | 0.2 / 0.5 ms | 0.2 / 0.9 ms | 0.9 / 5.0 ms | 0.8 / 4.6 ms | -| Lost on a power loss / OS crash | the file may be corrupted | ~1 s of acknowledged pushes | nothing acknowledged | same as FULL | - -No failed pushes, replication kept up in every case. `FULL`'s cost is the -disk's flush time: one client pushing one message at a time gets about -1 / (flush + 0.15 ms) pushes/s, ~1,300/s here; many clients share flushes -through the group commit, so the total drops much less (half here). On a -server SSD with power-loss protection a flush is far under 0.1 ms (close -to `NORMAL`), on a consumer SSD 1-5 ms, on a hard disk ~10 ms (~100/s for -one sequential client): time one on the target machine to know. -- **`BakaShrot_Storage_WriteMutex`** around every write. A connection that - finds the database locked sleeps in SQLite's busy handler (1, 2, 5, 10... - ms) and retries; with 10+ threads pushing, that's where the time went, and - 10 nodes per server pushed less than 5. Queued on the mutex, the next one - writes as soon as the lock is free. The busy timeout still covers other - processes. -- **Measured** with `Tests/Bench/Bench-Replication.ps1` (4 servers in a Y, - ~200-byte messages, i5-13500, all on localhost), along with the wake-ups - instead of `Delay()` polling (`ReplicationIssues.md` #6): - - | | Before | After | - |---|---|---| - | Cluster push ceiling, 5 / 10 nodes per server | ~955 / ~900 msg/s | ~5770 / ~5730 msg/s | - | Push latency p50 / p99, 10 nodes x 50 msg/s | 18 / 490 ms | 0.4 / 5 ms | - | Indexed query (latest message) | 6-12 ms | ~0.5 ms | - | Pushes while a 0.5 s query loops | 323 of 400 msg/s, max 5.1 s, 1 failure | 396 of 400, max 17 ms | - - That ceiling turned out not to be the database, but the `PrintN()` logging - every push (~0.4 ms each, serialized): see below. - -## Group commit (2026-11-07) - -- **`InsertNextMessage()`** queues the push (`BakaShrot_Storage_Queue`), - then takes the write mutex. Whoever holds it writes every queued push in - one transaction (up to `#BakaShrot_Storage_MaxGroupSize`), so the pushes - that were waiting find theirs done. No extra thread: the busier it gets, - the bigger the groups. Each push still returns once committed. -- **`[Storage]` log line** every 10 s while pushes come in: pushes/s, - pushes per transaction, ms per push, and how busy the writes are. -- **No more log line per push, read or query** (`#BakaShrot_Net_LogRequests` - in `Networking.pbi`): that `PrintN()` was what capped a server at ~2,400 - pushes/s. -- **Measured:** a single server ~2,400 -> ~12,000 pushes/s, the cluster of 4 - ~5,800 -> ~25,700 msg/s, 2.5-9 pushes per transaction when saturated. - The writes are now the limit again (70-90 % busy at 0.07-0.11 ms per push). -- **Open:** p99 at moderate load went up (0.7 -> 8-18 ms). Suspect: a WAL - checkpoint running while holding the write mutex. - -## The rule - -**Never share a database handle between threads.** The `SetDatabase*()` -parameters and the query results belong to a handle, so two threads using one -overwrite each other's. That used to happen: a peer link once read an empty -result while 3500 messages were left to send, see -`Design/ReplicationIssues.md`, issue 4. - -Every thread that touches the database opens its own connection with -`OpenStorageDatabase()` and closes it when it ends: - -| Who | Opens | Closes | Where | -|---|---|---|---| -| A client thread | once its client is authenticated | when the thread ends | `BakaShrot_NetClient_Thread()`, `Server/Networking/Networking.pbi` | -| A peer link thread | when the thread starts | when the thread ends | `BakaShrot_PeerLink_Thread()`, `Server/Networking/Peers.pbi` | -| A raw query | for the query, read-only | right after | `RunReadOnlyQuery()`, `Server/Storage/Storage.pbi` | -| The root | at start, and on restart | on restart and at the end | `Server/Root.pbi` | - -The root's connection is only used for setup, and while the workers are -stopped (vacuum, restart). See `Server/Root.pbi`. - -## What makes several connections work - -- **Busy timeout.** Each connection sets - `PRAGMA busy_timeout = #BakaShrot_Storage_BusyTimeout` (5000 ms), in - `OpenStorageDatabase()`. SQLite allows one writer at a time across - connections. Without it, a write fails at once with "database is locked" - while another connection writes. With it, the write waits its turn. -- **Atomic next id.** `InsertNextMessage()` is a single statement: - ```sql - INSERT INTO data (topic_id, node_id, message_id, message_data) - SELECT ?1, ?2, COALESCE(MAX(message_id), 0) + 1, ?3 - FROM data WHERE topic_id = ?1 AND node_id = ?2 - RETURNING message_id - ``` - Nothing can run between reading `MAX` and inserting, even from another - connection. The UNIQUE `(topic_id, node_id, message_id)` constraint stays - as a safety net. -- **`BEGIN IMMEDIATE` for replicated batches** (`InsertReplicatedMessages()`). - It takes the write lock up front, waiting for it like any write, instead - of a deferred transaction that could fail midway when upgrading to a write - lock. - -**Tested:** 8 connections pushing 100 messages each to the same topic/node -id at once, while two servers replicated. 800 pushes in 6.2 s, no failures, -ids exactly 1-800 on both servers. - -## Left for later - -- **What happens when the busy timeout runs out.** The statement fails, so - the push or batch is refused and retried at the next check-in for - replication. Fine at current loads; decide later whether pushes should - retry. -- ~~**Whether PureBasic's `DatabaseError()` is per thread**~~: it is, in - thread-safe mode (`/THREAD`), checked 2026-11-09 with 5.73 and 6.40: two - threads failing on their own connections 20,000 times each never saw the - other's message. `sqlite3_errmsg16()` on the connection gives the same - text. (`RunReadOnlyQuery()` still asks SQLite on Windows, for the errors - `DatabaseError()` doesn't report at all, see `Design/Release.md`.) -- **A single storage thread with a job queue,** only if writes ever become - the bottleneck. SQLite only has one writer anyway. diff --git a/Design/Suggestions.md b/Design/Suggestions.md deleted file mode 100644 index fc83c23..0000000 --- a/Design/Suggestions.md +++ /dev/null @@ -1,123 +0,0 @@ -# Suggestions, not done yet - -Improvements that came out of the 2026-11-07 benchmarks -(`Tests/Bench/Results-2026-11-07.md`), kept aside on purpose. The first two -are bigger changes, worth it when the use case needs them, the rest are -smaller. - -## 1. Several pushes in flight per connection - -**Today:** a client sends a `PushMessage`, waits for its `MessagePushed`, -then sends the next. One node can push at most once per round trip: - -| Round trip | Most pushes/s per node | -|---|---| -| localhost, now | ~2,000-3,000 | -| LAN, 0.5 ms | ~2,000 | -| WAN, 50 ms | ~20 | - -The server side doesn't care much, it groups pushes from every connection -anyway. This is about one node, or few nodes, far from their server. - -**What it entails:** - -- **Protocol.** Let a client send up to W pushes before the first answer. - TCP and the one thread per connection already keep them in order, and the - answers come back in the same order, so the Nth answer belongs to the Nth - push. Still, add a `RequestId` (client-chosen, echoed in `MessagePushed` - and `RequestRefused`) so a client can match answers without counting, and - so a desync is detectable. Old clients send no `RequestId` and keep - working one at a time. See `Design/Packets.md` for how to add a field. -- **Server inbox.** It holds at most two of the biggest packets - (`BakaShrot_Inbox_MaxSize()`), anything more aborts the connection as - "sent too much data". Since big packets (2026-11-08) that's ~32 MB once - authenticated, plenty for a window of small pushes, but a window of big - ones still needs backpressure: stop reading that client's socket while its inbox is full, - so TCP slows it down. PureBasic's `NetworkServerEvent()` keeps reporting - data that isn't read, so backpressure means the listener has to skip that - client's events without spinning: easiest is a per-client "full" flag, - with the listener not calling `ReceiveNetworkData()` for it and leaving - it out of its `select()` set until the client thread drains its inbox. -- **Server thread.** Take every complete packet in the inbox, queue all the - pushes in the writer at once (`BakaShrot_Storage_Queue`), then send the - answers. One connection then fills a whole group commit by itself. -- **Client DLL.** Keep `BakaShrot_PushMessage()` as is (synchronous, W=1). - Add an asynchronous variant for those who want it, without callbacks - since the DLL is used from other languages: - `BakaShrot_PushMessageAsync(Json)` returns a local sequence number, - `BakaShrot_GetPushResult(Sequence)` / `BakaShrot_WaitPushes()` collect the - ids or the refusals. The DLL holds at most W unanswered pushes, the next - call waits for room. -- **Semantics.** Each push is still independent: a refused one doesn't stop - the next ones, the caller gets one result per push. Ids are still handed - out in send order per node. -- **Bench.** `BenchClient` gets a window per pusher, to measure W = 1, 4, - 16, ideally with a simulated latency (or the servers on another machine). - -**Effort:** medium. Packets, DLL API, the server's inbox and thread loop. -The inbox backpressure is the delicate part. - -## 2. Replication: windowed batches, several sockets per link, check-ins on demand - -**Today,** per peer link: one connection, a check-in every -`PeerSyncInterval` (5 s) or so, then for each topic/node id the peer is -behind on, one batch of up to `PeerBatchSize` messages at a time, waiting -for its acknowledgement before the next, one pair after the other. The -benchmarks show it keeps up (the hub relays ~25,000+ msg/s), but the lag is -the check-in wait: 4-10 s of pushes, two check-ins from leaf to leaf. - -**What it entails, cheapest first:** - -1. **Check-ins on demand.** The writer signals (`Commons/Threading/Signal.pbi`) - when it committed something, and the link threads check in as soon as - there's something new, at most every `PeerMinSyncInterval` (say 100 - ms), and still every `PeerSyncInterval` when idle. Cheap since the sync - state is now read from `node_heads`. Lowers the lag from seconds to - about the minimum interval plus the relay through the hub. Biggest gain - for the least work. -2. **A window of batches.** Send up to W batches before waiting for the - first acknowledgement, acknowledged in order. On a refusal, stop, and the - next check-in starts again after the last acknowledged one. - - **Needed first: the receiver must refuse a gap.** Today a batch is - stored whatever its first id, with `INSERT OR IGNORE`. With a window, - batch 2 could be stored after batch 1 was refused, leaving a gap that - the max-only sync state never repairs (`ReplicationIssues.md` #5). - Refuse a batch whose first id isn't the pair's head + 1, which - `node_heads` (or the writer's id cache) makes a cheap check. - - The same inbox limit as above: two packets. A peer connection needs a - bigger inbox, or the backpressure. -3. **Several sockets per link.** `PeerConnections = N` in the peer's - section: N connections, N threads on both ends, each one checking in and - catching up its share of the topic/node ids (for example - `(TopicId * 65536 + NodeId) % N`). A pair always goes over the same - socket, which keeps its messages in order. Catch-ups of different pairs - then run in parallel instead of one after the other. On the receiving - side, the batches of the N threads queue on the write mutex: they could - join the pushes' group commit (one transaction for whatever batches and - pushes are waiting) instead of one transaction each. -4. **One connection for both directions** (`ReplicationIssues.md` #8), if - the number of connections ever matters. - -**Effort:** 1 is small, 2 is medium (mostly the gap check and the inbox), 3 -is medium (config, threads, partitioning), 4 is larger (both ends of the -protocol change). - -## 3. Smaller ones - -- ~~**Decide on `synchronous = NORMAL`**~~: done 2026-11-09, a config - option (`Synchronous`), `FULL` by default, measured in - `Design/StorageConcurrency.md`. -- **`Build.ps1`:** the compiler path and `-Compiler` are fixed (2026-11-07), - but the `Libs\` zips for libsodium and SQLite are gone: it only works while - the extracted DLLs are still in `Libs\*d`. -- **Benchmark on two machines:** the servers on one, `BenchClient` on the - other. Flat out, the load generator uses ~85 % of a core on the same - machine, and the servers compete with it for the CPU and the disk. -- **The WAL at full speed:** flat out, each server writes ~25,000 WAL - frames/s, and the checkpoints can't keep it small, so the writer falls - back to checkpointing by itself past `#BakaShrot_Storage_WalBackstopFrames` - (the worst push goes up to ~0.7 s). A bigger page size, or fewer indexes - (is `idx_data_message_id` needed?), would write fewer pages per push. -- **Full-table JSON queries** grow with the data (~0.45 ms per 1,000 rows). - If some JSON field gets queried often, a generated column with an index - on it (like the `msg_type` noted in `db_schema_v4.dbml`) makes it a lookup. diff --git a/Docker/README.md b/Docker/README.md deleted file mode 100644 index eb3eab4..0000000 --- a/Docker/README.md +++ /dev/null @@ -1,52 +0,0 @@ -# BakaShrot - Docker -Docker image for the server, built on the PureBasic images from `git.nibblepoker.lu`. - -> [!NOTE] -> The PureBasic images are licensed, building requires a login to their registry. \ -> The final image only holds the compiled server, libsodium and SQLite. - - -## Running -Fill in [Server/server.ini](Server/server.ini), then, from `Docker/Server/`: -```shell -docker compose up -d --build -``` - -See [Server/docker-compose.yml](Server/docker-compose.yml) and the [Dockerfile](Server/Dockerfile) for more. - - -## Building -From the repository's root: -```shell -git submodule update --init --recursive -docker login git.nibblepoker.lu -docker build --provenance=false -t bakashrot-server -f Docker/Server/Dockerfile . -``` - -`--provenance=false` pushes the image as a plain manifest: with the default attestation it's an index, and GitHub -doesn't see the Dockerfile's `org.opencontainers.image.source` label there, so the package isn't linked to the repository. - - -## Uploading -Tag and push the image to both registries, with the version and as `latest`: - -### Gitea -```shell -docker login git.nibblepoker.lu -docker tag bakashrot-server git.nibblepoker.lu/aziascreations/bakashrot-server:0.0.1 -docker tag bakashrot-server git.nibblepoker.lu/aziascreations/bakashrot-server:latest -docker push git.nibblepoker.lu/aziascreations/bakashrot-server:0.0.1 -docker push git.nibblepoker.lu/aziascreations/bakashrot-server:latest -``` - -### GitHub -Requires a [personal access token](https://github.com/settings/tokens) with the `write:packages` scope as the password. -```shell -docker login ghcr.io -u aziascreations -docker tag bakashrot-server ghcr.io/aziascreations/bakashrot-server:0.0.1 -docker tag bakashrot-server ghcr.io/aziascreations/bakashrot-server:latest -docker push ghcr.io/aziascreations/bakashrot-server:0.0.1 -docker push ghcr.io/aziascreations/bakashrot-server:latest -``` - -The package then has to be linked to the repository, and made public if needed, in its settings on GitHub. diff --git a/Docker/Server/Dockerfile b/Docker/Server/Dockerfile deleted file mode 100644 index 2a73df6..0000000 --- a/Docker/Server/Dockerfile +++ /dev/null @@ -1,81 +0,0 @@ -# BakaShrot server image. -# -# Built from the repository's root, with the PB-MessagePack submodule checked -# out and a login to the registry holding the PureBasic images (they're -# licensed, so not public): -# git submodule update --init --recursive -# docker login git.nibblepoker.lu -# docker build --provenance=false -t bakashrot-server -f Docker/Server/Dockerfile . -# Another compiler image: --build-arg COMPILER_IMAGE=, any Debian 13 -# (trixie) image with PureBasic's compilers on the PATH, gcc and libssl-dev. -# -# Run it with a config and a volume for the database: -# docker run -d --name bakashrot -p 12345:12345 \ -# -v ./server.ini:/etc/bakashrot/server.ini:ro \ -# -v bakashrot-data:/var/lib/bakashrot \ -# bakashrot-server -# In server.ini's [BakaShrot.Server]: Port = 12345, Host empty (every -# interface: 127.0.0.1 can't be reached from outside the container), and -# DatabasePath = /var/lib/bakashrot/server.sqlite (relative paths are from -# that folder too). -# -# Or with docker-compose.yml, next to this file, and its empty server.ini -# to fill in. -# -# `docker stop` stops it cleanly (SIGTERM). Console commands (names, vacuum, -# restart...): start it with -it, then `docker attach bakashrot`, and -# detach with Ctrl+P, Ctrl+Q. - - -# --- Build --------------------------------------------------------------------- - -# PureBasic 6.41 for linux3 (PureBasic's newest Linux build) on -# debian:trixie-slim, the same Debian as the runtime stage below. -ARG COMPILER_IMAGE=git.nibblepoker.lu/packages/purebasic:6.41-linux3-trixie-slim -FROM ${COMPILER_IMAGE} AS build - -RUN apt-get update \ - && apt-get install -y --no-install-recommends libsodium-dev \ - && rm -rf /var/lib/apt/lists/* - -WORKDIR /src -# Everything Server/BakaShrot_Server.pb includes, and nothing else. -COPY Client/BakaShrot_ErrorCodes.pbi Client/ -COPY Commons Commons -COPY Includes Includes -COPY Server Server - -# The release build: C backend, optimized, thread-safe. -RUN mkdir /out && pbcompilerc --thread --optimizer Server/BakaShrot_Server.pb --executable /out/bakashrot-server - - -# --- Runtime ------------------------------------------------------------------- - -FROM debian:trixie-slim - -# The source label links the package to the repository on ghcr.io. GitHub -# reads it from the image itself, not from an index: build with -# --provenance=false, or the attestation hides it (Docker/README.md). -LABEL org.opencontainers.image.source="https://github.com/aziascreations/BakaShrot" \ - org.opencontainers.image.description="BakaShrot server" \ - org.opencontainers.image.licenses="CC0-1.0" - -# libsodium for the cryptography, SQLite 3.38+ for the storage: the server -# loads libsqlite3.so.0 itself (Server/Storage/Storage.pbi). -RUN apt-get update \ - && apt-get install -y --no-install-recommends libsodium23 libsqlite3-0 \ - && rm -rf /var/lib/apt/lists/* - -RUN useradd --system --home-dir /var/lib/bakashrot --shell /usr/sbin/nologin bakashrot \ - && mkdir -p /etc/bakashrot /var/lib/bakashrot \ - && chown bakashrot:bakashrot /var/lib/bakashrot - -COPY --from=build /out/bakashrot-server /usr/local/bin/bakashrot-server - -USER bakashrot -WORKDIR /var/lib/bakashrot -VOLUME /var/lib/bakashrot -EXPOSE 12345 - -ENTRYPOINT ["/usr/local/bin/bakashrot-server"] -CMD ["/etc/bakashrot/server.ini"] diff --git a/Docker/Server/Dockerfile.dockerignore b/Docker/Server/Dockerfile.dockerignore deleted file mode 100644 index d9396e1..0000000 --- a/Docker/Server/Dockerfile.dockerignore +++ /dev/null @@ -1,8 +0,0 @@ -# Only what the server is compiled from: Build/ alone can hold gigabytes of -# test databases, and private keys. -* -!Client/BakaShrot_ErrorCodes.pbi -!Commons -!Includes -!Server -**/.git diff --git a/Docker/Server/docker-compose.yml b/Docker/Server/docker-compose.yml deleted file mode 100644 index 09786d2..0000000 --- a/Docker/Server/docker-compose.yml +++ /dev/null @@ -1,38 +0,0 @@ -# BakaShrot server, example compose file. -# -# Fill in server.ini next to this file first (a private key, topics, a -# client section: it's empty, the server refuses to start as it is), then, -# from this folder, with a login to the registry holding the PureBasic -# images (see the Dockerfile): -# docker compose up -d --build -# docker compose logs bakashrot # its public key, for client.ini -# docker compose down # stops it cleanly (SIGTERM) -# -# Console commands (names, vacuum, restart...): `docker attach bakashrot`, -# detach with Ctrl+P, Ctrl+Q (not Ctrl+C: that stops it). -# -# The database lives in the bakashrot-data volume, kept by `down` -# (`down -v` deletes it). - -services: - bakashrot: - build: - # The repository's root: the build needs Commons/, Includes/, Server/. - context: ../.. - dockerfile: Docker/Server/Dockerfile - image: bakashrot-server - container_name: bakashrot - restart: unless-stopped - ports: - # server.ini's [BakaShrot.Server] Port. - - "12345:12345" - volumes: - - ./server.ini:/etc/bakashrot/server.ini:ro - - bakashrot-data:/var/lib/bakashrot - # Only needed to type console commands with `docker attach bakashrot`. - # The server runs fine without these two lines. - stdin_open: true - tty: true - -volumes: - bakashrot-data: diff --git a/Docker/Server/server.ini b/Docker/Server/server.ini deleted file mode 100644 index a90d72e..0000000 --- a/Docker/Server/server.ini +++ /dev/null @@ -1,60 +0,0 @@ -; ============================================================================ -; BakaShrot server config, for docker-compose.yml: empty, fill it in. -; -; Every option is documented in Server/Config/schema.ini (config.example.ini -; in a release). Keys: BakaShrotGenerateKeyPairs.exe. Never commit a filled -; in copy, it holds the server's private key. -; ============================================================================ - -[BakaShrot] -; This server's private key. Its public key, which clients need as -; ServerPublicKey, is in the log when it starts (docker compose logs). -PrivateKey = - -; The node this server authenticates as when it links to peers. -Node = - - -[BakaShrot.Topics] -; One topic name per line. -; logs - - -[BakaShrot.Retention] -; topic = age (30d, 12h...), or nothing to keep everything forever. -; logs = 30d - - -[BakaShrot.Server] -; Empty: every interface (127.0.0.1 can't be reached from outside the -; container). The port must match docker-compose.yml's. -Host = -Port = 12345 -ReplicatingTopics = -NetThreadPoolSize = 4 -; In the bakashrot-data volume. -DatabasePath = /var/lib/bakashrot/server.sqlite -MaxAttachmentSize = 1G -Synchronous = FULL - - -; One section per peer, see schema.ini. -; [BakaShrot.Peer.other] -; Host = -; Port = -; Node = -; PublicKey = - - -; One section per client allowed to connect. -[BakaShrot.Client.example] -; The client's public key (client.ini's PublicKey). -PublicKeys = -; The node it writes as (client.ini's Node must say the same). -Node = -; DefaultTopic = logs -; PushTopics = logs -; ReadTopics = * -AllowRead = 1 -AllowWrite = 1 -AllowQuery = 0 diff --git a/Examples/README.md b/Examples/README.md deleted file mode 100644 index 9b01642..0000000 --- a/Examples/README.md +++ /dev/null @@ -1,12 +0,0 @@ -# Examples - -Ready-to-run setups, each in its own folder with its configs, scripts to -start it, and a README. Build first (`Build.ps1` at the root): the scripts -take the exes from `Build\`, or from a release folder with `-BinDir`. - -| Example | What it shows | -|---|---| -| [`SingleServer`](SingleServer/README.md) | One server, one client: pushing, reading, attachments, names, SQL, with the tools. | - -Their keys are in the repository, so public: they're only for trying the -examples locally, never reuse them. diff --git a/Examples/SingleServer/README.md b/Examples/SingleServer/README.md deleted file mode 100644 index 744ed66..0000000 --- a/Examples/SingleServer/README.md +++ /dev/null @@ -1,136 +0,0 @@ -# One server, one client - -The smallest BakaShrot setup: one server on `127.0.0.1:12360`, one client -that pushes and reads messages with the tools. - -> **The keys in `server.ini` and `client.ini` are public, they're in the -> repository.** They're only for trying this example on your own machine -> (the server only listens on 127.0.0.1). Never reuse them: make your own -> with `BakaShrotGenerateKeyPairs.exe`. - -## Running it - -Build first, `Build.ps1` at the root, or use a release folder (`-BinDir -Release\` on both scripts). Then, from this folder: - -```powershell -powershell -ExecutionPolicy Bypass -File Start-Server.ps1 -powershell -ExecutionPolicy Bypass -File Run-Client.ps1 -``` - -- `Start-Server.ps1` opens the server in its own window and waits until it - listens. Type `quit` in that window to stop it (`help` lists the other - commands). `-Here` runs it in the current console instead, `-Reset` - deletes its database first, so the ids start from 1 again. -- `Run-Client.ps1` goes through what a client does, printing each command - before its output. The commands can be pasted as they are from this - folder: - -```text -== Push a message to the client's default topic (logs, the server's DefaultTopic for it), as node demo -> ..\..\Build\BakaShrotPushMessage.exe @messages\hello.json client.ini - Pushed as message #1 -... -== Read the latest message of logs:demo (topic:node, by name) -> ..\..\Build\BakaShrotGetLatestMessage.exe logs demo client.ini - Message logs:demo#2 (ids 1:2), pushed 2026-11-08T21:23:53.590Z - Attachment: 159 bytes - {"level":"info","text":"Daily report, attached"} -``` - -The server's database (`example.sqlite`) and what the client saves -(`out\`) stay in this folder, git ignores them. - -## What's in here - -| File | What it is | -|---|---| -| `server.ini` | The server: its key, its names, where it listens, the one client it accepts and what that client may do. Every option is documented in `Server/Config/schema.ini`. | -| `client.ini` | The client: its key pair, the node it writes as (`demo`), and the server's address and public key. Every tool takes it as its last argument. | -| `Start-Server.ps1` | Starts the server with `server.ini`. | -| `Run-Client.ps1` | The client's steps, below. | -| `messages\` | What the client pushes (`hello.json`, `reading.json`, `report.json` with `report.txt` attached) and the SQL it runs (`query.sql`). | - -## How the two configs fit together - -- **Keys:** each side has a key pair. The server lists the client's public - key in `[BakaShrot.Client.demo] PublicKeys`; the client has the server's - in `ServerPublicKey`. Every connection is encrypted, and only reaches the - server holding the matching private key. -- **Names:** messages are filed under a topic and a node. The topics are - listed in `[BakaShrot.Topics]`, the nodes come from the sections that - define them (`server`, `demo`). The server gives each name an id of its - own; clients use the names. -- **Who the client is:** its node, `demo`, in both configs (`Node`). - Every message it pushes is stored under it. That's why the server - checks it: the key proves who's connecting, the server's `Node` for that - key says which node it may write as, so no client can push as another's - node. -- **Where its pushes go:** the server's `DefaultTopic = logs`, unless a - push names another topic in `PushTopics` (`-t sensors`). Only the server - has it: `client.ini` has no topic. -- **What it may do:** read every topic (`ReadTopics = *`, `AllowRead`), - push (`AllowWrite`), run read-only SQL (`AllowQuery`). -- **Retention:** `sensors` messages are kept a day, `logs` ones forever. -- **Durability:** `Synchronous = FULL` (the default): every message the - server acknowledges is flushed to disk first, so it survives a power cut. - `NORMAL` pushes faster but can lose the last second or so of messages - then; see `Server/Config/schema.ini`. - -## What the client does - -`Run-Client.ps1`, step by step: - -1. **Pushes** `hello.json` to `logs`, its default topic: `BakaShrotPushMessage @messages\hello.json`. - JSON goes in a file (`@file`): PowerShell drops the double quotes of an - argument. -2. **Pushes** `reading.json` to `sensors`: `-t sensors`. -3. **Pushes** `report.json` with `report.txt` attached: `-a messages\report.txt`. -4. **Reads the latest** message of `logs:demo`: `BakaShrotGetLatestMessage logs demo`. -5. **Saves the attachment** back to `out\report-copy.txt` and checks it's - the same: `BakaShrotGetAttachment logs demo out\report-copy.txt`. -6. **Reads every** message of `logs:demo`, one per line (id, time, data): - `BakaShrotGetMessages logs demo --time`. -7. **Reads** `sensors:demo`'s latest. -8. **Shows the ids** the server has for the names: `BakaShrotResolveIds topic sensors`, `BakaShrotList`. -9. **Queries** with SQL: `BakaShrotQuery @messages\query.sql`, on the - `messages` view, which has the names. - -To watch messages arrive, leave this running and push from another -terminal: - -```powershell -..\..\Build\BakaShrotGetMessages.exe logs demo --after latest --follow client.ini -``` - -## Looking at the database - -`example.sqlite` is a plain SQLite file, the `messages` view has the -names. To browse one topic in a tool like SQLiteStudio: - -1. Open the `browse` table: one row. Pick a topic in its `topic` cell (a - dropdown of the topics, from its foreign key), and a node in `node` to - narrow it, or leave it NULL for every node. Commit. -2. Open the `browse_messages` view: that topic's messages, newest first, - with their node, id, time (UTC), data and attachment size. - -The server never writes `browse`, so it's safe to change while it runs. -Close the tool when done: an open grid keeps the server from finishing -its checkpoints, and its WAL file grows meanwhile. - -## From Python - -The same `client.ini` works with the Python client -(`Interactors/Python/bakashrot.py`, over the DLL). From the repository's -root: - -```python -import sys -sys.path.insert(0, r"Interactors\Python") -from bakashrot import Client - -with Client.from_ini(r"Examples\SingleServer\client.ini", r"Build\BakaShrot_Client.dll") as client: - print("pushed", client.push({"from": "python"})) - for message in client.get_messages("logs", "demo").messages: - print(message.id, message.json()) -``` diff --git a/Examples/SingleServer/Run-Client.ps1 b/Examples/SingleServer/Run-Client.ps1 deleted file mode 100644 index b8a662c..0000000 --- a/Examples/SingleServer/Run-Client.ps1 +++ /dev/null @@ -1,101 +0,0 @@ -# ============================================================================ -# BakaShrot example: what a client does, with the tools and client.ini. -# -# Start the server first (Start-Server.ps1). Each step prints the command -# it runs, then its output: run from this folder, the commands can be -# pasted as they are. Every run pushes 3 more messages, the ids go on from -# the last run's (Start-Server.ps1 -Reset starts over). -# -# Usage: powershell -ExecutionPolicy Bypass -File Run-Client.ps1 [-BinDir ] -# -BinDir Where the tools are, with BakaShrot_Client.dll next to them: -# Build\ by default (Build.ps1), or a Release\\. -# ============================================================================ - -param( - [string]$BinDir = (Join-Path $PSScriptRoot "..\..\Build") -) - -$ErrorActionPreference = "Stop" - -$Port = 12360 - -function Test-Port($Port) { - $Client = New-Object System.Net.Sockets.TcpClient - try { - $Async = $Client.BeginConnect("127.0.0.1", $Port, $null, $null) - return ($Async.AsyncWaitHandle.WaitOne(200) -and $Client.Connected) - } catch { return $false } - finally { $Client.Close() } -} - -function Write-Step($Text) { - Write-Host "" - Write-Host "== $Text" -ForegroundColor Cyan -} - -# Runs a tool, shows the command and what it printed, stops if it failed. -# client.ini is always the last argument. -function Invoke-Tool($Name, [string[]]$Arguments) { - $Arguments += "client.ini" - $Shown = $Arguments | ForEach-Object { if ($_ -match " ") { "`"$_`"" } else { $_ } } - Write-Host ("> " + (Join-Path $Bin "$Name.exe") + " " + ($Shown -join " ")) -ForegroundColor DarkGray - $Output = & (Join-Path $Bin "$Name.exe") @Arguments 2>&1 - $Code = $LASTEXITCODE - $Output | ForEach-Object { Write-Host " $_" } - if ($Code -ne 0) { throw "$Name failed with code $Code" } - return ($Output -join "`n") -} - -if (-not (Test-Path (Join-Path $BinDir "BakaShrot_Client.dll"))) { - throw "No BakaShrot_Client.dll in ${BinDir}: build it first (Build.ps1), or pass -BinDir" -} -if (-not (Test-Port $Port)) { - throw "Nothing listens on port ${Port}: start the server first (Start-Server.ps1)" -} - -# From this folder, so every path is short: client.ini, messages\... -Push-Location $PSScriptRoot -try { - $Bin = Resolve-Path -Relative $BinDir - New-Item -ItemType Directory -Force "out" | Out-Null - - Write-Step "Push a message to the client's default topic (logs, the server's DefaultTopic for it), as node demo" - # JSON goes in a file (@file): PowerShell drops the double quotes of an argument. - $null = Invoke-Tool "BakaShrotPushMessage" @("@messages\hello.json") - - Write-Step "Push one to another topic it may push to (sensors)" - $null = Invoke-Tool "BakaShrotPushMessage" @("-t", "sensors", "@messages\reading.json") - - Write-Step "Push one with a file attached" - $Pushed = Invoke-Tool "BakaShrotPushMessage" @("-a", "messages\report.txt", "@messages\report.json") - if ($Pushed -notmatch "message #(\d+)") { throw "Unexpected answer: $Pushed" } - $ReportId = $Matches[1] - - Write-Step "Read the latest message of logs:demo (topic:node, by name)" - $null = Invoke-Tool "BakaShrotGetLatestMessage" @("logs", "demo") - - Write-Step "Read the attachment back" - $null = Invoke-Tool "BakaShrotGetAttachment" @("logs", "demo", $ReportId, "out\report-copy.txt") - if ((Get-FileHash "out\report-copy.txt").Hash -ne (Get-FileHash "messages\report.txt").Hash) { throw "The attachment came back different" } - Write-Host " Same bytes as messages\report.txt" - - Write-Step "Read every message of logs:demo, with when they were pushed (UTC)" - $null = Invoke-Tool "BakaShrotGetMessages" @("logs", "demo", "--time") - - Write-Step "Read the sensors one" - $null = Invoke-Tool "BakaShrotGetLatestMessage" @("sensors", "demo") - - Write-Step "What the server calls the names: their ids there" - $null = Invoke-Tool "BakaShrotResolveIds" @("topic", "sensors") - $null = Invoke-Tool "BakaShrotList" @() - - Write-Step "A raw SQL query (needs AllowQuery = 1), from messages\query.sql" - $null = Invoke-Tool "BakaShrotQuery" @("@messages\query.sql") - - Write-Host "" - Write-Host "Done. To follow new messages as they come, from this folder:" -ForegroundColor Green - Write-Host " $(Join-Path $Bin 'BakaShrotGetMessages.exe') logs demo --after latest --follow client.ini" -} -finally { - Pop-Location -} diff --git a/Examples/SingleServer/Start-Server.ps1 b/Examples/SingleServer/Start-Server.ps1 deleted file mode 100644 index 866ebe2..0000000 --- a/Examples/SingleServer/Start-Server.ps1 +++ /dev/null @@ -1,67 +0,0 @@ -# ============================================================================ -# BakaShrot example: starts the server with server.ini. -# -# In a window of its own by default (the server needs a console: it reads -# its commands there, and stops at once without one), then waits until it -# listens. Type "quit" in that window to stop it, "help" for the others. -# -# Usage: powershell -ExecutionPolicy Bypass -File Start-Server.ps1 [-BinDir ] [-Here] [-Reset] -# -BinDir Where BakaShrot_Server.exe is, with libsodium.dll and -# sqlite3.dll: Build\ by default (Build.ps1), or a Release\\. -# -Here Runs it in this console instead, until "quit". -# -Reset Deletes the example's database first: no messages, ids from 1. -# -# Its database, example.sqlite, goes next to this script. -# ============================================================================ - -param( - [string]$BinDir = (Join-Path $PSScriptRoot "..\..\Build"), - [switch]$Here, - [switch]$Reset -) - -$ErrorActionPreference = "Stop" - -$Server = Join-Path $BinDir "BakaShrot_Server.exe" -$Ini = Join-Path $PSScriptRoot "server.ini" -$Port = 12360 - -function Test-Port($Port) { - $Client = New-Object System.Net.Sockets.TcpClient - try { - $Async = $Client.BeginConnect("127.0.0.1", $Port, $null, $null) - return ($Async.AsyncWaitHandle.WaitOne(200) -and $Client.Connected) - } catch { return $false } - finally { $Client.Close() } -} - -if (-not (Test-Path $Server)) { - throw "No ${Server}: build it first (Build.ps1), or pass -BinDir" -} -if (Test-Port $Port) { - throw "Something already listens on port $Port, the example server may already run" -} - -if ($Reset) { - Get-ChildItem $PSScriptRoot -Filter "example.sqlite*" | Remove-Item -Confirm:$false - Write-Host "Deleted the example's database" -} - -if ($Here) { - Push-Location $PSScriptRoot - try { & $Server $Ini } - finally { Pop-Location } - exit $LASTEXITCODE -} - -$Process = Start-Process -FilePath $Server -ArgumentList "`"$Ini`"" -WorkingDirectory $PSScriptRoot -PassThru -$Deadline = (Get-Date).AddSeconds(15) -while (-not (Test-Port $Port)) { - if ($Process.HasExited) { throw "The server stopped with code $($Process.ExitCode), see its log above" } - if ((Get-Date) -gt $Deadline) { throw "The server isn't listening on $Port after 15 s" } - Start-Sleep -Milliseconds 100 -} - -Write-Host "The server runs in its own window (process $($Process.Id)), on 127.0.0.1:$Port." -Write-Host "Try it with: powershell -ExecutionPolicy Bypass -File `"$(Join-Path $PSScriptRoot 'Run-Client.ps1')`"" -Write-Host "Stop it by typing quit in its window." diff --git a/Examples/SingleServer/client.ini b/Examples/SingleServer/client.ini deleted file mode 100644 index 5a32cf6..0000000 --- a/Examples/SingleServer/client.ini +++ /dev/null @@ -1,26 +0,0 @@ -; ============================================================================ -; BakaShrot example: the client's config, read by every tool (their last -; argument), the client DLL and the Python client. -; -; EXAMPLE KEYS, PUBLIC IN THE REPOSITORY: never use them for anything real. -; Make your own with BakaShrotGenerateKeyPairs.exe. -; ============================================================================ - -[BakaShrot] -; This client's key pair. The server lists the public key in -; [BakaShrot.Client.demo] PublicKeys. -PrivateKey = zDA8o6hp7zkIatlumOKFWqV8j3yYON8QFpIkMAEnpJnKv4FbbX4SmshWDRJp9ds5qpEDVYRHSnE7exw2pkQK1w== -PublicKey = yr+BW21+EprIVg0SafXbOaqRA1WER0pxO3scNqZECtc= - -; The node it writes as: the server checks its section for this key says -; Node = demo. Every message it pushes is stored as "demo". -; No topic here: where its pushes go when they don't name one is the -; server's DefaultTopic, which topics it may push to and read its -; PushTopics and ReadTopics. -Node = demo - -; Where the server is, and its public key: the client only talks to the -; server holding the matching private key. -ServerHost = 127.0.0.1 -ServerPort = 12360 -ServerPublicKey = k32QNiTXL9lA7DhdwBQv9jQXouADujciaOWVZuA3JE4= diff --git a/Examples/SingleServer/messages/hello.json b/Examples/SingleServer/messages/hello.json deleted file mode 100644 index 5cf49bd..0000000 --- a/Examples/SingleServer/messages/hello.json +++ /dev/null @@ -1 +0,0 @@ -{"level":"info","text":"Hello from the example client"} \ No newline at end of file diff --git a/Examples/SingleServer/messages/query.sql b/Examples/SingleServer/messages/query.sql deleted file mode 100644 index bdcd7a3..0000000 --- a/Examples/SingleServer/messages/query.sql +++ /dev/null @@ -1 +0,0 @@ -SELECT topic, node, message_id, pushed_utc, message_data ->> '$.text' FROM messages WHERE topic = 'logs' AND is_json = 1 ORDER BY message_id \ No newline at end of file diff --git a/Examples/SingleServer/messages/reading.json b/Examples/SingleServer/messages/reading.json deleted file mode 100644 index 214d764..0000000 --- a/Examples/SingleServer/messages/reading.json +++ /dev/null @@ -1 +0,0 @@ -{"sensor":"kitchen-temperature","celsius":21.5} \ No newline at end of file diff --git a/Examples/SingleServer/messages/report.json b/Examples/SingleServer/messages/report.json deleted file mode 100644 index 0ef839f..0000000 --- a/Examples/SingleServer/messages/report.json +++ /dev/null @@ -1 +0,0 @@ -{"level":"info","text":"Daily report, attached"} \ No newline at end of file diff --git a/Examples/SingleServer/messages/report.txt b/Examples/SingleServer/messages/report.txt deleted file mode 100644 index e36a398..0000000 --- a/Examples/SingleServer/messages/report.txt +++ /dev/null @@ -1,5 +0,0 @@ -Daily report -============ - -Any file can be attached to a message: bytes of any kind, up to the -server's MaxAttachmentSize. The message's JSON says what it is. diff --git a/Examples/SingleServer/server.ini b/Examples/SingleServer/server.ini deleted file mode 100644 index 6aac1ac..0000000 --- a/Examples/SingleServer/server.ini +++ /dev/null @@ -1,67 +0,0 @@ -; ============================================================================ -; BakaShrot example: the server's config (one server, one client). -; -; EXAMPLE KEYS, PUBLIC IN THE REPOSITORY: never use them for anything real. -; Make your own with BakaShrotGenerateKeyPairs.exe. -; -; Every option is documented in Server/Config/schema.ini. -; ============================================================================ - -[BakaShrot] -; This server's private key. Its public key, which the client needs, is -; k32QNiTXL9lA7DhdwBQv9jQXouADujciaOWVZuA3JE4= (the server logs it too). -PrivateKey = KymGH/iJFcqE0JtGmRmWIsQnKTEl49Zq+qYEsfLHtWOTfZA2JNcv2UDsOF3AFC/2NBei4AO6NyJo5ZVm4DckTg== - -; The node this server authenticates as when it links to peers. It has -; none here. -Node = server - - -; The topics this server has. It gives each an id of its own (they keep it -; across restarts); clients and other servers use the names. -[BakaShrot.Topics] -logs -sensors - -; No [BakaShrot.Nodes]: the nodes come from the sections that define them, -; "server" above and "demo" below (and the ones peers send, as they come). - - -; Sensor readings are kept a day, logs forever (no line for them). -[BakaShrot.Retention] -sensors = 1d - - -[BakaShrot.Server] -; Only reachable from this machine. -Host = 127.0.0.1 -Port = 12360 -ReplicatingTopics = logs;sensors -NetThreadPoolSize = 4 -; Next to this file: Start-Server.ps1 runs the server from this folder. -DatabasePath = ./example.sqlite -MaxAttachmentSize = 64M -; Every acknowledged push is on disk, even through a power loss (the -; default). NORMAL is faster but can lose the last second of messages then. -Synchronous = FULL - - -; The one client: Run-Client.ps1's tools, with client.ini. -[BakaShrot.Client.demo] -; client.ini's PublicKey. -PublicKeys = yr+BW21+EprIVg0SafXbOaqRA1WER0pxO3scNqZECtc= -; The node this key writes as, fixed: every message it pushes is stored -; under it, so no client can push as another's node. client.ini's Node -; must say the same. -Node = demo -; Where its pushes go when they don't name a topic (BakaShrotPushMessage -; without -t). Only a default: it may push to any topic in PushTopics. -DefaultTopic = logs -; The topics it may push to (always as "demo"), and read from. Without -; these two lines: only its DefaultTopic. -PushTopics = logs;sensors -ReadTopics = * -AllowRead = 1 -AllowWrite = 1 -; Raw read-only SQL, for BakaShrotQuery.exe. -AllowQuery = 1 diff --git a/Includes/PB-MessagePack b/Includes/PB-MessagePack deleted file mode 160000 index ea38a45..0000000 --- a/Includes/PB-MessagePack +++ /dev/null @@ -1 +0,0 @@ -Subproject commit ea38a45cf307a8a8165ba910e2bb86fa26512161 diff --git a/Interactors/Python/README.md b/Interactors/Python/README.md deleted file mode 100644 index f16e97f..0000000 --- a/Interactors/Python/README.md +++ /dev/null @@ -1,83 +0,0 @@ -# BakaShrot - Python client -Python client for BakaShrot servers, over `BakaShrot_Client.dll`, without dependencies. - -The wheel includes the DLLs it needs, nothing else to install or compile. \ -Windows 10 or later, 64-bit Python 3.8+. - -> [!NOTE] -> The client and the server must come from the same release, any other protocol version refuses the connection. - - -## Linux -The Linux wheel (`bakashrot--py3-none-linux_x86_64.whl`) holds only the client library, -libsodium comes from the system: `apt install libsodium23` on Debian and Ubuntu. \ -Linux x86-64 with glibc 2.34+ (Debian 12, Ubuntu 22.04 or later), 64-bit Python 3.8+. - -It's tagged `linux_x86_64`, not `manylinux`: manylinux doesn't allow depending on libsodium, -so it goes on Gitea, not PyPI. - -Building it: compile the client in the Docker compiler image (Debian 13, so glibc 2.34 is enough), -named `BakaShrot_Client.dll` as the repository does on Linux, then `make_wheel.py --linux`: -```shell -docker run --rm -v "$PWD":/src:ro -v "$PWD/dist":/out -w /src git.nibblepoker.lu/packages/purebasic:6.41-linux3-trixie-slim \ - sh -c 'apt-get update -qq && apt-get install -y -qq libsodium-dev >/dev/null && pbcompilerc -t --optimizer Client/BakaShrot_Client.pbi -so /out/BakaShrot_Client.dll' -python3 Interactors/Python/make_wheel.py dist dist --linux -``` - - -## Installing -From Gitea: -```shell -pip install --index-url https://git.nibblepoker.lu/api/packages/aziascreations/pypi/simple/ bakashrot -``` - -From a GitHub release, or a release folder: -```shell -pip install https://github.com/aziascreations/BakaShrot/releases/download/v0.0.1/bakashrot-0.0.1-py3-none-win_amd64.whl -pip install python\bakashrot-0.0.1-py3-none-win_amd64.whl -``` - -Usage is in [bakashrot.py](bakashrot.py)'s docstring, and in [example.py](example.py). - - -## Building -`Release.ps1` builds the wheel into `Release\\python\`, and checks it once installed by pip. - -By hand, from the DLLs of a release folder or of `Build\`: -```shell -python Interactors/Python/make_wheel.py Release/ dist -``` - -The version comes from `__version__` in [bakashrot.py](bakashrot.py). - - -## Licenses -The wheel's license is `CC0-1.0 AND ISC`: -* BakaShrot is in the public domain ([CC0](../../LICENSE)). -* The included `libsodium.dll` is under the [ISC license](../../Libs/libsodium/LICENSE), - whose notice must ship with it: it's in the wheel's `dist-info/licenses/`. - -`vcruntime140.dll`, which libsodium needs, isn't included: Python already loads its own. - - -## Uploading - -### Gitea -Requires [twine](https://pypi.org/project/twine/) 6.1+ (for the license metadata), and your Gitea login or an access token with the `write:package` scope. -```shell -pip install twine -twine upload --repository-url https://git.nibblepoker.lu/api/packages/aziascreations/pypi -u aziascreations dist/bakashrot-0.0.1-py3-none-win_amd64.whl -``` - -### GitHub -GitHub has no Python registry, the wheel is attached to the release instead. - -Requires the [GitHub CLI](https://cli.github.com/), logged in with `gh auth login`. -```shell -gh release create v0.0.1 --repo aziascreations/BakaShrot --title "0.0.1" dist/bakashrot-0.0.1-py3-none-win_amd64.whl -``` - -Or, if the release already exists: -```shell -gh release upload v0.0.1 --repo aziascreations/BakaShrot dist/bakashrot-0.0.1-py3-none-win_amd64.whl -``` diff --git a/Interactors/Python/example.py b/Interactors/Python/example.py deleted file mode 100644 index aa02751..0000000 --- a/Interactors/Python/example.py +++ /dev/null @@ -1,42 +0,0 @@ -"""Example app: catches up on a topic/node's messages, then follows new ones. - -Usage: python example.py [--from-start] -Run it from Build\\ (Build.ps1) while BakaShrot_Server.exe runs, e.g.: - python ..\\Interactors\\Python\\example.py client.ini logs local -and push from another terminal: - .\\BakaShrotPushMessage.exe @msg.json client.ini -Ctrl+C to stop. -""" - -import json -import os -import sys - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from bakashrot import Client, ConnectionLostError # noqa: E402 - -if len(sys.argv) < 4: - print(__doc__) - sys.exit(1) - -ini, topic, node = sys.argv[1:4] -after = 0 if "--from-start" in sys.argv[4:] else "latest" - -# The DLL next to the ini (Build\), unless BAKASHROT_DLL says otherwise. -dll = os.environ.get("BAKASHROT_DLL") or os.path.join(os.path.dirname(os.path.abspath(ini)), "BakaShrot_Client.dll") - -try: - with Client.from_ini(ini, dll) as client: - print(f"Connected to {client.host}:{client.port} as node {client.node}, following {topic}:{node}") - for message in client.follow(topic, node, after=after): - # Parsing is the app's business: the server stores anything. - try: - shown = json.dumps(message.json()) - except ValueError: - shown = f"(not JSON) {message.data!r}" - print(f"{message.topic}:{message.node}#{message.id} {shown}") -except KeyboardInterrupt: - pass -except ConnectionLostError as error: - print(error) - sys.exit(1) diff --git a/Interactors/Python/make_wheel.py b/Interactors/Python/make_wheel.py deleted file mode 100644 index 29ff5ff..0000000 --- a/Interactors/Python/make_wheel.py +++ /dev/null @@ -1,204 +0,0 @@ -"""Builds the bakashrot wheel: bakashrot.py with the client library it -needs, so that `pip install` is all a Python app needs, nothing to compile. - - python make_wheel.py [OutDir] [--linux] - -BinDir holds BakaShrot_Client.dll and libsodium.dll (a release folder, or -Build\\). OutDir defaults to the current directory. Release.ps1 runs it. -Prints the wheel's path. - ---linux: the Linux wheel instead, from a Linux build's BakaShrot_Client.dll -(the .so, named as on Windows: bakashrot.py and the tools look for that -name). libsodium isn't in it: it comes from the system (Debian/Ubuntu: -libsodium23), and the wheel needs glibc 2.34+. Tagged linux_x86_64, not -manylinux: manylinux doesn't allow depending on libsodium. Build the .so on -an old enough glibc (the Docker compiler image, Debian 13, needs 2.34). - -Licenses: BakaShrot is CC0-1.0, libsodium ISC, which asks for its notice -in every copy: both are in the Windows wheel's dist-info/licenses/ (LICENSE, -and Libs/libsodium/LICENSE), the metadata says "CC0-1.0 AND ISC". The Linux -wheel only has LICENSE, "CC0-1.0", libsodium not being in it. -vcruntime140.dll, which libsodium.dll needs, isn't in the Windows wheel: -every CPython on Windows has loaded its own already, and that's the one used. - -The wheel is bakashrot--py3-none-win_amd64.whl (or --linux_x86_64.whl), the version being bakashrot.py's __version__. Inside -it, bakashrot.py is bakashrot/__init__.py, the libraries next to it, where -bakashrot.py looks first. Only the standard library: no setuptools, no -build step, and the same inputs give the same wheel (fixed timestamps). -""" - -import base64 -import hashlib -import os -import re -import sys -import zipfile - -HERE = os.path.dirname(os.path.abspath(__file__)) -ROOT = os.path.normpath(os.path.join(HERE, "..", "..")) - -NAME = "bakashrot" -# Zip entries' timestamp, so the wheel only changes when its content does. -FIXED_TIME = (2026, 1, 1, 0, 0, 0) - -USAGE_EXAMPLE = """\ -```python -from bakashrot import Client - -with Client.from_ini("client.ini") as client: - message_id = client.push({"temperature": 21.5}) - for message in client.get_messages("logs", "kitchen", after=0).messages: - print(message.id, message.data) -``` - -See the module's docstring (`help(bakashrot)`) for the rest. -""" - -WINDOWS = { - "tag": "py3-none-win_amd64", - "libraries": ["BakaShrot_Client.dll", "libsodium.dll"], - # In the wheel's dist-info/licenses/, from the repository's root. - "licenses": {"LICENSE": "LICENSE", "libsodium/LICENSE": "Libs/libsodium/LICENSE"}, - "license_expression": "CC0-1.0 AND ISC", - "classifier": "Operating System :: Microsoft :: Windows :: Windows 10", - "summary": "Python client for BakaShrot servers, with the client DLL included", - "description": """\ -# bakashrot - -Python client for [BakaShrot](https://github.com/aziascreations/BakaShrot) -servers: push messages and attachments, read them back, resolve names, query. - -Includes `BakaShrot_Client.dll` and `libsodium.dll`: nothing else to install -or build. Windows 10 or later, 64-bit Python 3.8+. The server must speak the -same protocol: use the release this package comes from. - -BakaShrot is CC0-1.0 (public domain). The included libsodium is Frank -Denis's, under the ISC license: its notice is in this package's -`licenses/libsodium/LICENSE`. - -""" + USAGE_EXAMPLE, -} - -LINUX = { - "tag": "py3-none-linux_x86_64", - "libraries": ["BakaShrot_Client.dll"], - "licenses": {"LICENSE": "LICENSE"}, - "license_expression": "CC0-1.0", - "classifier": "Operating System :: POSIX :: Linux", - "summary": "Python client for BakaShrot servers, with the client library included", - "description": """\ -# bakashrot - -Python client for [BakaShrot](https://github.com/aziascreations/BakaShrot) -servers: push messages and attachments, read them back, resolve names, query. - -Includes the client library (`BakaShrot_Client.dll`, a Linux shared object -named as on Windows). Needs libsodium from the system, nothing else to build: -`apt install libsodium23` on Debian and Ubuntu. Linux x86-64 with glibc 2.34+ -(Debian 12, Ubuntu 22.04 or later), 64-bit Python 3.8+. The server must speak -the same protocol: use the release this package comes from. - -BakaShrot is CC0-1.0 (public domain). - -""" + USAGE_EXAMPLE, -} - - -def read_version(module_path): - with open(module_path, encoding="utf-8") as file: - match = re.search(r'^__version__ = "([^"]+)"', file.read(), re.MULTILINE) - if not match: - sys.exit(f"No __version__ in {module_path}") - return match.group(1) - - -def record_line(path, data): - digest = base64.urlsafe_b64encode(hashlib.sha256(data).digest()).rstrip(b"=").decode("ascii") - return f"{path},sha256={digest},{len(data)}" - - -def main(): - args = sys.argv[1:] - platform = WINDOWS - if "--linux" in args: - args.remove("--linux") - platform = LINUX - if len(args) not in (1, 2): - sys.exit(__doc__) - bin_dir = args[0] - out_dir = args[1] if len(args) == 2 else os.getcwd() - tag = platform["tag"] - - module_path = os.path.join(HERE, "bakashrot.py") - version = read_version(module_path) - dist_info = f"{NAME}-{version}.dist-info" - - files = [] # (path in the wheel, bytes) - with open(module_path, "rb") as file: - files.append((f"{NAME}/__init__.py", file.read())) - for library in platform["libraries"]: - path = os.path.join(bin_dir, library) - if not os.path.isfile(path): - sys.exit(f"Missing {path}") - with open(path, "rb") as file: - data = file.read() - # A Windows DLL starts with "MZ", a Linux .so with "\x7fELF": a - # library from the other platform would only fail once imported. - if platform is LINUX and not data.startswith(b"\x7fELF"): - sys.exit(f"{path} isn't a Linux shared object (build it on Linux, or drop --linux)") - if platform is WINDOWS and data.startswith(b"\x7fELF"): - sys.exit(f"{path} is a Linux shared object (add --linux)") - files.append((f"{NAME}/{library}", data)) - - # Metadata 2.4 (PEP 639): an SPDX expression and the license files, - # without license classifiers (not allowed with an expression). - metadata = "\n".join([ - "Metadata-Version: 2.4", - f"Name: {NAME}", - f"Version: {version}", - f"Summary: {platform['summary']}", - "Author: Herwin Bozet (NibblePoker)", - f"License-Expression: {platform['license_expression']}", - ] + [f"License-File: {name}" for name in platform["licenses"]] + [ - "Project-URL: GitHub, https://github.com/aziascreations/BakaShrot", - "Project-URL: Gitea, https://git.nibblepoker.lu/aziascreations/BakaShrot", - f"Classifier: {platform['classifier']}", - "Classifier: Programming Language :: Python :: 3", - "Requires-Python: >=3.8", - "Description-Content-Type: text/markdown", - "", - platform["description"], - ]).encode("utf-8") - files.append((f"{dist_info}/METADATA", metadata)) - files.append((f"{dist_info}/WHEEL", "\n".join([ - "Wheel-Version: 1.0", - "Generator: BakaShrot make_wheel.py", - "Root-Is-Purelib: false", - f"Tag: {tag}", - "", - ]).encode("utf-8"))) - for name, source in platform["licenses"].items(): - path = os.path.join(ROOT, source) - if not os.path.isfile(path): - sys.exit(f"Missing {path}") - with open(path, "rb") as file: - files.append((f"{dist_info}/licenses/{name}", file.read())) - - record = "\n".join([record_line(path, data) for path, data in files] + [f"{dist_info}/RECORD,,", ""]) - files.append((f"{dist_info}/RECORD", record.encode("utf-8"))) - - os.makedirs(out_dir, exist_ok=True) - wheel_path = os.path.join(out_dir, f"{NAME}-{version}-{tag}.whl") - with zipfile.ZipFile(wheel_path, "w", zipfile.ZIP_DEFLATED) as wheel: - for path, data in files: - info = zipfile.ZipInfo(path, FIXED_TIME) - info.compress_type = zipfile.ZIP_DEFLATED - # The shared object must stay executable for some loaders. - info.external_attr = (0o755 if path.endswith(".dll") and platform is LINUX else 0o644) << 16 - wheel.writestr(info, data) - print(wheel_path) - - -if __name__ == "__main__": - main() diff --git a/Interactors/Python/notes.txt b/Interactors/Python/notes.txt deleted file mode 100644 index f5a77dc..0000000 --- a/Interactors/Python/notes.txt +++ /dev/null @@ -1,2 +0,0 @@ -This interactor should be able toquery a server via a client app. -The client should never parse the JSON, only the final app should. diff --git a/Libs/libsodium/Index of -libsodium-releases-.url b/Libs/libsodium/Index of -libsodium-releases-.url deleted file mode 100644 index 009736f..0000000 --- a/Libs/libsodium/Index of -libsodium-releases-.url +++ /dev/null @@ -1,2 +0,0 @@ -[InternetShortcut] -URL=https://download.libsodium.org/libsodium/releases/ diff --git a/Libs/libsodium/LICENSE b/Libs/libsodium/LICENSE deleted file mode 100644 index 95c22fb..0000000 --- a/Libs/libsodium/LICENSE +++ /dev/null @@ -1,18 +0,0 @@ -/* - * ISC License - * - * Copyright (c) 2013-2026 - * Frank Denis - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ diff --git a/Libs/redist/README.md b/Libs/redist/README.md deleted file mode 100644 index 8fed8d8..0000000 --- a/Libs/redist/README.md +++ /dev/null @@ -1,26 +0,0 @@ -# Runtime redistributables - -DLLs the release needs next to its exes that Windows doesn't always have, -packaged by `Release.ps1`. - -| File | Needed by | From | Version | -|---|---|---|---| -| `x64/vcruntime140.dll` | `libsodium.dll` (the official MSVC build) | Visual Studio 2026 (18) Community, `VC\Redist\MSVC\14.51.36231\x64\Microsoft.VC145.CRT\` | 14.51.36247.0 | - -SHA-256 of `x64/vcruntime140.dll`: -`D1F4225DF2CD877DBF130D5668A021DCE3F94118455FF5EC952061C30AFC9CE7` - -- **Why:** `libsodium.dll` imports `vcruntime140.dll` (the Visual C++ - 2015-2026 runtime). Without it, on a Windows without that runtime - installed, `BakaShrot_Server.exe`, `BakaShrot_Client.dll` and every tool - fail to load. Next to the exe, it's found before any installed one. -- **Not needed:** the other DLLs of that folder (`msvcp140.dll`, - `vcruntime140_1.dll`, ...): nothing imports them. The `api-ms-win-crt-*` - DLLs libsodium also imports are the Universal CRT, part of Windows 10 and - later, so the release needs Windows 10+. -- **Allowed:** files from Visual Studio's `VC\Redist` folder are the ones its - license lets you redistribute with an app. -- **Updating:** copy the newer one from that folder, update this table and - the hash. To check what a binary imports: - `grep -a -o -i -E "(vcruntime[0-9_]*|msvcp[0-9_]*|api-ms-win-crt-[a-z0-9-]+)\.dll" ` -- x86 isn't built, so there's no `x86/`. diff --git a/Libs/redist/x64/vcruntime140.dll b/Libs/redist/x64/vcruntime140.dll deleted file mode 100644 index 410f3a7..0000000 Binary files a/Libs/redist/x64/vcruntime140.dll and /dev/null differ diff --git a/Notes.md b/Notes.md deleted file mode 100644 index 227fca9..0000000 --- a/Notes.md +++ /dev/null @@ -1,979 +0,0 @@ -# BakaShrot - working notes - -Where things stand and what's next, as of 2026-11-09. A new session: read -`CLAUDE.md` first (how to build, test, and the traps), then "Right now" and -"Open items" below. The detailed docs are in `Design/`: - -| Doc | About | -|---|---| -| `Design/Packets.md` | The protocol: framing, every packet, flows, conventions, how to add a packet. | -| `Design/Attachments.md` | Attachments: one per message, in 1 MB parts, uploaded before the message, replicated after it. | -| `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. | - -## Right now (2026-11-10) - -- **Everything is committed**, on `timestamps-retention`: protocol 6 and - the rest (`488ffe4`: the tool renames, protocols 5 and 6, node - identities, error codes, names-only configs, `Synchronous`, schema v8 - (`browse`), `Examples/`, `Restart-Test.ps1`), the Linux fixes - (`5270f25`), then the server without a console on Linux and `Docker/`. - Every suite passes on it (8, see `CLAUDE.md`), it compiles with 5.73 and - 6.40, the push bench gives ~17,000 msg/s for 4 servers with - `Synchronous = FULL`. -- **`Release\20261109-df61ef9-dirty\` is out of date** (before - `Synchronous`, `browse` and the error codes): commit, then - `Release.ps1` again. -- **On Linux** (2026-11-10, `Done: Linux, Docker images`): every suite - passes, the server runs without a console (SIGTERM/SIGINT), `Docker/` - builds it into an image. -- **Found 2026-11-11, testing the Docker image:** the server segfaults on - bad frames while clients are busy (item 21, fixed in `Networking.pbi`, - uncommitted, Linux suites pass, Windows suites to run), a leading BOM is - dropped (22), a NUL cuts a message (23). -- **Suggested next** (not decided by the owner): the server without a - console on Windows (item 1), then whatever the real-world test shows. The run on a - clean Windows is the owner's, not an item here. - -## 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 (since protocol 3, `Design/Cryptography.md`; - the protocol is at 6: attachments in 4, node-only identities in 5, - refusal codes in 6). - - A client authenticates as a node (`[BakaShrot.Client.] Node`, - one per section, a key may be in several); its pushes go to that - section's `DefaultTopic` unless they name one. - - Topics are listed by name (`[BakaShrot.Topics]`), the server gives the - ids and keeps them; nodes come from the sections that use them, - `[BakaShrot.Nodes]` is optional, peers' nodes are taken as they come - (`AcceptNodes = *` by default). - - `[BakaShrot.Server] Synchronous = FULL` (default, every acknowledged - push on disk) or `NORMAL` (faster, a power loss can lose the last - second). - - 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`). - - Stamps every push with the time it arrived (`pushed_at`, UTC ms), which - replication carries as is, and deletes each topic's messages past its - max age (`[BakaShrot.Retention]`, per server). - - A message can have one attachment of any size up to `MaxAttachmentSize` - (default 1G), sent in 1 MB parts, replicated after its message - (`Design/Attachments.md`). - - One thread per client and per peer, each with its own SQLite connection. - - The root thread can stop every worker (restart, vacuum). -- **Errors:** every refusal carries a code, every client failure too - (`Client/BakaShrot_ErrorCodes.pbi`): `BakaShrot_GetLastError()` in the - DLL, `error.code` in Python, the name in the tools' messages. Nothing - reconnects by itself; delivery is at least once. -- **Database tools:** the `messages` view (by names), and `browse` / - `browse_messages` to pick a topic from a dropdown in SQLiteStudio. -- **Example:** `Examples/SingleServer/`, a server and a client with scripts - (its keys committed on purpose, public). -- **Client:** a DLL with A/W string exports, PureBasic prototypes in - `Client/BakaShrot_Client_Prototypes.pbi`, and tools in `Tools/`: - `BakaShrotPushMessage` (`-a` to attach a file), - `BakaShrotGetLatestMessage`, `BakaShrotGetMessages` (with `--follow`), - `BakaShrotGetAttachment`, `BakaShrotResolveIds`, `BakaShrotList`, - `BakaShrotQuery`, `BakaShrotGenerateKeyPairs`. -- **Python:** `Interactors/Python/bakashrot.py`, over the DLL with ctypes, - no dependencies, and `example.py`. -- **Release:** `Release.ps1` builds with PB 6.40's C backend into - `Release\-\` with a zip, and smoke-tests it. - -## Renamed: group id -> topic id (2026-11-07) - -- Everywhere: code (`TopicId`, `ReplicatingTopicIds`, `IsReplicatingTopic`, - ...), config keys (`TopicId =`, `ReplicatingTopicIds =`), the DLL export - (`BakaShrot_SetTopicId`), the columns (`topic_id`), docs, bench - placeholders (`{TOPIC}`). Not "group commit", `PreferenceGroup*` or SQL - `GROUP BY`. The wire format is unchanged (fields are positional). -- **Old configs need their keys renamed** by hand, `GroupId` is no longer - read. Build.ps1 writes the new ones. -- **Old databases are migrated on start** (`MigrateStorageTopicIds()` in - `Storage.pbi`, schema `db_schema_v4.dbml`). Tested on a v2 and a v3 - database, and two servers replicating after both were migrated. - -## Done: topic and node names, filters (2026-11-07) - -- **Names are the shared identity, ids are per server.** `[BakaShrot.Topics]` - and `[BakaShrot.Nodes]` (`logs = 1`): "logs" can be 1 here and 200 on a - peer. Replication sends names, the receiver stores under its own ids. - Kept on purpose even though using the same ids everywhere would be - simpler: hand-written configs drift, names keep them matching anyway. - Rules for a "ref" (name or id): `Commons/Networking/Names.pbi`. -- **Only what's named on both servers replicates.** Unnamed topics and - nodes, and names the other side doesn't have, are dropped. The sync - state of every check-in lists every name the receiver takes from that - peer, and its wildcards, and the sender only sends those: no refusal at - every check-in. Unnamed ones still work locally, by id. -- **Wildcards (2026-11-07),** like file names: `*` any characters, `?` one, - no case, only names (`Commons/Networking/Names.pbi`). In every topic list - (`ReplicatingTopics`, `SendTopics`, `AcceptTopics`, `PushTopics`, - `ReadTopics`) and in the peers' new node lists `SendNodes` (default `*`) - and `AcceptNodes` (default: the nodes named here). In `AcceptTopics` / - `AcceptNodes`, `*` and wildcards also take names this server doesn't have - (`BakaShrot_Names_Ingest()`): highest free id counting down from 65535, - origin "peer". So `AcceptNodes = kitchen-*` saves listing every kitchen - node on every server. Clients still can't create topics by name. -- **A peer authenticates by name:** its own node must be named the same - on the servers it links to (it sends its name when it has one). It sent - a topic too before protocol 5. -- **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 - (`BakaShrotPushMessage -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 - `BakaShrotList` tool (`BakaShrot_ListTopics/Nodes()` + `BakaShrot_GetNamesList()` - as JSON, request `ListNames`), `BakaShrotResolveIds` 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, if more than 16 MB is ever needed: - done since, see `Design/Attachments.md`. 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:** `BakaShrotGetMessages [--after ] - [--limit ] [--follow] [--interval ] [ClientIni]`: one line per message, id, tab, - data as stored. `--follow` polls every 500 ms once caught up, exits 1 when - the connection fails. Polling, not pushed by the server: fine for a few - followers, a subscription would be the next step if many follow. -- **Python** (`Interactors/Python/bakashrot.py`): `Client(...)` or - `Client.from_ini()`, `push()` (a str as is, anything else as JSON), - `latest()` (None if none), `get_messages()` -> page with `.more`, - `iter_messages()`, `follow()`, `resolve_topic/node()`, `list_topics/nodes()`, - `query()` / `query_raw()`. `RefusedError` (still connected) vs - `ConnectionLostError`. Uses the DLL's UTF-8 exports, a lock serializes - calls. **One connection per process** (the DLL's globals): a second - Client can't connect while one is. ~9,600 pushes/s on one connection, - against ~75/s launching `BakaShrotPushMessage.exe` each time. -- **Released:** `BakaShrotGetMessages.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. - -## State on 2026-11-08: good, mid, bad - -As judged for the threat model below (internal tool, trusted machines). - -**Good** -- The core works and is tested end to end: push, latest, runs of messages - and `--follow`, names and ids, filters and wildcards, raw read-only SQL, - per-client permissions, retention, attachments; eight `Tests/*.ps1` - suites, two `.pb` tests, the release's smoke test (PB 6.40 C), all - passing (see `CLAUDE.md` for the list). -- Fast: ~40,800 msg/s pushed across 4 servers (10 nodes each, PB 5.73), - fully replicated; ~9,000 msg/s from one Python connection. -- Replication by name, each server with its own ids; restart catch-up is - designed in (nothing it needs lives only in memory). -- Security beyond what's needed here: encrypted connections, both ends - proven, peer links verified. -- Data: 16 MB messages, anything stored (`is_json`), errors of queries - surfaced; pushed times; retention per topic and server; one attachment - per message, any size, flat memory (512 MB with the server at 15 MB). -- Clients: DLL for any language, CLI tools, dependency-free Python. -- Packaging (runtime included) and docs that match the code. - -**Mid** -- Replication: gaps aren't detected; two servers writing the same - topic/node pair can drift (fine with one writer per pair, a rule to - state); the sync state must fit in one packet. -- `synchronous = NORMAL`: a power loss can lose the last commits (a killed - process loses nothing committed). Often fine internally, to decide. -- Client: one connection per process, `--follow` polls, no reconnect. -- Tests run by hand, on fixed ports, no runner, no CI. -- Linux tested, Docker images (2026-11-10); keys in plain-text inis (file - permissions are enough here). - -**Bad** -- The server can't run unattended: it needs a console, stops at once - without one, can't be stopped cleanly from a script, so no service. The - main blocker for deploying it. -- Never run from the extracted zip, on a clean Windows, nor with two - release servers, nor restarted after a kill: designed to work, unchecked. -- A corrupted stored attachment is re-sent to peers forever (open item 3). - -Commits (at this writing, check `git log`): `master` has everything up to -protocol 3 (`12fbe5f`); branch `timestamps-retention` adds timestamps and -retention (`9caf816`); attachments and their tests were left uncommitted on -that branch, waiting for the owner to ask. - -Suggested order: a stop file and running as a service; smoke-test items -1-3 (`Design/Release.md`); the corrupted-attachment fix; a single test -runner, then CI. - -## Done: pushed times, retention (2026-11-08) - -- **`pushed_at`:** every message has the time it was pushed, in - milliseconds since 1970 UTC, set by the server it was pushed to when the - push arrived (its clock), and kept as is on every server it's replicated - to (`ReplicateMessages` carries it). Clients get it in `LatestMessage` - and `Messages`: `BakaShrot_GetMessagePushedAt()` in the DLL, - `Message.pushed_at` / `.pushed` (a UTC datetime) in Python, - `BakaShrotGetMessages --time`, and `BakaShrotGetLatestMessage` shows it. In SQL: - `data.pushed_at`, and `pushed_at` / `pushed_utc` (text) in the - `messages` view. -- **Upgrade:** a database from before gets the column, every message - stamped with the time of the upgrade (their real time is unknown), so a - max age counts from then for them (schema v6, `db_schema_v6.dbml`). -- **Protocol:** folded into version 3 (not released yet, like the - encryption); a v3 build from before today can't talk to this one. -- **Retention:** `[BakaShrot.Retention]` in each server's config, - `topic = age` by name or id, pattern (`sensors.* = 12h`), or `*`; ages - like `30d`, `1d12h`, `forever`. Every `RetentionInterval` seconds - (`[BakaShrot.Server]`, default 60), `Server/Storage/Retention.pbi` - deletes what was pushed before now minus the age, 5000 at a time through - the writer, so pushes go on. Each server applies its own: a peer keeps - its copies by its own rules. An age without a unit refuses to start. -- **What deleting keeps:** `node_heads`, so ids never go back (the writer's - next id now comes from it), and peers aren't sent again what a server - deleted. -- **Skipped on arrival:** what a peer replicates already past this - server's max age for the topic isn't stored, but its head still goes up - to it, so the peer doesn't send it again (`InsertReplicatedMessages()`'s - `SkipBeforeMs`). Each peer's thread has its own copy of the rules. The file doesn't shrink, SQLite reuses the space; `vacuum` - gives it back. -- **Cost:** a column and a `(topic_id, pushed_at)` index entry per message; - no slowdown measured (40,817 msg/s for 4 servers, PB 5.73, - `Tests/Bench/Bench-Replication.ps1 -Ramp 10x0 -Parts Ramp`). -- **Tested:** `Tests/Retention-Test.ps1` (52 checks, ports 12408-12409): - the upgrade of an old database (needs Python), stamps within the push's - time, `--time`, the same `pushed_at` on both servers, deleting by name, - pattern and `*` on one server only, ids going on after it, nothing sent - again, skipped on arrival (B started late: its head goes up, nothing - stored, nothing sent again), the bad age refused. Python checks - `pushed_at` too. -- **By topic only, on purpose:** no per-node max age. -- **Removed:** the `archives` table, a leftover of the first schemas that - nothing ever used, dropped from existing databases at start. - -## Done: attachments (2026-11-08) - -- **One per message**, optional: bytes of any size up to the server's - `MaxAttachmentSize` (default 1G, at most 1T), no name or type (the JSON - says what it is), a size and a SHA-256. Protocol version 4, schema v7. -- **Pushing:** uploaded first in 1 MB parts (UploadStart, UploadChunk), the - server checks the SHA-256, then the PushMessage carries the upload's id: - the message and its attachment are stored in the same transaction, so - readers never see one without the other. Uploads not pushed within - `UploadTimeout` (default 3600 s) are deleted. -- **Reading:** a part per request (GetAttachment), checked by the client. - Messages tell `AttachmentSize` and `AttachmentReady`. -- **Replication:** separate from the messages, after them: the message - carries the size and SHA-256, then at each check-in the peer lists what - it's missing (MissingAttachments), the sender sends the parts, from where - the peer stopped. Over the receiver's `MaxAttachmentSize`: the message - comes, the attachment is marked not kept and never asked for. -- **Deleted with its message** (retention): triggers mark the data, the - retention thread deletes its parts 32 at a time. It now always runs. -- **Clients:** DLL `BakaShrot_PushMessageWithFile/WithData()`, - `_SaveAttachment()`, `_LoadAttachment()` + `_GetAttachmentData()`, - `_GetMessageAttachmentSize()`, `_IsMessageAttachmentReady()`; Python - `push(..., attachment=bytes or path)`, `get_attachment()`, - `save_attachment()`, `Message.attachment_size/_ready`; tools - `BakaShrotPushMessage -a`, `BakaShrotGetAttachment`. -- **Measured:** 512 MB up in 8.5 s, down in 3.9 s, identical, the server - peaking at 15 MB of memory. The push benchmark isn't affected (messages - without attachments only gain a LEFT JOIN on reads). -- **Tested:** `Tests/Attachments-Test.ps1` (39 checks, ports 12410-12411), - Python's checks (55 in all now); every other suite still passes. -- **Edge cases tested:** `Tests/AttachmentEdges-Test.ps1` (51 checks, a raw - protocol client): wrong SHA-256, parts out of order / wrong size / - repeated, others' uploads, wrong topic, attached twice, too big, uploads - expiring past `UploadTimeout`, replication resuming after the receiver - was killed mid-transfer, a corrupted stored copy. All hold. -- **Found:** a server whose own copy is corrupted re-sends it to its peers - at every check-in, forever, and serves it to clients (who refuse it). - Not fixed: open item 3 below has the details and the proposed fix. -- **Left:** resuming an upload after a dropped connection (replication - does resume); several parts in flight for high-latency links. - See `Design/Attachments.md`. - -## Renamed: the tools (2026-11-08) - -Every tool is prefixed with `BakaShrot` (no `_`, the server keeps -`BakaShrot_Server`), folder, source and exe alike, three renamed too: - -| Before | Now | -|---|---| -| KeyGen | BakaShrotGenerateKeyPairs | -| ListNames | BakaShrotList | -| Resolve | BakaShrotResolveIds | -| PushMessage, GetLatestMessage, GetMessages, GetAttachment, Query | BakaShrotPushMessage, BakaShrotGetLatestMessage, ... | - -The packets and DLL functions keep their names (`ListNames`, -`GetMessages`, `BakaShrot_ResolveTopic()`...). Older sections below -still say the old names where they tell what was done then. - -## Done: tools wait for Enter when started from Explorer (2026-11-08) - -- **Every tool** ends through `ToolConsole_End()` (`Tools/Common/ToolConsole.pbi`, - included by `ToolClient.pbi`, and by BakaShrotGenerateKeyPairs directly): started directly - (a double-click, a shortcut), it prints "Press Enter to close..." and - waits, so what it printed (the usage, BakaShrotGenerateKeyPairs' keys) can be read before - its console closes. -- **Started directly** = alone on its console (`GetConsoleProcessList`, as - [PB-Template-Win32-CliApp](https://github.com/aziascreations/PB-Template-Win32-CliApp) - does it) **and** its input and output are a console: a redirected tool - never waits, even alone on a new hidden console (the `--follow` test's - `Start-Process -WindowStyle Hidden -RedirectStandardOutput`). Never - waits outside of Windows. -- **Checked:** from a shell, from Python's `subprocess`, hidden and - redirected: no wait; `Start-Process` in a new window: waits. Every suite - still passes; compiles with 5.73 and 6.40. - -## Done: error codes, protocol 6 (2026-11-09) - -- **Every failure has a code**, in `Client/BakaShrot_ErrorCodes.pbi` - (shipped next to the prototypes, which include it), with what to do about - each in its header: - - 1-99, sent by the server with each refusal (`RequestRefused` got a - `Code`, protocol 5 -> 6): NotAllowed, UnknownName, NotFound, NotReady, - TooBig, NoDefaultTopic, InvalidRequest, DataMismatch, QueryFailed, - ServerError. Each of the server's 64 refusals has one. - - 100+, the client's own: NotConnected, ConnectFailed, AuthRejected, - ServerNotVerified, ConnectionLost, ProtocolError, InvalidArgument, - FileError, AttachmentMismatch, AlreadyConnected, Internal. The - handshake (`Outbound.pbi`) tells where it failed: unreachable, closed - by the server (wrong ServerPublicKey, key or node not allowed, another - version), the server's signature wrong. -- **DLL:** `BakaShrot_GetLastError()` after any call that can fail (0 when - it succeeded); `BakaShrot_ErrorName()` names a code. Set where it - happens (`BakaShrot_Fail()`), the lost connection, refusals and - unexpected answers in one place each. -- **Python:** `ErrorCode` (IntEnum, the same numbers), `error.code` on every - exception; `RefusedError` (1-99), `ConnectionLostError` (not connected, - unreachable, lost, protocol error: connect again), the new `AuthError` - (rejected or unverified: fix the config). `latest()` tells "no message" - by its code, not its text. -- **Tools:** failures print the code's name, "Refused by the server - (UnknownName): Unknown topic 'nope'", "Failed to connect and - authenticate to host:port (AuthRejected): ..."; exit codes unchanged (1). - `BakaShrotGetMessages --after latest` only starts from the start on - NotFound, any other refusal is told. -- **Nothing reconnects by itself**, decided: apps act on the codes. A push - whose answer was lost may be stored twice if retried: at least once, - accepted (11b). -- **Tested:** the Python client's checks (UNKNOWN_NAME, NOT_FOUND, - NOT_ALLOWED, QUERY_FAILED, INVALID_ARGUMENT, FILE_ERROR, - ALREADY_CONNECTED, NOT_CONNECTED, CONNECT_FAILED, AUTH_REJECTED), - `Names-Test.ps1` (the tools' code names), `Restart-Test.ps1` (a killed - server gives the pushers CONNECTION_LOST). - -## Done: restart catch-up tested (2026-11-09) - -- **`Tests/Restart-Test.ps1`** (15 checks, ports 12415-12416, 26 s): two - servers, a client node pushing on each through `Tests/restart_pusher.py` - (as fast as answers come, logging every acknowledged id), servers killed - with `Stop-Process -Force` (TerminateProcess, like a crash): - 1. B killed while both push, A goes on alone for 3 s, B restarted. - 2. B killed again partway through catching up (9,376 -> 10,806 of 22,064 - kitchen messages when killed), restarted. - 3. A killed while both push (the other direction), restarted. -- **All hold:** every acknowledged push survived, ids 1..n without a gap - on both servers, the last acknowledged message is the one pushed, the - next push gets the next id, and both servers end with the same messages - (counts, ids, data and pushed_at sums equal), each catching up on what - the other got meanwhile. The logs show nothing but the links lost and - retried while a server was down. -- **Found:** a push committed but not answered before the kill (#26272 - stored, #26271 the last answered): a client retrying it stores it twice - (open item 11b). -- With `Synchronous = FULL`, the default; a killed process loses nothing - committed with `NORMAL` either (only a power loss or an OS crash would). - -## Done: browsing a topic from a database tool, schema v8 (2026-11-09) - -- **A view can't take a parameter**, and SQLiteStudio has no dropdown for - one. It does show a dropdown for a column with a foreign key (its - `FkComboBox`, in the installed copy), so: -- **`browse`**: one row (`id = 1`), `topic` referencing `topics(name)` and - `node` referencing `nodes(name)` (NULL: every node). Set them from the - dropdowns, commit, open **`browse_messages`**: that topic's messages, - newest first, with `node`, `message_id`, `pushed_utc`, `message_data`, - `is_json`, `attachment_size`. Index searches all the way (by name, then - `(topic_id, pushed_at)`). -- **The server never writes `browse`** nor turns foreign keys on, so the - references never get in its way; a topic renamed in the config only - leaves a stale name there. Made by `SetupStorageDatabase()`, so every - database gets them at its next start (`db_schema_v8.dbml`). -- **Writing to it while the server runs** is a short write next to the - server's (it waits up to its 5 s busy timeout). A database tool left - open on a table holds a read snapshot, which keeps checkpoints from - finishing: the WAL grows until it's closed. -- **Tested:** `Names-Test.ps1` sets it with Python's `sqlite3` (foreign - keys on, like SQLiteStudio): a topic lists its messages, a node narrows - them, a name that isn't a topic is refused. Not tested by hand in - SQLiteStudio itself. - -## Done: Synchronous, FULL by default (2026-11-09) - -- **`[BakaShrot.Server] Synchronous`**: `FULL` (default, every commit - flushed: an acknowledged push survives a power loss) or `NORMAL` - (flushed at checkpoints, about every second: faster, but a power loss - can lose the last second and hand its ids out again). `OFF` and `EXTRA` - are refused, saying why. The server logs it ("ready (synchronous FULL)"). -- **Measured** (`Design/StorageConcurrency.md`): `FULL` halves the push - ceiling here (17,200 msg/s for 4 servers instead of 33,900), a single - sequential client gets ~1/flush pushes/s (1,300/s on this VM's 0.6 ms - flush), and a steady load only gets ~0.7 ms more per push. -- **The bench takes `-Synchronous`** (`FULL` by default, like the server), - `-Synchronous NORMAL` to compare with the numbers from before. -- **Before:** the release smoke test passed on the release built with - protocol 5 and names-only configs, and the example ran from its - extracted zip (2026-11-09). Not done: a run on a clean Windows. -- **Tested:** `Names-Test.ps1` checks the C server starts with `NORMAL` - and logs it, and that `OFF` is refused; every suite passes with the - `FULL` default. - -## Done: the server picks the ids, nodes come from their sections (2026-11-08) - -- **`[BakaShrot.Topics]` is a list of names**, one per line. The server - gives each its id: the one its database already has for the name, else - the lowest free one (`AssignConfigId()`, `Config.pbi`), so the order - doesn't matter and ids never move. `name = id` still pins one: every - existing config works as it is (the tests and `Build.ps1` keep their - pinned ids, they check the translation between servers). -- **`[BakaShrot.Nodes]` is optional:** `[BakaShrot] Node`, every peer's and - client's `Node` name their node by themselves (`DeclareConfigNode()`), - before any node list is read. List only the others to know by name. -- **The root reads the database's names before the config** - (`BakaShrot_Names_ReadKnown()`, `Root.pbi`), from `DatabasePath` read - ahead. `BakaShrot_Names_Load()` then reconciles as before. -- **A peer's `AcceptNodes` defaults to `*`** (was: the named ones only): - other servers' clients come as they come, under ids of this server's - counting down from 65535. `AcceptNodes` still narrows it per peer. -- **Found: the Preferences library misreads LF files** with keys without - `=`: it takes the next line for the value, a section header too, losing - that whole section. The config is now opened through a CRLF copy in the - temporary folder when it has LF line endings (`OpenConfigPreferences()`), - deleted once read. -- **Tested:** `Names-Test.ps1` (55 checks): two servers with names-only - topics and no nodes listed (C's in an LF file), ids in order, the nodes - from the sections, D taking a node it never named, C restarted with its - topics reordered and a new one: same ids. Every suite and the push bench - (35,600 msg/s) pass; compiles with 5.73 and 6.40. The example's - `server.ini` lists names only. - -## Done: protocol 5, a client's node and default topic apart (2026-11-08) - -- **Client sections** (`[BakaShrot.Client.]`): `Node` (required, the - node that key writes as) and `DefaultTopic` (optional, where its pushes - go when they don't name a topic) instead of `Identities = Topic:Node;...`. - `PushTopics` / `ReadTopics` default to `DefaultTopic`, nothing without - one. A key that writes as several nodes is in a section per node. -- **Why the node:** every push is stored under the authenticated node, so - the server decides which node each key writes as. The topic was only - ever the default one, and mixing the two made it look like more. -- **The Hello carries the node only** (protocol 4 -> 5): `client.ini`, - the DLL (`BakaShrot_SetTopic*()` removed), the tools and Python - (`Client(...)` lost its `topic` argument) have no topic any more. A push - without one and no `DefaultTopic` is refused ("No default topic for this - client"). -- **Servers too:** `[BakaShrot] Topic` and peers' `Topic` aren't read any - more (ignored if left), a server links to its peers by node only. -- **Old configs:** `Identities` makes the server refuse to start, saying - what to write (`Node = garage and DefaultTopic = logs instead of - Identities = logs:garage`). -- **Tested:** `Names-Test.ps1` (now 49 checks): no `DefaultTopic` means a - push must name its topic, a key can't write as another section's node - (and the log says why), the old `Identities` refused. Every suite and - the push bench (36,400 msg/s, no failures) pass; compiles with 5.73 and - 6.40. - -## Done: examples, one server and one client (2026-11-08) - -- **`Examples/`**, one folder per setup with its README, indexed in - `Examples/README.md`. The first, `Examples/SingleServer/`: one server on - 127.0.0.1:12360, one client (`logs:demo`, may push to logs and sensors, - read all, query), retention on sensors. -- **Its configs are committed, keys included** (a fixed key pair each, - marked as public and example-only in the files and the README). Every - other config with keys stays out of git. -- **`Start-Server.ps1`** opens the server in its own window and waits until - it listens (`-Here` in the current console, `-Reset` deletes its - database). **`Run-Client.ps1`** pushes (to its topic, another topic, with - an attachment), reads back (latest, every message with `--time`, the - attachment, checked), resolves and lists names, runs a SQL query; it - prints each command, pasteable from the example's folder. Both take - `-BinDir`, `Build\` by default. -- **Git ignores** what they write: `Examples/**/*.sqlite*`, `Examples/**/out/`. -- **Checked:** both scripts, twice in a row (the ids go on), the - double-start guard, the README's Python snippet. `Start-Server.ps1 -Here` - wasn't (it needs an interactive console). - -## Done: Linux, Docker images (2026-11-10) - -- **Every suite passes on Linux** (Ubuntu, x64) with 6.41's asm and C - backends: `Tests/*.ps1` through PowerShell 7, once `-WindowStyle Hidden` - is dropped (not supported there), the binaries named as on Windows - (`BakaShrot_Client.dll` is the `.so`), `-Build` given. 5.73 compiles and - passes the rest, but can't restart a server on the same port within - ~60 s (its listener doesn't set `SO_REUSEADDR`): Names, Restart and - AttachmentEdges. -- **Fixed on the way:** SQLite on Linux is the system's `libsqlite3.so.0` - (`#BakaShrot_Storage_SqliteLibrary`), so the query error check and the - writer's prepared statements work there too; `BakaShrot_SendPacket()` - retries when the send buffer is full (`EAGAIN`, it aborted clients - reading big answers); four tests that relied on Windows timing. -- **The server runs without a console on Linux** (item 1, there): SIGTERM - and SIGINT stop it like `quit`, and with no console input it runs on - until one comes. `Input()` can't do it: on Linux it returns `""` (quit) - at the end of the input, and PureBasic's console moves descriptor 0 - elsewhere, so `ReadCommand()` reads a `dup` of it taken before - `OpenConsole()`, `poll()`ing 250 ms at a time. Checked with no input, - piped commands (CRLF too), a terminal, `quit`, both signals, on 5.73 and - 6.41. -- **`Docker/Server/`** (multi-stage: built with the C backend and the - optimizer on `git.nibblepoker.lu/packages/purebasic:6.41-linux3-trixie-slim`, - run on `debian:trixie-slim` with libsodium and SQLite only, as user - `bakashrot`). The compiler image was `Docker/Compiler/` at first, built - from a PureBasic archive copied in by hand; removed for the registry's - (2026-11-11, needs a `docker login`, it's licensed). Config - `/etc/bakashrot/server.ini`, data volume `/var/lib/bakashrot`, port 12345. - Checked: pushes, reads and queries through the port, `docker stop` clean - (~0.3 s, exit 0), data kept over a restart, commands with `-i`. Alpine was - tried: PureBasic needs glibc 2.38+. -- **`Docker/Server/docker-compose.yml`** (2026-11-11): builds and runs the - image with `server.ini` next to it (an empty config to fill in: no key, - topic or client, the server refuses it as is), the `bakashrot-data` - volume and a console for `docker attach`. Not run yet (no Docker on the - dev machine; the Linux one has Docker but no `compose` plugin). - -## Checked: the Docker image under load, the Linux tools (2026-11-11) - -Image built from `master` (`5887e70`), driven from the host through -`bakashrot.py` and the Linux client `.so`, built in the same compiler image -with every tool (all compile with `--optimizer`). Scripts not committed. - -- **Passed:** 4 concurrent pushers of random data (JSON of any shape, - control and astral characters, non-JSON, up to 1.5 MB, 1 % at 8-16 MB, - 15 % with 1 B-6 MB attachments): every acked message stored as sent - (bar item 22), ids increasing, attachments identical. `docker kill` - (SIGKILL) and `docker restart` (SIGTERM, ~0.2 s) 3 times each under that - load: 3600 acked, none lost, the pushers reconnect. Refusals and limits - (unknown topic/node, PushTopics, ReadTopics, AllowWrite/Query, a - MAX_MESSAGE_SIZE message, a 64M attachment at a 64M MaxAttachmentSize and - one byte over, non-SELECT and >10000-row queries, wrong keys, wrong node), - the connection still usable after each. 500 idle sockets open: a client - is still served in 0.04 s. Every tool against it (push with attachment, - get, `--follow`, query, resolve, list, refusals). -- **Failed: the server segfaults on bad frames under load** (item 21, - fixed the same day). -- **Seen, harmless:** `SELECT 1; DELETE FROM messages` answers the SELECT, - SQLite only runs the first statement (nothing deleted). -- **No Linux wheel** (item 20): `make_wheel.py` stops at "Missing - BakaShrot_Client.dll" on a Linux build folder, and would tag it - `win_amd64` anyway. - -## Done: the Python wheel (2026-11-11) - -- **`Interactors/Python/make_wheel.py`** packs `bakashrot.py` (as - `bakashrot/__init__.py`) with `BakaShrot_Client.dll` and `libsodium.dll` - into `bakashrot--py3-none-win_amd64.whl`: `pip install` and - done, nothing to compile. Standard library only (no setuptools), same - inputs give the same wheel. The version is `bakashrot.py`'s - `__version__` (0.0.1). -- **Licenses:** libsodium is ISC, its notice must ship with every copy: - `Libs/libsodium/LICENSE` (from its 1.0.22-RELEASE tag) goes in the - wheel's `dist-info/licenses/` with ours, the metadata (2.4) says - `License-Expression: CC0-1.0 AND ISC`. The release zip ships both too - (`LICENSE.txt`, `LICENSE-libsodium.txt`), it didn't before. No - `vcruntime140.dll` in the wheel: CPython on Windows has loaded its own, - libsodium uses that one (checked by the release's smoke test). -- Works without touching the loader: `bakashrot.py` looks next to itself - first, and Python 3.8+ loads a DLL's dependencies from its own folder. -- **`Release.ps1`** builds it into `python\` (if Python is on the PATH), - and its smoke test installs it with pip into a folder, then reads and - pushes from another folder with no DLL path: passes (6.40 C build). -- Uploading: Gitea's PyPI registry (twine), GitHub has none, so the wheel - goes on the GitHub release (`gh release`). Commands in - `Interactors/Python/README.md`. -- **Windows only.** Linux: open item 20, without bundling libsodium. - -## 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) - Done on Linux (2026-11-10): SIGTERM/SIGINT stop it, it runs on without - console input (`Done: Linux, Docker images`). Windows still needs it. -2. **The 1.0.0 smoke test, what's left:** replication between two servers - built by `Release.ps1` (the suites use `BenchServer.exe`, the same server - code). Done: the release's own smoke test and the example from its zip - (2026-11-09), restart catch-up (`Restart-Test.ps1`, 2026-11-09). The run - on a clean Windows is the owner's, as needed: not an open item here. - (`Design/Release.md`, items 1-3) -3. **A corrupted stored attachment is re-sent to peers forever.** Found - by `Tests/AttachmentEdges-Test.ps1` part 4 (a byte flipped in the - sender's `blob_chunks`, `flip.py`). - - What happens: the peer checks the SHA-256 once all parts are in, - drops its copy (`FinishReplicatedAttachment(..., #False)`), refuses the - last part ("The attachment doesn't match its SHA-256, send it again"), - and lists it as missing again. At the next check-in the sender sends - all of it again: every `PeerSyncInterval` (6 times in 6 s in the test), - 1 GB each time for a 1 GB attachment. Forever. - - The sender never notices: it also serves the damaged parts to clients - (`GetAttachment`), who refuse them by their SHA-256 (the DLL checks at - the end of `BakaShrot_Download()`). - - Proposed fix, in `BakaShrot_PeerLink_SendAttachment()` - (`Server/Networking/Peers.pbi`): when the peer refuses with "doesn't - match", check this server's own copy with `HashStorageBlob()` - (`Server/Storage/Attachments.pbi`, the link's own `DbId`). If it's - damaged, `FinishReplicatedAttachment(TopicId, NodeId, MessageId, - BlobId, #False)` already does the rest: drops the blob, marks the - attachment missing (state 0), so this server stops sending it and asks - its own peers for a good copy (`MissingAttachments`), and stops - serving it. Log it loudly. If its copy is fine (the damage was in - transit), sending again is right. - - The refusal now has its own code (DataMismatch, protocol 6): match - that rather than the text. - - The origin (where it was pushed) has no other source: its attachment - then stays missing ("isn't here yet"), better than serving bad data; - maybe a "lost" state (4) so `BakaShrotGetAttachment` says so. - - Optional, to catch it on reads too: a SHA-256 per part in - `blob_chunks`, checked by `ReadStorageBlobChunk()`, at ~3 s/GB. - - Test: part 4 of `AttachmentEdges-Test.ps1` then expects the sender to - log its copy as damaged and the re-sends to stop (today it only prints - an INFO line with the count); its own `attachments` row goes to 0. -4. ~~**`synchronous = NORMAL`**~~: done, `[BakaShrot.Server] Synchronous`, - `FULL` by default (see "Done: Synchronous" above). -5. ~~**Drift between servers**~~: ruled out by config, a node pushes to - one server (written in `schema.ini` and `Design/ReplicationIssues.md` - #1). Not an open item: nothing to do unless that rule has to go. -6. **Gaps in a pair's ids aren't detected** on replication. - (`Design/ReplicationIssues.md` #5) -7. **No single test runner**, and fixed ports (12399, 12401-12416): every - `Tests/*.ps1` and the two `.pb` tests are run by hand. Needed for CI. - (`Design/Release.md`, "For CI/CD") -8. ~~**Is `DatabaseError()` per thread?**~~ Yes, checked (2026-11-09): - two threads failing on their own connections 20,000 times each, never - once the other's message, with 5.73 and 6.40 (`/THREAD`). - `sqlite3_errmsg16()` on the connection gives the same messages, kept as - is. Linux: not checked the same way, its suites pass (2026-11-10). -9. **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 - -10. **One connection per process** (the DLL's globals): a handle-based API - for several. Polling rather than server-pushed subscriptions. Nothing - reconnects by itself, on purpose: the error codes tell the app when to - (see "Done: error codes" above). -11. ~~**Breaking with protocols 3 to 6**~~: in the release notes now - (`VERSION.txt`, "Compatibility", written by `Release.ps1`): servers and - clients from the same release only, what old configs need. -11b. ~~**A push whose answer was lost can be stored twice if retried.**~~ - Accepted, the way it is: delivery is at least once. A server killed - between committing a push and answering it keeps it (`Restart-Test.ps1` - saw #26272 stored, #26271 the last answered), the client gets - ConnectionLost; pushing it again stores it twice. Documented in - `BakaShrot_ErrorCodes.pbi`, the DLL's header and `bakashrot.py`; a - client that minds checks the latest message before retrying. - -### Security, low priority under the threat model - -12. **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) -13. **Private keys sit in plain-text ini files**, readable by whoever can - read the config. On trusted machines: file permissions are enough. -14. **No key rotation or revocation**, other than editing configs and - restarting; a server can't announce a new key, clients pin one. -15. **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. -16. **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 - -17. **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. -18. ~~**Linux is untested**~~ Done (2026-11-10): every suite passes, see - `Done: Linux, Docker images`. -19. **Console commands can't be scripted** (see 1). -20. ~~**No Linux wheel.**~~ Done (2026-11-11, uncommitted): - `make_wheel.py --linux`, the client `.so` only (built in the Docker - compiler image, needs glibc 2.34+), libsodium from the system - (`libsodium23`), tagged `linux_x86_64`. Installed by pip on Python 3.13 - (Debian 13) and 3.8 (Debian 12), talks to the `0.0.1` server image; - `twine check` passes; uploaded to Gitea's PyPI registry (0.0.1). The - Windows wheel is byte-identical to before. Was: the Windows one bundles `libsodium.dll` next to the - client DLL; on Linux, find a way not to bundle libsodium like that, - maybe through a package: the distribution's (`libsodium23`, as the - Docker image does, the wheel then holding only the client `.so`), or - a Python package that provides it. See `Done: the Python wheel`. -21. ~~**The server crashes on bad frames while clients are busy**~~ Fixed - (2026-11-11, uncommitted on `master`), as proposed below: every suite - passes on Linux with 6.41's C and asm backends, 5.73 compiles it, the - reproducer (5 rounds in Docker) no longer crashes. Windows: suites not - run yet. Retention-Test failed once, then passed 4 times: its scan - caught B's "the check-in failed" while A was stopping first (a race - in the test, `Stop-Srv $SA` before `$SB`, unrelated). (Linux, - found 2026-11-11, `Checked: the Docker image under load`). Garbage on - raw sockets (random bytes, bad lengths, anything giving "sent an - invalid frame") while two clients push: SIGSEGV in - `PB_SimpleList_Remove()` under `NetworkServerEvent()`, or - `malloc(): unsorted double linked list corrupted`, 3 times out of 3. - Garbage alone, or clients alone, don't. Cause: the listener calls - `NetworkServerEvent()` without `*Server\Mutex`, while a client thread - aborting calls `CloseNetworkConnection()` (`BakaShrot_NetClient_Thread`, - `Networking.pbi`), also without it: both change PureBasic's connection - list. Fix, tested in a copy (5 rounds of the same load, no crash, same - push speed): the listener locks the mutex around `NetworkServerEvent()` - and the event's handling (not around `WaitEvent`), the abort around - `CloseNetworkConnection()`. -22. **A leading UTF-8 BOM is dropped from pushed messages** (found - 2026-11-11): `"{}"` is stored as `{}`, a lone BOM as `""`. Only - the first one, a BOM elsewhere is kept. Before storage (the stored - hex has no `EFBBBF`). Not `PeekS(..., #PB_UTF8)`, checked: it keeps it. - Noted for now, not looked into further. -23. **A message with a NUL is cut there, silently** (found 2026-11-11): - `bakashrot.py` passes data as a C string (`PushMessageToA`), - `"before\x00after"` is stored as `before`. Refuse it in `push()`, or - send a length. - -### 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). -- `pushed_at` timestamps, carried by replication; retention per topic and - server, skipping on arrival what's past its age (2026-11-08). -- Attachments, protocol 4: one per message, in 1 MB parts, replicated after - their message, resumable; edge cases tested (2026-11-08). -- Tools renamed `BakaShrot`, waiting for Enter when started from - Explorer; `Examples/SingleServer/` (2026-11-08). -- Protocol 5: a client is a node, its default topic the server's - (`Node`, `DefaultTopic`); names-only topics, ids picked by the server, - nodes from their sections, `AcceptNodes = *` (2026-11-08). -- `Synchronous`, `FULL` by default, measured (2026-11-09). -- Schema v8: `browse` / `browse_messages` for database tools (2026-11-09). -- Restart catch-up tested: kills mid-traffic and mid-catch-up, nothing - acknowledged lost (`Restart-Test.ps1`, 2026-11-09). -- Protocol 6: error codes everywhere, at-least-once delivery accepted - (2026-11-09). -- Linux: every suite passes, the server runs without a console there, - a `Docker/` image for the server (2026-11-10). - -## 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 on - Windows, and the server stops on it. On Linux it returns `""`, and the - server reads its commands itself (`ReadCommand()`): piping commands into - it works there. -- **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. -- **JSON on a tool's command line loses its double quotes** (PowerShell 5 - and PureBasic's `ProgramParameter()`): the tests write it to a file and - pass `@file`. -- **Things only a raw client can do** (a wrong SHA-256, abandoned uploads): - `Tests/AttachmentEdgeClient.pb`, over `Commons/Networking/Outbound.pbi`. - Copy its `Exchange()` / `Refusal()` helpers for new protocol tests. -- **Log scans in the tests skip "Refused a request" lines:** refusals are - expected, and their codes' names (`InvalidRequest`, `QueryFailed`) hold - the words the scans look for. PowerShell's `-match` ignores case. -- **Traffic while a server is killed:** `Tests/restart_pusher.py` pushes as - fast as answers come and logs every acknowledged id, then the error's - code; `Restart-Test.ps1` shows how to read it back. -- **Corrupting or seeding a database** from a test: Python's `sqlite3`, - with the server stopped through its stop file (its WAL is checkpointed - then), see `Retention-Test.ps1` (an old schema) and - `AttachmentEdges-Test.ps1` (`flip.py`). diff --git a/Release.ps1 b/Release.ps1 deleted file mode 100644 index f6c2af6..0000000 --- a/Release.ps1 +++ /dev/null @@ -1,412 +0,0 @@ -# ============================================================================ -# BakaShrot release build -# -# Builds everything with PureBasic 6.40's C backend and its optimizer into -# Release\\, ready to copy to a server or hand to a client: -# BakaShrot_Server.exe the server -# BakaShrot_Client.dll the client DLL, with -# BakaShrot_Client_Prototypes.pbi its PureBasic prototypes, and -# BakaShrot_ErrorCodes.pbi the error codes they include -# BakaShrotPushMessage.exe, BakaShrotGetLatestMessage.exe, -# BakaShrotGetMessages.exe, BakaShrotGetAttachment.exe, BakaShrotQuery.exe, -# BakaShrotResolveIds.exe, BakaShrotList.exe, -# BakaShrotGenerateKeyPairs.exe the tools -# libsodium.dll, sqlite3.dll what they need next to them -# vcruntime140.dll what libsodium.dll needs (Libs\redist) -# python\bakashrot.py, example.py the Python client, over the DLL -# python\bakashrot-*.whl the same with the DLLs in it, for pip -# (if Python is on the PATH) -# config.example.ini the server's config, documented -# VERSION.txt commit, date, compiler, libraries -# LICENSE.txt, LICENSE-libsodium.txt BakaShrot's (CC0), libsodium's (ISC, -# its notice must ship with it) -# and Release\BakaShrot-.zip of it, unless -NoZip. -# -# No keys and no configs with keys in it: generate them with BakaShrotGenerateKeyPairs.exe. -# -# Then checks the build works, unless -SkipTest: generates keys, runs the -# server from the release folder on a spare port with a throwaway database, -# pushes two messages, reads them back by name (the latest, then both), -# resolves a name and queries it through the "messages" view with the -# tools, reads them with the Python client if Python is on the PATH, then -# stops the server and deletes all of it. -# -# Usage: -# powershell -ExecutionPolicy Bypass -File Release.ps1 -# ... -Version 1.2.0 instead of - -# ... -Force replaces Release\\ if it exists -# ... -Compiler -NoOptimizer -SqliteDll -SkipTest -NoZip -# -# Needs libsodium in Libs\libsodium\x64 and sqlite3.dll (3.38+, for the JSON -# functions) in Libs\sqlite\x64, Build.ps1 extracts both from Libs\*.zip. -# ============================================================================ - -param( - [string]$Version = "", - [string]$Compiler = "C:\Program Files\PureBasic_640\Compilers\pbcompilerc.exe", - [switch]$NoOptimizer, - [string]$SqliteDll = "", - [string]$OutRoot = "", - [switch]$Force, - [switch]$SkipTest, - [switch]$NoZip, - [int]$TestPort = 12399 -) - -$ErrorActionPreference = "Stop" - -$Root = $PSScriptRoot -if (-not $OutRoot) { $OutRoot = Join-Path $Root "Release" } - - -# --- Checks ----------------------------------------------------------------- - -if (-not (Test-Path $Compiler)) { throw "Compiler not found: $Compiler, pass -Compiler" } -$CompilerName = ((& $Compiler /VERSION) | Select-Object -First 1) -replace " - \(c\).*$", "" -if ($CompilerName -notmatch "PureBasic 6\.") { throw "Expected PureBasic 6.x, got '$CompilerName'" } -if ($CompilerName -notmatch "C Backend") { Write-Warning "Not the C backend: $CompilerName" } - -$Sodium = Join-Path $Root "Libs\libsodium\x64\libsodium.dll" -if (-not (Test-Path $Sodium) -or -not (Test-Path (Join-Path $Root "Libs\libsodium\x64\libsodium.lib"))) { - throw "Missing Libs\libsodium\x64\libsodium.dll/.lib, run Build.ps1 once to extract them" -} -if (-not $SqliteDll) { $SqliteDll = Join-Path $Root "Libs\sqlite\x64\sqlite3.dll" } -if (-not (Test-Path $SqliteDll)) { throw "Missing $SqliteDll, run Build.ps1 once to extract it, or pass -SqliteDll" } -$SqliteVersion = (Get-Item $SqliteDll).VersionInfo.ProductVersion -if ([version]$SqliteVersion -lt [version]"3.38") { throw "SQLite $SqliteVersion is too old, the JSON functions need 3.38+" } -$SodiumVersion = (Get-Item $Sodium).VersionInfo.ProductVersion -# Its ISC license asks for its notice in every copy, the wheel's too. -$SodiumLicense = Join-Path $Root "Libs\libsodium\LICENSE" -if (-not (Test-Path $SodiumLicense)) { throw "Missing Libs\libsodium\LICENSE, libsodium's notice must ship with it" } -# The runtime DLLs Windows may not have, see Libs\redist\README.md. -$Redist = @(Get-ChildItem (Join-Path $Root "Libs\redist\x64") -Filter "*.dll" -ErrorAction SilentlyContinue) -if (-not ($Redist | Where-Object { $_.Name -eq "vcruntime140.dll" })) { - throw "Missing Libs\redist\x64\vcruntime140.dll, libsodium.dll needs it, see Libs\redist\README.md" -} -$RedistVersion = ($Redist | Where-Object { $_.Name -eq "vcruntime140.dll" }).VersionInfo.FileVersion - -# The commit, marked "dirty" if anything isn't committed. -$Commit = "nogit" -$Dirty = $false -Push-Location $Root -try { - $Commit = (git rev-parse --short HEAD 2>$null) - if ($LASTEXITCODE -ne 0 -or -not $Commit) { $Commit = "nogit" } - else { $Dirty = [bool](git status --porcelain 2>$null) } -} catch { $Commit = "nogit" } -finally { Pop-Location } - -if (-not $Version) { - $Version = (Get-Date -Format "yyyyMMdd") + "-" + $Commit - if ($Dirty) { $Version += "-dirty" } -} - -$OutDir = Join-Path $OutRoot $Version -if (Test-Path $OutDir) { - if (-not $Force) { throw "$OutDir already exists, pass -Force to replace it" } - Remove-Item -Recurse -Force $OutDir -} -New-Item -ItemType Directory -Force $OutDir | Out-Null - -Write-Host "Release $Version -> $OutDir" -Write-Host "Compiler: $CompilerName$(if (-not $NoOptimizer) { ' /OPTIMIZER' })" -Write-Host "SQLite $SqliteVersion, libsodium $SodiumVersion" -if ($Dirty) { Write-Warning "Uncommitted changes, the version is marked dirty" } - - -# --- Build ------------------------------------------------------------------ - -$Common = @("/QUIET") -if (-not $NoOptimizer) { $Common += "/OPTIMIZER" } - -$Targets = @( - @("Server\BakaShrot_Server.pb", "BakaShrot_Server.exe", @("/CONSOLE", "/THREAD")), - @("Client\BakaShrot_Client.pbi", "BakaShrot_Client.dll", @("/DLL", "/THREAD")), - @("Tools\BakaShrotPushMessage\BakaShrotPushMessage.pb", "BakaShrotPushMessage.exe", @("/CONSOLE")), - @("Tools\BakaShrotGetLatestMessage\BakaShrotGetLatestMessage.pb", "BakaShrotGetLatestMessage.exe", @("/CONSOLE")), - @("Tools\BakaShrotGetMessages\BakaShrotGetMessages.pb", "BakaShrotGetMessages.exe", @("/CONSOLE")), - @("Tools\BakaShrotGetAttachment\BakaShrotGetAttachment.pb", "BakaShrotGetAttachment.exe", @("/CONSOLE")), - @("Tools\BakaShrotQuery\BakaShrotQuery.pb", "BakaShrotQuery.exe", @("/CONSOLE")), - @("Tools\BakaShrotResolveIds\BakaShrotResolveIds.pb", "BakaShrotResolveIds.exe", @("/CONSOLE")), - @("Tools\BakaShrotList\BakaShrotList.pb", "BakaShrotList.exe", @("/CONSOLE")), - @("Tools\BakaShrotGenerateKeyPairs\BakaShrotGenerateKeyPairs.pb", "BakaShrotGenerateKeyPairs.exe", @("/CONSOLE")) -) - -Push-Location $Root -try { - foreach ($Target in $Targets) { - Write-Host "Compiling $($Target[0])" - $Flags = $Target[2] + $Common - & $Compiler (Join-Path $Root $Target[0]) @Flags /OUTPUT (Join-Path $OutDir $Target[1]) - if ($LASTEXITCODE -ne 0) { throw "Failed to compile $($Target[0])" } - } -} -finally { - Pop-Location -} - -# The DLL's import library and exports aren't needed to use it. -Get-ChildItem $OutDir -Include "*.lib", "*.exp" -Recurse | Remove-Item -Force - -Copy-Item $Sodium $OutDir -Copy-Item $SodiumLicense (Join-Path $OutDir "LICENSE-libsodium.txt") -Copy-Item (Join-Path $Root "LICENSE") (Join-Path $OutDir "LICENSE.txt") -foreach ($File in $Redist) { Copy-Item $File.FullName $OutDir } -Copy-Item $SqliteDll (Join-Path $OutDir "sqlite3.dll") -Copy-Item (Join-Path $Root "Client\BakaShrot_Client_Prototypes.pbi") $OutDir -Copy-Item (Join-Path $Root "Client\BakaShrot_ErrorCodes.pbi") $OutDir -New-Item -ItemType Directory -Force (Join-Path $OutDir "python") | Out-Null -foreach ($File in @("bakashrot.py", "example.py")) { - Copy-Item (Join-Path $Root "Interactors\Python\$File") (Join-Path $OutDir "python") -} -# The wheel: bakashrot.py with this release's DLLs, `pip install` and done. -$Wheel = $null -$PythonExe = Get-Command python -ErrorAction SilentlyContinue -if ($PythonExe) { - $Wheel = & $PythonExe.Source -B (Join-Path $Root "Interactors\Python\make_wheel.py") $OutDir (Join-Path $OutDir "python") - if ($LASTEXITCODE -ne 0) { throw "Failed to build the Python wheel: $Wheel" } - Write-Host "Wheel: $Wheel" -} -else { - Write-Warning "No python on the PATH, no wheel" -} -Copy-Item (Join-Path $Root "Server\Config\schema.ini") (Join-Path $OutDir "config.example.ini") - -$VersionText = @" -BakaShrot $Version -Built: $(Get-Date -Format "yyyy-MM-dd HH:mm:ss") -Commit: $Commit$(if ($Dirty) { " (with uncommitted changes)" }) -Compiler: $CompilerName$(if (-not $NoOptimizer) { " /OPTIMIZER" }) -SQLite: $SqliteVersion -libsodium: $SodiumVersion -VC++ runtime: $RedistVersion (vcruntime140.dll, for libsodium.dll) - -Needs Windows 10 or later, 64-bit. Keep the DLLs next to the exes. -Licenses: BakaShrot is CC0 (LICENSE.txt), libsodium ISC (LICENSE-libsodium.txt), -SQLite public domain, vcruntime140.dll under Visual Studio's redistribution terms. - -Run the server: BakaShrot_Server.exe config.ini - Its config: config.example.ini. Keys: BakaShrotGenerateKeyPairs.exe, the - private key goes in [BakaShrot] PrivateKey, the public key in the configs that trust it, and - in its clients' client.ini as ServerPublicKey (it logs it when it starts). - Every connection is encrypted, and only reaches the server holding the - private key of the ServerPublicKey (or peer PublicKey) it was given. - It reads commands from its console (quit, restart, vacuum, help), so it - needs one: it stops right away without console input. - Topics and nodes go by name ([BakaShrot.Topics], [BakaShrot.Nodes]) or id, - each server has its own ids for the same names. - [BakaShrot.Server] Synchronous = FULL (default) flushes every push to disk - before answering it; NORMAL is faster but a power loss can lose the last - second of messages. See config.example.ini. -Tools, next to BakaShrot_Client.dll, with a client.ini: - BakaShrotPushMessage [-t ] [-a ] [ClientIni] - BakaShrotGetLatestMessage [ClientIni] - BakaShrotGetMessages [--after ] [--limit ] [--follow] [--interval ] [--time] [ClientIni] - BakaShrotGetAttachment [ClientIni] - BakaShrotResolveIds [ClientIni] - BakaShrotList [topics|nodes|all] [ClientIni] [--json] - BakaShrotQuery [ClientIni] e.g. SELECT * FROM messages WHERE topic = 'logs' - client.ini: [BakaShrot] PrivateKey, PublicKey, Node (the node it writes - as, a name or an id), ServerHost, ServerPort, ServerPublicKey. Where its - pushes go by default is the server's DefaultTopic for it. -Python (3.8+, 64-bit): python\bakashrot.py, no dependencies, uses - BakaShrot_Client.dll (set BAKASHROT_DLL, or pass dll_path). See its - docstring, and python\example.py . - Or pip install python\bakashrot-*.whl: the same, with the DLLs in it. -Compatibility: protocol 6. Servers and clients (the DLL, the tools, the - Python client) must come from the same release: any other version - refuses the connection, there's no mixing. From an older release: - - server configs: [BakaShrot.Client.] Identities = topic:node is - refused at start, write Node = node and DefaultTopic = topic (the - server's message says which); [BakaShrot] and peer sections' Topic is - ignored; [BakaShrot.Topics] can be names alone, [BakaShrot.Nodes] can - go; Synchronous = FULL is the default now (NORMAL was); - - client.ini: Topic is ignored, ServerPublicKey is required; - - apps: BakaShrot_ErrorCodes.pbi next to the prototypes, SetTopic() is - gone, and a database made before is upgraded in place at the first - start (keep a copy). -Errors: every failure has a code, BakaShrot_GetLastError() in the DLL, - error.code in Python (bakashrot.ErrorCode), the name in the tools' - messages. BakaShrot_ErrorCodes.pbi lists them, and what to do about each. - Nothing reconnects by itself. A push whose answer was lost may have been - stored: pushed again, it's stored twice (at least once delivery). -"@ -Set-Content -Path (Join-Path $OutDir "VERSION.txt") -Value $VersionText -Encoding UTF8 - - -# --- Test ------------------------------------------------------------------- - -function New-KeyPair { - $Lines = & (Join-Path $OutDir "BakaShrotGenerateKeyPairs.exe") - if ($LASTEXITCODE -ne 0) { throw "BakaShrotGenerateKeyPairs failed: $Lines" } - return @{ - PrivateKey = $Lines[0] -replace "^PrivateKey = ", "" - PublicKey = $Lines[1] -replace "^PublicKey = ", "" - } -} - -function Test-Port($Port) { - $Client = New-Object System.Net.Sockets.TcpClient - try { - $Async = $Client.BeginConnect("127.0.0.1", $Port, $null, $null) - return ($Async.AsyncWaitHandle.WaitOne(200) -and $Client.Connected) - } catch { return $false } - finally { $Client.Close() } -} - -function Invoke-Tool($Name, [string[]]$Arguments) { - $Output = & (Join-Path $OutDir $Name) @Arguments 2>&1 - if ($LASTEXITCODE -ne 0) { throw "$Name failed: $Output" } - return ($Output -join "`n") -} - -if (-not $SkipTest) { - Write-Host "Testing the build" - - # Inside the release folder: exes run from temp folders get blocked by - # the antivirus here, and the tools look for the DLL next to themselves. - $TestDir = Join-Path $OutDir "_test" - New-Item -ItemType Directory -Force $TestDir | Out-Null - $Server = $null - try { - if (Test-Port $TestPort) { throw "Port $TestPort is already in use, pass -TestPort" } - - $ServerKeys = New-KeyPair - $ClientKeys = New-KeyPair - - Set-Content -Path (Join-Path $TestDir "server.ini") -Encoding Ascii -Value @" -[BakaShrot] -PrivateKey = $($ServerKeys.PrivateKey) -Node = server - -[BakaShrot.Topics] -releasetest = 7 - -[BakaShrot.Nodes] -server = 1 -tester = 2 - -[BakaShrot.Server] -Host = 127.0.0.1 -Port = $TestPort -ReplicatingTopics = releasetest -DatabasePath = $(Join-Path $TestDir "test.sqlite") - -[BakaShrot.Client.test] -PublicKeys = $($ClientKeys.PublicKey) -Node = tester -DefaultTopic = releasetest -AllowRead = 1 -AllowWrite = 1 -AllowQuery = 1 -"@ - Set-Content -Path (Join-Path $TestDir "client.ini") -Encoding Ascii -Value @" -[BakaShrot] -PrivateKey = $($ClientKeys.PrivateKey) -PublicKey = $($ClientKeys.PublicKey) -Node = tester -ServerHost = 127.0.0.1 -ServerPort = $TestPort -ServerPublicKey = $($ServerKeys.PublicKey) -"@ - Set-Content -Path (Join-Path $TestDir "message.json") -Encoding Ascii -Value '{"release":"test","value":42}' - - # Its own (hidden) console: without console input, the server stops - # right away. - $Server = Start-Process -FilePath (Join-Path $OutDir "BakaShrot_Server.exe") -ArgumentList "`"$(Join-Path $TestDir 'server.ini')`"" ` - -WorkingDirectory $TestDir -WindowStyle Hidden -PassThru - $Deadline = (Get-Date).AddSeconds(15) - while (-not (Test-Port $TestPort)) { - if ($Server.HasExited) { throw "The server exited with code $($Server.ExitCode)" } - if ((Get-Date) -gt $Deadline) { throw "The server isn't listening on $TestPort" } - Start-Sleep -Milliseconds 100 - } - - $ClientIni = Join-Path $TestDir "client.ini" - $Pushed = Invoke-Tool "BakaShrotPushMessage.exe" @("@$(Join-Path $TestDir 'message.json')", $ClientIni) - if ($Pushed -notmatch "message #1") { throw "Unexpected push answer: $Pushed" } - - $Latest = Invoke-Tool "BakaShrotGetLatestMessage.exe" @("releasetest", "tester", $ClientIni) - if ($Latest -notmatch '"release"\s*:\s*"test"' -or $Latest -notmatch '\(ids 7:2\)') { throw "Unexpected latest message: $Latest" } - - $Pushed = Invoke-Tool "BakaShrotPushMessage.exe" @("@$(Join-Path $TestDir 'message.json')", $ClientIni) - if ($Pushed -notmatch "message #2") { throw "Unexpected second push answer: $Pushed" } - # message.json ends with a line break, kept in the data: one empty line after each. - $Messages = @(& (Join-Path $OutDir "BakaShrotGetMessages.exe") "releasetest" "tester" $ClientIni | Where-Object { $_ -ne "" }) - if ($LASTEXITCODE -ne 0 -or $Messages.Count -ne 2 -or $Messages[0] -notmatch '^1\t\{"release"' -or $Messages[1] -notmatch '^2\t') { - throw "Unexpected messages: $($Messages -join ' | ')" - } - - $Resolved = Invoke-Tool "BakaShrotResolveIds.exe" @("topic", "releasetest", $ClientIni) - if ($Resolved -notmatch "topic releasetest = 7") { throw "Unexpected resolved topic: $Resolved" } - - $Sql = Join-Path $TestDir "query.sql" - Set-Content -Path $Sql -Encoding Ascii -Value "SELECT message_data ->> '$.value', is_json, topic_id FROM messages WHERE topic = 'releasetest' AND node = 'tester' AND is_json = 1" - $Queried = Invoke-Tool "BakaShrotQuery.exe" @("@$Sql", $ClientIni) - if ($Queried -notmatch '\[\["42","1","7"\],\["42","1","7"\]\]') { throw "Unexpected query result: $Queried" } - - Write-Host " Pushed, read back by name, resolved and queried messages: OK" - - if ($PythonExe) { - $Script = "import sys; sys.path.insert(0, sys.argv[1]); from bakashrot import Client; " + - "c = Client.from_ini(sys.argv[2], sys.argv[3]); c.connect(); " + - "p = c.get_messages('releasetest', 'tester'); print(len(p), p.messages[0].json()['value'], c.push({'py': 1})); c.close()" - $PyOut = & $PythonExe.Source -B -c $Script (Join-Path $OutDir "python") $ClientIni (Join-Path $OutDir "BakaShrot_Client.dll") 2>&1 - if ($LASTEXITCODE -ne 0 -or "$PyOut" -ne "2 42 3") { throw "Unexpected Python client output: $PyOut" } - Write-Host " Read and pushed with the Python client: OK" - - # The wheel, installed by pip, run from elsewhere with no DLL - # path: it must use the DLLs inside it. - $Installed = Join-Path $TestDir "wheel" - $PipOut = & $PythonExe.Source -m pip install --no-index --no-deps --disable-pip-version-check --quiet --target $Installed $Wheel 2>&1 - if ($LASTEXITCODE -ne 0) { throw "pip couldn't install the wheel: $PipOut" } - $Script = "import os, sys; sys.path.insert(0, sys.argv[1]); import bakashrot; " + - "c = bakashrot.Client.from_ini(sys.argv[2]); c.connect(); " + - "inside = os.path.dirname(c._dll.path) == os.path.dirname(bakashrot.__file__); " + - "print(inside, c.latest('releasetest', 'tester').json()['py'], c.push({'wheel': 1})); c.close()" - Push-Location $TestDir - try { $PyOut = & $PythonExe.Source -B -c $Script $Installed $ClientIni 2>&1 } - finally { Pop-Location } - if ($LASTEXITCODE -ne 0 -or "$PyOut" -ne "True 1 4") { throw "Unexpected output from the wheel: $PyOut" } - Write-Host " Read and pushed with the wheel, installed by pip: OK" - } - else { - Write-Host " No python on the PATH, the Python client wasn't checked" - } - - # An attachment of 3 parts and a bit, up and back. - $Attach = Join-Path $TestDir "attach.bin" - $Bytes = New-Object byte[] (3 * 1024 * 1024 + 17) - (New-Object System.Random 5).NextBytes($Bytes) - [IO.File]::WriteAllBytes($Attach, $Bytes) - $Pushed = Invoke-Tool "BakaShrotPushMessage.exe" @("-a", $Attach, "@$(Join-Path $TestDir 'message.json')", $ClientIni) - if ($Pushed -notmatch "message #(\d+), with an attachment of 3145745 bytes") { throw "Unexpected push with an attachment: $Pushed" } - $AttachedId = $Matches[1] - $Copy = Join-Path $TestDir "attach-copy.bin" - $Saved = Invoke-Tool "BakaShrotGetAttachment.exe" @("releasetest", "tester", $AttachedId, $Copy, $ClientIni) - if ($Saved -notmatch "Saved 3145745 bytes" -or (Get-FileHash $Attach).Hash -ne (Get-FileHash $Copy).Hash) { throw "Unexpected attachment read back: $Saved" } - Write-Host " Pushed and read back an attachment: OK" - } - finally { - if ($Server -and -not $Server.HasExited) { - Stop-Process -Id $Server.Id -Force - $Server.WaitForExit(5000) | Out-Null - } - Remove-Item -Recurse -Force $TestDir -ErrorAction SilentlyContinue - } -} - - -# --- Package ---------------------------------------------------------------- - -if (-not $NoZip) { - Add-Type -AssemblyName System.IO.Compression.FileSystem - $Zip = Join-Path $OutRoot "BakaShrot-$Version.zip" - if (Test-Path $Zip) { Remove-Item -Force $Zip } - [IO.Compression.ZipFile]::CreateFromDirectory($OutDir, $Zip, [IO.Compression.CompressionLevel]::Optimal, $true) - Write-Host "Zip: $Zip" -} - -Write-Host "" -Write-Host "Done: $OutDir" -Get-ChildItem $OutDir | Select-Object Name, @{ n = "KB"; e = { [math]::Round($_.Length / 1KB) } } | Format-Table -AutoSize | Out-String | Write-Host diff --git a/Server/BakaShrot_Server.pb b/Server/BakaShrot_Server.pb deleted file mode 100644 index fa8a568..0000000 --- a/Server/BakaShrot_Server.pb +++ /dev/null @@ -1,249 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: BakaShrot_Server.pb -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; BakaShrot Server - CLI entry point -; -; Usage: BakaShrot_Server [ConfigFile] -; ConfigFile Path to the server's ini config, defaults to "config.ini". -; See Config/schema.ini for its layout. -; -; Loads the config, opens and sets up the database at [BakaShrot.Server] -; DatabasePath, listens on [BakaShrot.Server] Host:Port, and links to every -; [BakaShrot.Peer.]. Then reads commands from the console: -; (empty), quit Stops the server. -; restart Stops every worker, reloads the config, starts again. -; vacuum Stops every worker, VACUUMs the database, starts again. -; names Lists every topic and node with its id and name. -; help Lists the commands. -; See Root.pbi for how the workers are stopped. -; Exits with 0 on success, 1 on failure. -; -; Windows: it stops once there's no more console input (no console, closed -; standard input). Elsewhere, it runs on without one (a container, a -; service) and SIGTERM or SIGINT stops it the same way as "quit". -; -; Compile as a thread-safe console program. -; ============================================================================ - -EnableExplicit - -XIncludeFile "Root.pbi" - - -#BakaShrot_Server_DefaultConfigPath = "config.ini" - - -Procedure PrintCommands() - PrintN("Commands: quit (or an empty line), restart, vacuum, names, help") -EndProcedure - - -CompilerIf #PB_Compiler_OS <> #PB_OS_Windows - ; Same numbers on Linux and macOS. - #BakaShrot_Server_SigInt = 2 - #BakaShrot_Server_SigTerm = 15 - #BakaShrot_Server_PollIn = $0001 - #BakaShrot_Server_FDupFd = 0 - - ; struct pollfd - Structure BakaShrot_Server_PollFd - Fd.l - Events.w - REvents.w - EndStructure - - ImportC "" - BakaShrot_Server_Signal.i(Signal.l, *Handler) As "signal" - BakaShrot_Server_Poll.l(*Fds, Count.i, TimeoutMs.l) As "poll" - BakaShrot_Server_Read.i(Fd.l, *Buffer, Size.i) As "read" - ; dup() itself can't be imported: fasm reserves the name. - BakaShrot_Server_Fcntl.l(Fd.l, Command.l, Argument.i) As "fcntl" - EndImport - - ; Longest command line kept, the rest of a longer one is dropped. - #BakaShrot_Server_MaxCommandSize = 256 - - ; The signal that asked to stop, 0 until then. Only ever set by the - ; handler (all a handler may safely do), read by ReadCommand(). - Global BakaShrot_Server_StopSignal.l = 0 - - ; #True once standard input is closed: commands can't come any more. - Global BakaShrot_Server_NoInput.i = #False - - ; Standard input, taken before OpenConsole(): it moves descriptor 0 - ; elsewhere and closes it (then reused by the next file opened). - Global BakaShrot_Server_InputFd.l = -1 - - ProcedureC BakaShrot_Server_OnSignal(Signal.l) - BakaShrot_Server_StopSignal = Signal - EndProcedure -CompilerEndIf - - -; Waits for the next command, Chr(4) once there's no more input. -; Windows: Input(). Elsewhere, Input() returns "" (quit) at the end of the -; input and blocks until a whole line came, so standard input is read here -; instead: never blocking for more than 250 ms without checking for a stop -; signal (it then returns "", see BakaShrot_Server_StopSignal). -Procedure.s ReadCommand() - CompilerIf #PB_Compiler_OS = #PB_OS_Windows - ProcedureReturn Input() - CompilerElse - Protected Fd.BakaShrot_Server_PollFd, Byte.a, BytesRead.i, Size.i - Protected Dim Chars.a(#BakaShrot_Server_MaxCommandSize) - - Repeat - If BakaShrot_Server_StopSignal - ProcedureReturn "" - EndIf - If BakaShrot_Server_NoInput - Delay(250) - Continue - EndIf - If BakaShrot_Server_InputFd < 0 - ProcedureReturn Chr(4) - EndIf - - Fd\Fd = BakaShrot_Server_InputFd - Fd\Events = #BakaShrot_Server_PollIn - Fd\REvents = 0 - If BakaShrot_Server_Poll(@Fd, 1, 250) <= 0 - Continue - EndIf - - ; Readable, or closed: one byte, so nothing is read past the line. - BytesRead = BakaShrot_Server_Read(BakaShrot_Server_InputFd, @Byte, 1) - If BytesRead = 0 Or (BytesRead < 0 And Not BakaShrot_Server_StopSignal) - ProcedureReturn Chr(4) - EndIf - If BytesRead = 1 - If Byte = 10 - ProcedureReturn PeekS(@Chars(0), Size, #PB_UTF8 | #PB_ByteLength) - EndIf - ; CR of a CRLF skipped. - If Byte <> 13 And Size < #BakaShrot_Server_MaxCommandSize - Chars(Size) = Byte - Size + 1 - EndIf - EndIf - ForEver - CompilerEndIf -EndProcedure - - -Define Root.BakaShrot_Root -Define Command.s, ExitCode.i - -CompilerIf #PB_Compiler_OS <> #PB_OS_Windows - BakaShrot_Server_InputFd = BakaShrot_Server_Fcntl(0, #BakaShrot_Server_FDupFd, 0) -CompilerEndIf - -OpenConsole("BakaShrot Server") - -CompilerIf #PB_Compiler_OS <> #PB_OS_Windows - BakaShrot_Server_Signal(#BakaShrot_Server_SigTerm, @BakaShrot_Server_OnSignal()) - BakaShrot_Server_Signal(#BakaShrot_Server_SigInt, @BakaShrot_Server_OnSignal()) -CompilerEndIf - -Root\ConfigPath = #BakaShrot_Server_DefaultConfigPath -If CountProgramParameters() > 0 - Root\ConfigPath = ProgramParameter(0) -EndIf - -If Not BakaShrot_Root_LoadConfig(@Root) - End 1 -EndIf - -If Not BakaShrot_Root_OpenDatabase(@Root) - FreeConfig(Root\Config) - End 1 -EndIf - -If Not BakaShrot_Root_StartWorkers(@Root) - BakaShrot_Root_CloseDatabase(@Root) - FreeConfig(Root\Config) - End 1 -EndIf - -PrintN("Running.") -PrintCommands() - -ExitCode = 0 -Repeat - Command = LCase(Trim(ReadCommand())) - - CompilerIf #PB_Compiler_OS <> #PB_OS_Windows - If BakaShrot_Server_StopSignal - If BakaShrot_Server_StopSignal = #BakaShrot_Server_SigTerm - PrintN("Got SIGTERM, stopping") - Else - PrintN("Got SIGINT, stopping") - EndIf - Break - EndIf - CompilerEndIf - - ; Once there's no more input (no console, closed standard input), every - ; ReadCommand() returns Chr(4) right away. Without this, it would loop - ; forever. - If FindString(Command, Chr(4)) - CompilerIf #PB_Compiler_OS = #PB_OS_Windows - PrintN("No more input, stopping") - Break - CompilerElse - PrintN("No console input, running until SIGTERM or SIGINT") - BakaShrot_Server_NoInput = #True - Continue - CompilerEndIf - EndIf - - Select Command - Case "", "quit" - Break - - Case "restart" - If Not BakaShrot_Root_Restart(@Root) - PrintN("[Root] Restart failed, stopping") - ExitCode = 1 - Break - EndIf - - Case "vacuum" - If Not BakaShrot_Root_Vacuum(@Root) - PrintN("[Root] Couldn't start again after vacuuming, stopping") - ExitCode = 1 - Break - EndIf - - Case "names" - BakaShrot_Names_Print() - - Case "help" - PrintCommands() - - Default - PrintN("Unknown command '" + Command + "'") - PrintCommands() - EndSelect -ForEver - -PrintN("Stopping...") -BakaShrot_Root_StopWorkers(@Root) -BakaShrot_Root_CloseDatabase(@Root) -FreeConfig(Root\Config) -End ExitCode diff --git a/Server/BakaShrot_Server.pb.cfg b/Server/BakaShrot_Server.pb.cfg deleted file mode 100644 index 1308c0a..0000000 --- a/Server/BakaShrot_Server.pb.cfg +++ /dev/null @@ -1,8 +0,0 @@ -IDE Options = PureBasic 6.41 beta 2 (Windows - x64) -CursorPosition = 15 -FirstLine = 23 -EnableXP -DPIAware -CompileSourceDirectory -EnableCompileCount = 1 -EnableBuildCount = 0 diff --git a/Server/Config/Config.pbi b/Server/Config/Config.pbi deleted file mode 100644 index f1bad8b..0000000 --- a/Server/Config/Config.pbi +++ /dev/null @@ -1,1335 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: Config.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; BakaShrot Server 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, one per line, this server -; gives them their ids ("name = id" pins one) -; [BakaShrot.Nodes] -> node names, the same, optional: the nodes of -; [BakaShrot], the peers and the clients are -; named by their sections -; [BakaShrot.Retention] -> how long each topic's messages are kept -; here, "topic = max age" lines, see -; BakaShrot_RetentionRule -; [BakaShrot.Peer.] -> one BakaShrot_CoreConfig\Peers() entry per -; section. -; [BakaShrot.Client.] -> one BakaShrot_CoreConfig\Clients() entry per -; section. -; -; of a peer or client section is only a key for this file, it is never -; sent on the wire. Topic and node names are: they're what other servers know -; them by, see Commons/Networking/Names.pbi. -; -; Everywhere else, a topic or node is a "ref": a name from those sections, -; or an id in digits. Topic and node lists ("0;logs;100-150;sensors.*") also -; take ranges of ids, patterns like file names ("sensors.*", "kitchen-??", -; see Commons/Networking/Names.pbi), and "*" for every one. In a peer's -; AcceptTopics / AcceptNodes, "*" and patterns also take names this server -; doesn't have: they're added with an id of their own, see -; Server/Storage/Names.pbi. -; -; LoadConfig() returns 0 on any mistake, with the reason in -; BakaShrot_ConfigError. -; ============================================================================ - -XIncludeFile "../../Commons/Networking/Names.pbi" -; #BakaShrot_MaxAttachmentSize. -XIncludeFile "../../Commons/Networking/Packets.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. - Known.i - - ; Str(Id) -> #True, from ids, ranges and names in the list. - Map Ids.i() - - ; Patterns ("sensors.*"), matched against names, known here or not: - ; a peer's topics and nodes it doesn't name are taken if they match. - List Patterns.s() -EndStructure - - -; Ini Section: [BakaShrot.Peer.] (one section per known peer) -; The server links to every peer on start, see Server/Networking/Peers.pbi. -; The peer must register this server in one of its [BakaShrot.Client.]. -; PublicKey is the peer's: a link to it only goes through if the peer -; proves it holds the matching private key (Commons/Networking/Connections.pbi). -; Node is 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 - - ; Node: the remote server's node, a ref resolved to this server's id. - ; The peer authenticates as it when it links to here. - 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 (*), the ones it doesn't name yet - ; are added as they come (Server/Storage/Names.pbi). - 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 - NodeText.s - -EndStructure - - -; What a client is allowed to do once authenticated. -; Ini keys of [BakaShrot.Client.], 1 to allow, 0 to deny. -Structure BakaShrot_ClientPermissions - - ; AllowRead: GetLatestMessage. Defaults to 1. - Read.i - - ; AllowWrite: PushMessage. Defaults to 1. - Write.i - - ; AllowQuery: raw read-only SQL queries. Defaults to 0, they can read - ; every topic's data. - Query.i - -EndStructure - -#BakaShrot_Config_DefaultAllowRead = 1 -#BakaShrot_Config_DefaultAllowWrite = 1 -#BakaShrot_Config_DefaultAllowQuery = 0 - - -; Ini Section: [BakaShrot.Client.] (one section per registered client) -Structure BakaShrot_ClientConfig - - ; Ed25519 public keys (Base64) the client is allowed to authenticate with. - ; Format: Key;Key;... - List PublicKeys.s() - - ; Node: the node it writes as, a ref, required. It sends it in its - ; Hello, which must come with one of PublicKeys. A key listed in several - ; sections may write as each of their nodes. - NodeId.u - - ; DefaultTopic: the topic of its pushes that don't name one, a ref, -1 - ; without one (they're refused then). - DefaultTopicId.l - - ; 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 its DefaultTopic, nothing without one. - PushTopics.BakaShrot_NameSet - ReadTopics.BakaShrot_NameSet - - ; As written in the ini, for SaveConfig(). Chr(1) when missing. - NodeText.s - DefaultTopicText.s - PushTopicsText.s - ReadTopicsText.s - -EndStructure - - -; One line of [BakaShrot.Retention]: messages of the topics it matches may -; be deleted from this server once they were pushed MaxAgeMs ago (see -; Server/Storage/Retention.pbi). Only this server's: each server keeps its -; own, a peer keeps what it was sent as long as its own rules say. -; logs = 30d one topic, by name (known here or not) or id -; sensors.* = 12h a pattern, matching names (Commons/Networking/Names.pbi) -; * = 365d every other topic -; Ages: numbers with a unit, s m h d w, added up ("1d12h"); "forever" (or -; 0) keeps them. A topic takes its id's line, else its name's, else the -; first pattern matching it, in the file's order, else "*"'s. Without any -; line, messages are kept forever. -Enumeration BakaShrot_RetentionKinds - #BakaShrot_Retention_Id = 1 - #BakaShrot_Retention_Name = 2 - #BakaShrot_Retention_Pattern = 3 - #BakaShrot_Retention_Default = 4 -EndEnumeration - -Structure BakaShrot_RetentionRule - Kind.i - ; As written: the topic's name or id, the pattern, or "*". - Ref.s - ; For #BakaShrot_Retention_Id. - TopicId.i - ; 0: kept forever. - MaxAgeMs.q - ; The age as written, for SaveConfig() and the logs. - AgeText.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 - - ; Seconds between two passes deleting the messages past their topic's - ; max age ([BakaShrot.Retention]). Default 60. - RetentionInterval.i - - ; Biggest attachment this server takes, in bytes: pushed with a message, - ; or replicated (a bigger one's message is kept, not its attachment). - ; Written with a unit: 500M, 1G (K M G T, 1024-based). Default 1G. - MaxAttachmentSize.q - MaxAttachmentSizeText.s - - ; Seconds an upload may take, before it's pushed with its message: past - ; that it's deleted. Default 3600. - UploadTimeout.i - - ; PRAGMA synchronous, FULL (default) or NORMAL, see - ; BakaShrot_Storage_Synchronous in Server/Storage/Storage.pbi. - Synchronous.s - -EndStructure - - -; Ini Section: [BakaShrot] -Structure BakaShrot_CoreConfig - - ; This node's Ed25519 private key (Base64), used to sign every packet it - ; sends. Its matching public key must be handed to peers, who store it - ; as PublicKey in the relevant [BakaShrot.Peer.] section of THEIR - ; own config. See Commons/Cryptography/Libsodium.pbi. - PrivateKey.s - - ; Node: the node this server authenticates as when it links to its - ; peers, a ref. Peers must know it by the same name. - NodeId.u - NodeText.s - - ; [BakaShrot.Server] - Server.BakaShrot_ServerConfig - - ; [BakaShrot.Topics] and [BakaShrot.Nodes], plus the nodes the other - ; sections define: LCase(name) -> id, and Str(id) -> name as written. - ; Ids pinned in the config, or given by LoadConfig() (AssignConfigId()). - 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() - - ; [BakaShrot.Retention], in the file's order. - List Retention.BakaShrot_RetentionRule() - - ; One [BakaShrot.Peer.] entry per map key. - Map Peers.BakaShrot_PeerConfig() - - ; One [BakaShrot.Client.] entry per map key. - Map Clients.BakaShrot_ClientConfig() - -EndStructure - - -Macro Ptr_BakaShrot_CoreConfig : i : EndMacro - - -#BakaShrot_Config_DefaultNetThreadPoolSize = 4 -#BakaShrot_Config_DefaultDatabasePath = "./test.sqlite" -#BakaShrot_Config_DefaultPeerRetryDelay = 10 -#BakaShrot_Config_DefaultPeerSyncInterval = 5 -#BakaShrot_Config_DefaultPeerBatchSize = 100 -#BakaShrot_Config_DefaultRetentionInterval = 60 -#BakaShrot_Config_DefaultMaxAttachmentSize = "1G" -#BakaShrot_Config_DefaultUploadTimeout = 3600 -#BakaShrot_Config_DefaultSynchronous = "FULL" - -; 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) - - -; What the database already has (BakaShrot_Names_ReadKnown(), Storage/ -; Names.pbi), for LoadConfig() to give a name listed without an id the id -; it already has: LCase(name) -> id, and Str(id) -> #True for every id it -; has a row or messages for, named or not. -Structure BakaShrot_KnownNames - Map TopicIds.i() - Map TopicUsed.i() - Map NodeIds.i() - Map NodeUsed.i() -EndStructure - -; The one LoadConfig() was given, while it runs. -Global *BakaShrot_ConfigKnown.BakaShrot_KnownNames - - -; Why the last LoadConfig() failed. -Global BakaShrot_ConfigError.s = "" - - -; Reads Key, or OldKey if Key is missing: Node and ReplicatingTopics were -; 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 - - -; Gives Name an id in Ids() / Names(): the one the database already has for -; it (KnownIds()), unless another of the config's names has it, else the -; lowest free one, used neither by the config nor by the database -; (KnownUsed()). Names a peer adds get theirs counting down from 65535. -; Returns the id, -1 if none is left. -Procedure.i AssignConfigId(Name.s, Map Ids.i(), Map Names.s(), Map KnownIds.i(), Map KnownUsed.i()) - Protected Id.i = -1 - - If FindMapElement(KnownIds(), LCase(Name)) - Id = KnownIds() - If FindMapElement(Names(), Str(Id)) - Id = -1 - EndIf - EndIf - If Id < 0 - For Id = 1 To #BakaShrot_MaxId - If Not FindMapElement(Names(), Str(Id)) And Not FindMapElement(KnownUsed(), Str(Id)) - Break - EndIf - Next - If Id > #BakaShrot_MaxId - ProcedureReturn -1 - EndIf - EndIf - - Ids(LCase(Name)) = Id - Names(Str(Id)) = Name - ProcedureReturn Id -EndProcedure - -; A node ref that defines a node: [BakaShrot] Node, a peer's or a client's. -; Resolved like ResolveConfigNode(), and a name [BakaShrot.Nodes] doesn't -; list is named all the same, its id given like one listed without an id. -; -1 if it's neither an id nor a valid name. -Procedure.i DeclareConfigNode(*Config.BakaShrot_CoreConfig, Ref.s) - Protected Id.i = ResolveConfigNode(*Config, Ref) - - If Id >= 0 Or Not BakaShrot_IsValidName(Ref) - ProcedureReturn Id - EndIf - ProcedureReturn AssignConfigId(Ref, *Config\NodeIds(), *Config\NodeNames(), *BakaShrot_ConfigKnown\NodeIds(), *BakaShrot_ConfigKnown\NodeUsed()) -EndProcedure - - -; An age as [BakaShrot.Retention] writes it ("30d", "1d12h", "forever") in -; milliseconds, 0 for forever, -1 if it isn't one. -Procedure.q ParseRetentionAge(Text.s) - Protected i.i, c.s, Digits.s, Total.q, Unit.q, Seen.i - - Text = LCase(Trim(Text)) - If Text = "forever" Or Text = "0" - ProcedureReturn 0 - EndIf - If Text = "" - ProcedureReturn -1 - EndIf - - For i = 1 To Len(Text) - c = Mid(Text, i, 1) - If c >= "0" And c <= "9" - Digits + c - If Len(Digits) > 9 - ProcedureReturn -1 - EndIf - Continue - EndIf - Select c - Case "s" : Unit = 1000 - Case "m" : Unit = 60 * 1000 - Case "h" : Unit = 3600 * 1000 - Case "d" : Unit = 86400 * 1000 - Case "w" : Unit = 7 * 86400 * 1000 - Default : ProcedureReturn -1 - EndSelect - ; A unit needs its number: "d" or "1dd" isn't an age. - If Digits = "" - ProcedureReturn -1 - EndIf - Total + Val(Digits) * Unit - Digits = "" - Seen = #True - Next - - ; A number without a unit: seconds or days? Refused rather than guessed. - If Digits <> "" Or Not Seen - ProcedureReturn -1 - EndIf - ProcedureReturn Total -EndProcedure - - -; A size as MaxAttachmentSize writes it ("500M", "1G", "1048576") in bytes, -; -1 if it isn't one. Units are 1024-based: K M G T. -Procedure.q ParseConfigSize(Text.s) - Protected Unit.q = 1, Digits.s, Last.s, i.i - - Text = UCase(Trim(Text)) - If Text = "" - ProcedureReturn -1 - EndIf - Last = Right(Text, 1) - Select Last - Case "K" : Unit = 1024 - Case "M" : Unit = 1024 * 1024 - Case "G" : Unit = 1024 * 1024 * 1024 - Case "T" : Unit = 1024 * 1024 * 1024 * 1024 - EndSelect - Digits = Text - If Unit > 1 - Digits = Left(Text, Len(Text) - 1) - EndIf - If Digits = "" Or Len(Digits) > 13 - ProcedureReturn -1 - EndIf - For i = 1 To Len(Digits) - If Mid(Digits, i, 1) < "0" Or Mid(Digits, i, 1) > "9" - ProcedureReturn -1 - EndIf - Next - ProcedureReturn Val(Digits) * Unit -EndProcedure - - -; Reads [BakaShrot.Retention] into *Config\Retention(). -; Returns #False on an invalid line, with the reason in BakaShrot_ConfigError. -Procedure.i ParseRetentionSection(*Config.BakaShrot_CoreConfig) - Protected Ref.s, Value.s, MaxAge.q, Id.i - - If Not PreferenceGroup("BakaShrot.Retention") - ProcedureReturn #True - EndIf - - If ExaminePreferenceKeys() - While NextPreferenceKey() - Ref = Trim(PreferenceKeyName()) - Value = Trim(PreferenceKeyValue()) - MaxAge = ParseRetentionAge(Value) - If MaxAge < 0 - BakaShrot_ConfigError = "[BakaShrot.Retention] " + Ref + " = '" + Value + "' isn't an age: numbers with a unit (s m h d w), like 30d or 1d12h, or 'forever'" - ProcedureReturn #False - EndIf - - AddElement(*Config\Retention()) - *Config\Retention()\Ref = Ref - *Config\Retention()\MaxAgeMs = MaxAge - *Config\Retention()\AgeText = Value - *Config\Retention()\TopicId = -1 - Id = BakaShrot_RefToId(Ref) - If Ref = "*" - *Config\Retention()\Kind = #BakaShrot_Retention_Default - ElseIf Id >= 0 - *Config\Retention()\Kind = #BakaShrot_Retention_Id - *Config\Retention()\TopicId = Id - ElseIf BakaShrot_IsValidName(Ref) - ; A name this config doesn't have may still come from a peer. - *Config\Retention()\Kind = #BakaShrot_Retention_Name - ElseIf BakaShrot_IsValidPattern(Ref) - *Config\Retention()\Kind = #BakaShrot_Retention_Pattern - Else - BakaShrot_ConfigError = "[BakaShrot.Retention] '" + Ref + "' isn't a topic name, id, pattern or *" - ProcedureReturn #False - EndIf - Wend - EndIf - - ; Two lines for the same topic: the second would silently lose. - Protected NewMap Seen.i() - ForEach *Config\Retention() - Ref = LCase(*Config\Retention()\Ref) - If FindMapElement(Seen(), Ref) - BakaShrot_ConfigError = "[BakaShrot.Retention] '" + *Config\Retention()\Ref + "' is given twice" - ProcedureReturn #False - EndIf - Seen(Ref) = #True - Next - - ProcedureReturn #True -EndProcedure - - -; How long a topic's messages are kept by *Config's [BakaShrot.Retention], -; in ms, 0 for forever. Name is "" for an unnamed topic. -Procedure.q RetentionMaxAgeMs(List Rules.BakaShrot_RetentionRule(), TopicId.i, Name.s) - Protected *Default.BakaShrot_RetentionRule, *Named.BakaShrot_RetentionRule, *Matched.BakaShrot_RetentionRule - - ForEach Rules() - Select Rules()\Kind - Case #BakaShrot_Retention_Id - If Rules()\TopicId = TopicId - ProcedureReturn Rules()\MaxAgeMs - EndIf - Case #BakaShrot_Retention_Name - If Not *Named And Name <> "" And LCase(Rules()\Ref) = LCase(Name) - *Named = @Rules() - EndIf - Case #BakaShrot_Retention_Pattern - If Not *Matched And Name <> "" And BakaShrot_GlobMatch(Rules()\Ref, Name) - *Matched = @Rules() - EndIf - Case #BakaShrot_Retention_Default - *Default = @Rules() - EndSelect - Next - - If *Named - ProcedureReturn *Named\MaxAgeMs - ElseIf *Matched - ProcedureReturn *Matched\MaxAgeMs - ElseIf *Default - ProcedureReturn *Default\MaxAgeMs - EndIf - ProcedureReturn 0 -EndProcedure - - -; Reads a names section into Ids() (LCase(name) -> id) and Names() (Str(id) -; -> name). A line is a name, its id given by AssignConfigId() once the -; pinned ones are known (the database's for it, else a free one), or -; "name = id" to pin it. Kind is "topic" or "node", for the errors. -; The file must be open with OpenConfigPreferences(), see why there. -; 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(), Map KnownIds.i(), Map KnownUsed.i()) - Protected Name.s, Value.s, Id.i - Protected NewList Unpinned.s() - - If Not PreferenceGroup(Section) Or Not ExaminePreferenceKeys() - ProcedureReturn #True - EndIf - - 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 - If FindMapElement(Ids(), LCase(Name)) - BakaShrot_ConfigError = "[" + Section + "] " + Kind + " '" + Name + "' is given twice" - ProcedureReturn #False - EndIf - If Value = "" - ; Its id once every pinned one is known, -1 until then. - Ids(LCase(Name)) = -1 - AddElement(Unpinned()) : Unpinned() = Name - Continue - EndIf - Id = BakaShrot_RefToId(Value) - If Id < 0 - BakaShrot_ConfigError = "[" + Section + "] " + Name + " = '" + Value + "' isn't an id, 0-" + Str(#BakaShrot_MaxId) + " (or leave it out, the server gives it one)" - 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 - - ForEach Unpinned() - DeleteMapElement(Ids(), LCase(Unpinned())) - If AssignConfigId(Unpinned(), Ids(), Names(), KnownIds(), KnownUsed()) < 0 - BakaShrot_ConfigError = "[" + Section + "] no " + Kind + " id left for '" + Unpinned() + "'" - ProcedureReturn #False - EndIf - Next - - 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 - - -; Reads a client section's Node and DefaultTopic into *Client, in the -; current preference group. Where: "[BakaShrot.Client.]". -; Returns #False with BakaShrot_ConfigError set: Node missing or unknown, -; DefaultTopic unknown, or the old Identities still there. That one is -; refused rather than guessed at: a "Topic:Node" list could grant several -; nodes, and the topic was only ever the default one. -Procedure.i ParseClientIdentity(*Config.BakaShrot_CoreConfig, *Client.BakaShrot_ClientConfig, Where.s) - Protected Old.s, Pair.s, Id.i - - Old = Trim(ReadPreferenceString("Identities", #BakaShrot_Config_Missing)) - If Old <> #BakaShrot_Config_Missing - Pair = Trim(StringField(Old, 1, ";")) - If CountString(Old, ";") = 0 And CountString(Pair, ":") = 1 - BakaShrot_ConfigError = Where + " Identities isn't used any more (protocol 5): write Node = " + Trim(StringField(Pair, 2, ":")) + - " and DefaultTopic = " + Trim(StringField(Pair, 1, ":")) + " instead of Identities = " + Old - Else - BakaShrot_ConfigError = Where + " Identities isn't used any more (protocol 5): write the node it writes as in Node, and the topic of its pushes that don't name one in DefaultTopic, one section per node (a key may be in several)" - EndIf - ProcedureReturn #False - EndIf - - *Client\NodeText = Trim(ReadPreferenceString("Node", "")) - If *Client\NodeText = "" - BakaShrot_ConfigError = Where + " Node is missing: the node this client writes as, a name or an id" - ProcedureReturn #False - EndIf - Id = DeclareConfigNode(*Config, *Client\NodeText) - If Id < 0 - BakaShrot_ConfigError = Where + " Node: '" + *Client\NodeText + "' isn't a node name or an id" - ProcedureReturn #False - EndIf - *Client\NodeId = Id - *Config\UsedNodeIds(Str(Id)) = #True - - *Client\DefaultTopicId = -1 - *Client\DefaultTopicText = ReadPreferenceString("DefaultTopic", #BakaShrot_Config_Missing) - If *Client\DefaultTopicText <> #BakaShrot_Config_Missing And Trim(*Client\DefaultTopicText) <> "" - *Client\DefaultTopicText = Trim(*Client\DefaultTopicText) - Id = ResolveConfigTopic(*Config, *Client\DefaultTopicText) - If Id < 0 - BakaShrot_ConfigError = Where + " DefaultTopic: unknown topic '" + *Client\DefaultTopicText + "', not an id nor in [BakaShrot.Topics]" - ProcedureReturn #False - EndIf - *Client\DefaultTopicId = Id - *Config\UsedTopicIds(Str(Id)) = #True - EndIf - - ProcedureReturn #True -EndProcedure - - -; Returns the name of the [BakaShrot.Client.] section with this Node -; and PublicKey in its PublicKeys, or "" if none has. -; Not thread-safe, it moves *Config\Clients()' current element. -Procedure.s FindClientName(*Config.BakaShrot_CoreConfig, PublicKey.s, NodeId.i) - ForEach *Config\Clients() - If *Config\Clients()\NodeId = NodeId - ForEach *Config\Clients()\PublicKeys() - If *Config\Clients()\PublicKeys() = PublicKey - ProcedureReturn MapKey(*Config\Clients()) - EndIf - Next - EndIf - Next - - ProcedureReturn "" -EndProcedure - - -; Returns the name of the [BakaShrot.Peer.] section with exactly this -; public key and node, or "" if none has. -; Not thread-safe, it moves *Config\Peers()' current element. -Procedure.s FindPeerName(*Config.BakaShrot_CoreConfig, PublicKey.s, NodeId.i) - ForEach *Config\Peers() - If *Config\Peers()\PublicKey = PublicKey And *Config\Peers()\NodeId = NodeId - ProcedureReturn MapKey(*Config\Peers()) - EndIf - Next - - ProcedureReturn "" -EndProcedure - - -Procedure FreeConfig(*Config.BakaShrot_CoreConfig) - FreeStructure(*Config) -EndProcedure - - -; Where OpenConfigPreferences() put its copy, "" when it opened the file. -Global BakaShrot_ConfigCopyPath.s - -; OpenPreferences(IniFilePath), through a copy with CRLF line endings when -; the file has LF ones: there, the Preferences library takes the line after -; a key without "=" for its value, a section header too ("logs" then -; "[BakaShrot.Server]" loses that whole section), and names are listed -; without "=". The copy goes in the temporary folder, CloseConfigPreferences() -; deletes it. Returns OpenPreferences()' result. -Procedure.i OpenConfigPreferences(IniFilePath.s) - Protected FileId.i, Format.i, HadBom.i, Size.q, *Data, Text.s, Copy.s, Opened.i - - BakaShrot_ConfigCopyPath = "" - FileId = ReadFile(#PB_Any, IniFilePath) - If Not FileId - ProcedureReturn #False - EndIf - Format = ReadStringFormat(FileId) - HadBom = Bool(Format <> #PB_Ascii) - If Not HadBom - Format = #PB_UTF8 - EndIf - Size = Lof(FileId) - Loc(FileId) - *Data = AllocateMemory(Size + 2) - If Not *Data - CloseFile(FileId) - ProcedureReturn #False - EndIf - ReadData(FileId, *Data, Size) - CloseFile(FileId) - Text = PeekS(*Data, Size, Format | #PB_ByteLength) - FreeMemory(*Data) - - If Not FindString(ReplaceString(Text, #CRLF$, ""), #LF$) - ProcedureReturn OpenPreferences(IniFilePath) - EndIf - - Text = ReplaceString(ReplaceString(Text, #CRLF$, #LF$), #LF$, #CRLF$) - Copy = GetTemporaryDirectory() + "BakaShrot-config-" + Str(Date()) + "-" + Str(Random(999999)) + ".ini" - FileId = CreateFile(#PB_Any, Copy) - If Not FileId - ProcedureReturn #False - EndIf - If HadBom - WriteStringFormat(FileId, Format) - EndIf - WriteString(FileId, Text, Format) - CloseFile(FileId) - - Opened = OpenPreferences(Copy) - If Opened - BakaShrot_ConfigCopyPath = Copy - Else - DeleteFile(Copy) - EndIf - ProcedureReturn Opened -EndProcedure - -; ClosePreferences(), and deletes OpenConfigPreferences()' copy if it made one. -Procedure CloseConfigPreferences() - ClosePreferences() - If BakaShrot_ConfigCopyPath <> "" - DeleteFile(BakaShrot_ConfigCopyPath) - BakaShrot_ConfigCopyPath = "" - EndIf -EndProcedure - - -; [BakaShrot.Server] DatabasePath of IniFilePath, "" if it can't be opened: -; where the root reads the names it already has from, before LoadConfig(). -Procedure.s ReadConfigDatabasePath(IniFilePath.s) - Protected Path.s - - If OpenConfigPreferences(IniFilePath) - PreferenceGroup("BakaShrot.Server") - Path = ReadPreferenceString("DatabasePath", #BakaShrot_Config_DefaultDatabasePath) - CloseConfigPreferences() - EndIf - ProcedureReturn Path -EndProcedure - - -; Loads IniFilePath. Returns 0 on failure, with the reason in BakaShrot_ConfigError. -; *Known: the names the database already has, so the ones listed without an -; id keep theirs (0: none, a new database). -Procedure.Ptr_BakaShrot_CoreConfig LoadConfig(IniFilePath.s, *Known.BakaShrot_KnownNames = 0) - 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 - Protected NoneKnown.BakaShrot_KnownNames - - BakaShrot_ConfigError = "" - If Not *Known - *Known = @NoneKnown - EndIf - *BakaShrot_ConfigKnown = *Known - - If Not OpenConfigPreferences(IniFilePath) - BakaShrot_ConfigError = "can't open '" + IniFilePath + "'" - ProcedureReturn 0 - EndIf - - *Config = AllocateStructure(BakaShrot_CoreConfig) - If Not *Config - CloseConfigPreferences() - 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(), *Known\TopicIds(), *Known\TopicUsed()) Or - Not ParseNameSection("BakaShrot.Nodes", "node", *Config\NodeIds(), *Config\NodeNames(), *Known\NodeIds(), *Known\NodeUsed()) - Goto LoadFailed - EndIf - - PreferenceGroup("BakaShrot") - *Config\PrivateKey = ReadPreferenceString("PrivateKey", "") - ; Topic (TopicId) isn't read any more: a server authenticates by node. - *Config\NodeText = Trim(ReadConfigKey("Node", "NodeId", "0")) - Id = DeclareConfigNode(*Config, *Config\NodeText) - If Id < 0 - BakaShrot_ConfigError = "[BakaShrot] Node: '" + *Config\NodeText + "' isn't a node name or an id" - Goto LoadFailed - EndIf - *Config\NodeId = Id - *Config\UsedNodeIds(Str(*Config\NodeId)) = #True - - ; Every [BakaShrot.Peer.] and [BakaShrot.Client.], found - ; dynamically so adding one never needs a second "list of names" kept in - ; sync by hand. Read once the walk is done: PreferenceGroup() inside it - ; would lose the walk's place. - If ExaminePreferenceGroups() - While NextPreferenceGroup() - GroupName = PreferenceGroupName() - If Left(GroupName, Len("BakaShrot.Peer.")) = "BakaShrot.Peer." And Len(GroupName) > Len("BakaShrot.Peer.") - AddElement(PeerNames()) - PeerNames() = Mid(GroupName, Len("BakaShrot.Peer.") + 1) - EndIf - If Left(GroupName, Len("BakaShrot.Client.")) = "BakaShrot.Client." And Len(GroupName) > Len("BakaShrot.Client.") - AddElement(ClientNames()) - ClientNames() = Mid(GroupName, Len("BakaShrot.Client.") + 1) - EndIf - Wend - EndIf - - ; The nodes the peer and client sections define are named before any - ; node list (SendNodes, AcceptNodes) can refer to them. A bad one is - ; reported when its section is read below. - ForEach PeerNames() - PreferenceGroup("BakaShrot.Peer." + PeerNames()) - DeclareConfigNode(*Config, Trim(ReadConfigKey("Node", "NodeId", "0"))) - Next - ForEach ClientNames() - PreferenceGroup("BakaShrot.Client." + ClientNames()) - Text = Trim(ReadPreferenceString("Node", "")) - If Text <> "" - DeclareConfigNode(*Config, Text) - EndIf - Next - - ForEach *Config\TopicNames() - *Config\UsedTopicIds(MapKey(*Config\TopicNames())) = #True - Next - ForEach *Config\NodeNames() - *Config\UsedNodeIds(MapKey(*Config\NodeNames())) = #True - Next - - 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\RetentionInterval = ReadPreferenceLong("RetentionInterval", #BakaShrot_Config_DefaultRetentionInterval) - If *Config\Server\RetentionInterval < 1 - BakaShrot_ConfigError = "[BakaShrot.Server] RetentionInterval must be 1 second or more" - Goto LoadFailed - EndIf - *Config\Server\MaxAttachmentSizeText = Trim(ReadPreferenceString("MaxAttachmentSize", #BakaShrot_Config_DefaultMaxAttachmentSize)) - *Config\Server\MaxAttachmentSize = ParseConfigSize(*Config\Server\MaxAttachmentSizeText) - If *Config\Server\MaxAttachmentSize < 0 Or *Config\Server\MaxAttachmentSize > #BakaShrot_MaxAttachmentSize - BakaShrot_ConfigError = "[BakaShrot.Server] MaxAttachmentSize = '" + *Config\Server\MaxAttachmentSizeText + "' isn't a size up to 1T: bytes, or a number with K, M, G or T, like 500M (0: no attachments)" - Goto LoadFailed - EndIf - *Config\Server\UploadTimeout = ReadPreferenceLong("UploadTimeout", #BakaShrot_Config_DefaultUploadTimeout) - If *Config\Server\UploadTimeout < 10 - BakaShrot_ConfigError = "[BakaShrot.Server] UploadTimeout must be 10 seconds or more" - Goto LoadFailed - EndIf - *Config\Server\Synchronous = UCase(Trim(ReadPreferenceString("Synchronous", #BakaShrot_Config_DefaultSynchronous))) - ; An If chain, not a Select: a Goto out of a Select corrupts the stack - ; with 5.73's ASM backend (it keeps the value there). - If *Config\Server\Synchronous = "OFF" - BakaShrot_ConfigError = "[BakaShrot.Server] Synchronous = OFF isn't allowed: a power loss could corrupt the database. FULL, or NORMAL to only risk the last second of messages" - Goto LoadFailed - ElseIf *Config\Server\Synchronous = "EXTRA" - BakaShrot_ConfigError = "[BakaShrot.Server] Synchronous = EXTRA does nothing more than FULL in WAL mode: write FULL" - Goto LoadFailed - ElseIf *Config\Server\Synchronous <> "FULL" And *Config\Server\Synchronous <> "NORMAL" - BakaShrot_ConfigError = "[BakaShrot.Server] Synchronous = '" + *Config\Server\Synchronous + "' isn't FULL or NORMAL" - Goto LoadFailed - EndIf - *Config\Server\ReplicatingTopicsText = ReadConfigKey("ReplicatingTopics", "ReplicatingTopicIds", "") - If Not ParseTopicSet(*Config, *Config\Server\ReplicatingTopicsText, @*Config\Server\ReplicatingTopics, "[BakaShrot.Server] ReplicatingTopics") - Goto LoadFailed - EndIf - - If Not ParseRetentionSection(*Config) - Goto LoadFailed - 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", "") - ; Topic (TopicId) isn't read any more: a peer authenticates by node. - \NodeText = Trim(ReadConfigKey("Node", "NodeId", "0")) - Id = DeclareConfigNode(*Config, \NodeText) - If Id < 0 - BakaShrot_ConfigError = "[BakaShrot.Peer." + PeerName + "] Node: '" + \NodeText + "' isn't a node name or an id" - Failed = #True : Break - EndIf - \NodeId = Id - *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\All = #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()) - If Not ParseClientIdentity(*Config, @*Config\Clients(), "[BakaShrot.Client." + ClientName + "]") - 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 its default topic, nothing without one. - \PushTopicsText = ReadPreferenceString("PushTopics", #BakaShrot_Config_Missing) - \ReadTopicsText = ReadPreferenceString("ReadTopics", #BakaShrot_Config_Missing) - If \PushTopicsText = #BakaShrot_Config_Missing - If \DefaultTopicId >= 0 - \PushTopics\Ids(Str(\DefaultTopicId)) = #True - EndIf - ElseIf Not ParseTopicSet(*Config, \PushTopicsText, @\PushTopics, "[BakaShrot.Client." + ClientName + "] PushTopics") - Failed = #True : Break - EndIf - If \ReadTopicsText = #BakaShrot_Config_Missing - If \DefaultTopicId >= 0 - \ReadTopics\Ids(Str(\DefaultTopicId)) = #True - EndIf - ElseIf Not ParseTopicSet(*Config, \ReadTopicsText, @\ReadTopics, "[BakaShrot.Client." + ClientName + "] ReadTopics") - Failed = #True : Break - EndIf - EndWith - Next - If Failed - Goto LoadFailed - EndIf - - CloseConfigPreferences() - ProcedureReturn *Config - - LoadFailed: - CloseConfigPreferences() - 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("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) - WritePreferenceLong("RetentionInterval", *Config\Server\RetentionInterval) - WritePreferenceString("MaxAttachmentSize", *Config\Server\MaxAttachmentSizeText) - WritePreferenceLong("UploadTimeout", *Config\Server\UploadTimeout) - WritePreferenceString("Synchronous", *Config\Server\Synchronous) - - 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 - - If ListSize(*Config\Retention()) - PreferenceGroup("BakaShrot.Retention") - ForEach *Config\Retention() - WritePreferenceString(*Config\Retention()\Ref, *Config\Retention()\AgeText) - Next - EndIf - - ForEach *Config\Peers() - PreferenceGroup("BakaShrot.Peer." + MapKey(*Config\Peers())) - WritePreferenceString("Host", *Config\Peers()\Host) - WritePreferenceLong("Port", *Config\Peers()\Port) - 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("Node", *Config\Clients()\NodeText) - WriteConfigText("DefaultTopic", *Config\Clients()\DefaultTopicText) - 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 "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 - Debug " Node: " + Str(*Config\Clients()\NodeId) + ", DefaultTopic: " + Str(*Config\Clients()\DefaultTopicId) - Next - - SaveConfig("schema_out.ini", *Config) - - FreeConfig(*Config) - Else - Debug "Failed to load schema.ini: " + BakaShrot_ConfigError - EndIf - -CompilerEndIf diff --git a/Server/Config/Config.pbi.cfg b/Server/Config/Config.pbi.cfg deleted file mode 100644 index 943c0db..0000000 --- a/Server/Config/Config.pbi.cfg +++ /dev/null @@ -1,8 +0,0 @@ -IDE Options = PureBasic 6.41 beta 2 (Windows - x64) -CursorPosition = 135 -Folding = -- -EnableXP -DPIAware -CompileSourceDirectory -EnableCompileCount = 1 -EnableBuildCount = 0 diff --git a/Server/Config/schema.ini b/Server/Config/schema.ini deleted file mode 100644 index 6d38e92..0000000 --- a/Server/Config/schema.ini +++ /dev/null @@ -1,218 +0,0 @@ -; BakaShrot server config file. -; Section names are literal strings as far as PureBasic's Preferences -; library is concerned — the dots below are just part of the name. -; -; Topics and nodes: each has an id (0-65535) on this server, and can have a -; name. Topics are named in [BakaShrot.Topics]; nodes by the sections that -; define them ([BakaShrot] Node, a peer's, a client's), [BakaShrot.Nodes] -; only names the others. The server gives every name its id, and keeps it. -; Names are what's shared between servers: replication sends them, and -; each server stores the messages under its own ids for them ("logs" can be -; 1 here and 200 on a peer). -; ONLY WHAT'S NAMED ON BOTH SERVERS REPLICATES: a topic or node without a -; name, or whose name the other server doesn't have, is dropped. Unnamed -; ones still work locally, by id. -; Names: 1-64 of A-Z a-z 0-9 _ . -, not only digits, case doesn't matter. -; The server's "names" command and the BakaShrotList tool list them all. -; -; Topic, Node and ReplicatingTopics were TopicId, NodeId and -; ReplicatingTopicIds before: the old names are still read. -; -; Everywhere below, a topic or node can be written as a name or an id. -; Topic lists (and a peer's node lists): names and ids separated by ";", -; ranges of ids (100-150), wildcards like file names (sensors.*, kitchen-??: -; * any characters, ? one, they only match names), or * for every one. -; In a peer's AcceptTopics / AcceptNodes, * and wildcards also take names -; this server doesn't have: they get an id here by themselves, the highest -; free one counting down from 65535 (see them with the "names" command). - -[BakaShrot] -; Config shared by every type of config. - -; This node's Ed25519 private key (Base64), from BakaShrotGenerateKeyPairs.exe. It proves who -; this server is: clients seal their Hello for its public key and check -; that it signed the handshake, so they need that public key (client.ini's -; ServerPublicKey, peers' PublicKey below in THEIR own config). The server -; logs it when it starts. See Commons/Networking/Connections.pbi. -PrivateKey = - -; The node this server authenticates as when it links to its peers, a name -; or an id. Its peers must register it under the same name: a client -; section with this Node and this server's public key. (A Topic left here -; from before protocol 5 is ignored.) -Node = - - -[BakaShrot.Topics] -; One topic name per line. This server gives each its id: the one its -; database already has for it, or the lowest free one for a new one, so the -; order doesn't matter and they keep their ids. -; "name = id" pins one instead (configs from before work as they are). Once -; a name has messages, its id can't change: the server refuses to start if -; a pin moves it, and says which id to use. -; logs -; sensors - - -[BakaShrot.Nodes] -; Optional. The nodes [BakaShrot] Node, the peers' and the clients' Node -; define are named already. List the others this server should know by name -; up front, like topics; peers add the ones they send as they come -; (AcceptNodes, below). -; kitchen - - -[BakaShrot.Retention] -; How long this server keeps each topic's messages, counted from when they -; were pushed (to whichever server they were first pushed to). Past that, -; they may be deleted: checked every RetentionInterval seconds. Each server -; has its own: a peer keeps its copies as long as its own config says. -; One line per topic: name or id = age, a pattern (sensors.*), or * for -; every topic not listed. A topic takes its id's line, else its name's, -; else the first pattern matching it, else *'s. -; Ages: numbers with a unit, s m h d w, added up (1d12h), or forever. -; Without any line, everything is kept forever. -; Deleting doesn't shrink the file, SQLite reuses the space for new -; messages; the "vacuum" console command gives it back to the disk. -; logs = 30d -; sensors.* = 12h -; * = 365d - - -[BakaShrot.Server] -; IPV4 that the server will be bound to. -Host = - -; Used port. -Port = - -; The topics replicated with every peer that doesn't say otherwise -; (SendTopics, AcceptTopics below). -; Format: logs;0;100-150;... or * for every topic. -ReplicatingTopics = - -; Amount of threads used for networking-related tasks. -NetThreadPoolSize = 4 - -; SQLite database file holding the messages. -DatabasePath = ./test.sqlite - -; Seconds to wait before connecting to a peer again, after failing to -; connect or losing the connection. -PeerRetryDelay = 10 - -; Seconds between two check-ins with a linked peer, where it's sent the -; messages it's missing. -PeerSyncInterval = 5 - -; Most messages sent to a peer per packet when it's missing some, 1-10000. -; A batch is also cut short at about 64 KB, a bigger message goes alone. -PeerBatchSize = 100 - -; Seconds between two passes deleting the messages past their topic's age -; ([BakaShrot.Retention] above), and the attachments' leftovers. -RetentionInterval = 60 - -; Biggest attachment this server takes (one per message, see -; Design/Attachments.md): pushed to it, or replicated (a bigger one's message -; is kept, its attachment isn't). Bytes, or K M G T (1024-based). 0: none. -MaxAttachmentSize = 1G - -; Seconds a client may take to upload an attachment and push its message, -; after which the upload is deleted. -UploadTimeout = 3600 - -; How hard the database makes sure a push is on disk before answering it. -; FULL (default) every commit is flushed to disk: a message the server -; acknowledged survives a power loss or an OS crash. -; NORMAL flushed about once a second only (at the checkpoints): faster -; (twice the pushes under full load, measured), but a power loss -; or an OS crash loses the last second or so of acknowledged -; messages, and their ids are handed out again, which peers that -; already got them can't tell (Design/ReplicationIssues.md #1). -; A crash of the server alone loses nothing either way. -; The cost of FULL is the disk's flush time, once per group of pushes: well -; under a millisecond on a server SSD, ~10 ms on a hard disk, which then -; caps one client pushing one message at a time to ~100/s. -; See Design/StorageConcurrency.md for the numbers. -Synchronous = FULL - - -; One [BakaShrot.Peer.] section per peer this node talks to. -; is only a key for this file; it is never sent on the wire. -[BakaShrot.Peer.example] -; Remote address of the peer. Can be a domain name, IPV4 or IPV6. -Host = - -; Remote port of the peer (0-65535). -Port = - -; The server links to every peer on start, and retries every PeerRetryDelay. -; The peer must register this server in one of its [BakaShrot.Client.]. -; The link only goes through if the peer proves it holds the private key -; of PublicKey below, and it's encrypted. - -; The peer's node, a name or an id: the one in its own [BakaShrot] Node. -; It authenticates as it when it links to here. -Node = - -; The topics sent to this peer (if it takes them), and the topics taken -; from it. Both default to ReplicatingTopics. -; SendTopics = logs;sensors.* -; AcceptTopics = logs;sensors.* - -; The nodes whose messages are sent to this peer (default: every one), and -; the nodes whose messages are taken from it (default: every one, the names -; this server doesn't have yet are added as they come). AcceptNodes = -; kitchen-*;garage only takes those, named here or not. -; SendNodes = * -; AcceptNodes = kitchen-*;garage - -; This peer's Ed25519 public key (Base64), required: the link's Hello is -; sealed for it, and the peer must sign the handshake with its private key. -; It's also the key the peer authenticates with when it links to here. -PublicKey = - - -; One [BakaShrot.Client.] section per client allowed to connect. -; is only a key for this file; it is never sent on the wire. -[BakaShrot.Client.example] -; Ed25519 public keys (Base64) this client is allowed to authenticate with. -; Format: Key;Key;... -PublicKeys = - -; The node this client writes as, a name or an id, required. Every message -; it pushes is stored under it, so the server decides which node each key -; writes as, and no client can push as another's node (or as a peer's). -; Its client.ini's Node must say the same. A key that writes as several -; nodes is listed in a section per node. -; ONE SERVER PER NODE: give a node a client section on the one server it -; pushes to, the others get its messages by replication. Two servers taking -; pushes for the same node end up with different messages under the same -; ids, which nothing detects (Design/ReplicationIssues.md #1). To read from -; another server, give the client another node there (or no write access: -; AllowWrite = 0). -Node = - -; Where its pushes go when they don't name a topic, a name or an id. -; Optional: without it, every push must name its topic. Only a default, it -; may push to any topic in PushTopics. -; DefaultTopic = logs - -; (Identities, the Topic:Node pairs before protocol 5, isn't read any more: -; the server refuses to start with it, saying what to write instead.) - -; The topics it may push to (always under its own node), and the topics it -; may read the latest messages of. Both default to its DefaultTopic, -; nothing without one; empty allows none. -; PushTopics = logs;sensors -; ReadTopics = * - -; What this client may do once authenticated, 1 to allow, 0 to deny. -; Read: GetLatestMessage. Write: PushMessage. -; Query: raw read-only SQL, which can read every topic's data, whatever -; ReadTopics says. The "messages" view has the names: -; SELECT * FROM messages WHERE topic = 'logs' AND node = 'kitchen' -AllowRead = 1 -AllowWrite = 1 -AllowQuery = 0 diff --git a/Server/Config/schema_out.ini b/Server/Config/schema_out.ini deleted file mode 100644 index ed0d33c..0000000 --- a/Server/Config/schema_out.ini +++ /dev/null @@ -1,14 +0,0 @@ - -[BakaShrot] -PrivateKey = -TopicId = 0 -NodeId = 0 -[BakaShrot.Server] -Host = -Port = 0 -ReplicatingTopicIds = -[BakaShrot.Peer.example] -Host = -Port = 0 -TopicId = 0 -NodeId = 0 diff --git a/Server/Networking/Networking.pbi b/Server/Networking/Networking.pbi deleted file mode 100644 index a0d9847..0000000 --- a/Server/Networking/Networking.pbi +++ /dev/null @@ -1,1762 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: Networking.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; BakaShrot Server Networking -; -; Threaded TCP server, one thread per client: -; - The listener thread is the only one calling NetworkServerEvent(), -; holding *Server\Mutex, which client threads hold to close a connection. -; On connect it starts a thread for the client, on data it adds what it -; received to that client's inbox, on disconnect it flags the client. -; Either way it then sets the client's Signal to wake its thread up. -; With nothing to do, it sleeps in select() on every socket (see -; Commons/Networking/SocketWait.pbi). -; - Each client thread runs the handshake (see Connections.pbi) by taking -; packets out of its inbox, sleeping on its Signal while it's empty. -; Anything out of order or unexpected aborts the connection. -; It opens the client's sealed Hello with this server's key, proves it -; holds it, and sets up the connection's cipher: every packet after the -; ChallengeRequest is encrypted, and decrypted by the client's thread. -; -; Once authenticated, a client's thread answers its requests one at a time -; until it disconnects: PushMessage, GetLatestMessage, GetMessages, -; QueryRequest, ResolveName and ListNames, UploadStart, UploadChunk and -; GetAttachment (Design/Attachments.md), each one only if its -; [BakaShrot.Client.] allows it (AllowWrite and PushTopics, AllowRead -; and ReadTopics, AllowQuery), and for -; peers, SyncStateRequest and ReplicateMessages, then MissingAttachmentsRequest -; and ReplicateAttachmentChunk, refused for regular clients, -; within the peer's AcceptTopics and AcceptNodes. Any other packet aborts it. -; -; Topics and nodes come by name or id (Commons/Networking/Names.pbi), and -; are resolved to this server's ids by Storage/Names.pbi. -; -; Each client thread opens its own database connection once its client is -; authenticated, and closes it when it ends. See the top of Storage/Storage.pbi. -; -; Logs with PrintN(), so the program must have a console open. -; Must be compiled with the thread-safe option enabled. -; ============================================================================ - -CompilerIf Not #PB_Compiler_Thread - CompilerError "Networking.pbi needs the thread-safe option (Compiler Options > Create threadsafe executable)." -CompilerEndIf - -XIncludeFile "../../Commons/Networking/Connections.pbi" -XIncludeFile "../../Commons/Networking/SocketWait.pbi" -XIncludeFile "../../Commons/Threading/Signal.pbi" -XIncludeFile "../Config/Config.pbi" -XIncludeFile "../Storage/Storage.pbi" -XIncludeFile "../Storage/Names.pbi" - - -#BakaShrot_Net_ReceiveBufferSize = 65536 - -; How long a client gets to send each handshake packet. -#BakaShrot_Net_HandshakeTimeout = 10000 - -; Logs every push, read and query. Off: PrintN() costs ~0.4 ms per line and -; serializes every thread behind it, which capped a server at ~2400 pushes/s -; (12000/s without it, see Design/StorageConcurrency.md). The storage logs a -; summary every 10 s instead. -#BakaShrot_Net_LogRequests = #False - - -Structure BakaShrot_NetServer - ServerId.i - ThreadId.i - *Config.BakaShrot_CoreConfig - - ; Every client thread opens its own connection to it, and so does every - ; raw query, read-only. - DatabasePath.s - - ; This server's identity, from [BakaShrot] PrivateKey: signs the - ; handshake, and opens the Hellos sealed for it. Read-only once started, - ; every client thread uses them. Wiped when it stops. - PrivateKey.a[#BakaShrot_Ed25519_PrivateKeySize] - PublicKey.a[#BakaShrot_Ed25519_PublicKeySize] - HelloKeys.BakaShrot_HelloKeys - - ; Set by BakaShrot_NetServer_Stop(), makes every thread return. - StopRequested.i - - ; Guards Clients(), every client's Inbox, Disconnected and Overflowed, - ; ActiveClientThreads and the use of *Config\Clients(). - Mutex.i - - ; Client threads that haven't finished yet. - ActiveClientThreads.i - - ; *BakaShrot_NetClient by Str(ClientId), for the listener to find them. - ; A client is removed when it disconnects or its thread closes it. - Map Clients.i() -EndStructure - - -Structure BakaShrot_NetClient - *Server.BakaShrot_NetServer - ClientId.i - - ; Filled by the listener thread, read by the client's thread. - Inbox.BakaShrot_Inbox - - ; Set by the listener thread. - Disconnected.i - Overflowed.i - - ; Set by the listener thread whenever it changed the above, or the - ; inbox. The client's thread sleeps on it while waiting for a packet. - ; Freed by the client's thread, once it's out of Clients(). - Signal.i - - ; Only used by the client's thread. - Metadata.BakaShrot_ConnectionMetadata - - ; Name of the [BakaShrot.Peer.] the client authenticated as, "" - ; for a regular client. Only peers may replicate. - PeerName.s - - ; From the [BakaShrot.Client.] the client authenticated as, copied - ; so this thread can look them up without the server's mutex. - Permissions.BakaShrot_ClientPermissions - PushTopics.BakaShrot_NameSet - ReadTopics.BakaShrot_NameSet - - ; From the [BakaShrot.Peer.], for peers only. - AcceptTopics.BakaShrot_NameSet - AcceptNodes.BakaShrot_NameSet - - ; [BakaShrot.Retention], for peers only: what they send that's already - ; past its max age isn't stored. A copy, lists aren't safe to walk from - ; several threads. - List Retention.BakaShrot_RetentionRule() - - ; This thread's own database connection, opened once authenticated. - DbId.i -EndStructure - - -; Waits for the next packet from *Client, for up to TimeoutMs, 0 waits forever. -; Decrypted once the connection's cipher is set up, outside the server's -; mutex. -; Returns the packet (free it with FreeMemory) with its size in *OutSize\i, -; or 0 if the client disconnected, sent an invalid frame, one that doesn't -; decrypt or too much data, timed out, or the server is stopping. The -; reason is logged. -Procedure.i BakaShrot_NetClient_WaitPacket(*Client.BakaShrot_NetClient, *OutSize.Integer, TimeoutMs.i) - Protected *Packet = 0, Result.i, Disconnected.i, Overflowed.i, StartTime.i - - StartTime = ElapsedMilliseconds() - - Repeat - LockMutex(*Client\Server\Mutex) - Disconnected = *Client\Disconnected - Overflowed = *Client\Overflowed - Result = BakaShrot_Inbox_TakePacket(@*Client\Inbox, @*Packet, *OutSize) - UnlockMutex(*Client\Server\Mutex) - - If Result = #BakaShrot_Inbox_Packet - *Packet = BakaShrot_OpenFrame(@*Client\Metadata\Cipher, *Packet, *OutSize\i, *OutSize) - If Not *Packet - PrintN("[Net] Client " + Str(*Client\ClientId) + " sent a packet that doesn't decrypt") - EndIf - ProcedureReturn *Packet - EndIf - - If Result = #BakaShrot_Inbox_Invalid - PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an invalid frame") - ProcedureReturn 0 - EndIf - - If Overflowed - PrintN("[Net] Client " + Str(*Client\ClientId) + " sent too much data") - ProcedureReturn 0 - EndIf - - If Disconnected - PrintN("[Net] Client " + Str(*Client\ClientId) + " disconnected") - ProcedureReturn 0 - EndIf - - If *Client\Server\StopRequested - PrintN("[Net] Client " + Str(*Client\ClientId) + " dropped, the server is stopping") - ProcedureReturn 0 - EndIf - - If TimeoutMs > 0 And ElapsedMilliseconds() - StartTime > TimeoutMs - PrintN("[Net] Client " + Str(*Client\ClientId) + " timed out") - ProcedureReturn 0 - EndIf - - ; Sleeps until the listener got something for it, waking up at least - ; every 50 ms to check the timeout and StopRequested. - BakaShrot_Signal_Wait(*Client\Signal, 50) - ForEver -EndProcedure - - -; Runs the server's side of the handshake, see Connections.pbi. -; Returns #True once the client is authenticated, #False if it must be aborted. -Procedure.i BakaShrot_NetClient_Authenticate(*Client.BakaShrot_NetClient) - Protected *Server.BakaShrot_NetServer = *Client\Server - Protected *Packet, PacketSize.Integer, *View.MsgPackData, *Sealed - Protected *Hello.BakaShrot_AuthHello - Protected Request.BakaShrot_ChallengeRequest - Protected *Response.BakaShrot_ChallengeResponse - Protected Accepted.BakaShrot_AuthAccepted - Protected Proof.BakaShrot_ChallengeProof - Protected KeyPair.BakaShrot_SessionKeyPair - Protected NodeId.i, DefaultTopicId.i, PublicKey.s, ClientName.s, NodeRef.s - Protected NonceMatches.i, SignatureDecoded.i, Sent.i, CipherReady.i - - *Client\Metadata\Status = #BakaShrot_ConnectionStatus_New - CopyMemory(@*Server\PublicKey[0], @*Client\Metadata\ServerPublicKey[0], #BakaShrot_Ed25519_PublicKeySize) - - - ; 1. Hello, sealed for this server - *Sealed = BakaShrot_NetClient_WaitPacket(*Client, @PacketSize, #BakaShrot_Net_HandshakeTimeout) - If Not *Sealed - ProcedureReturn #False - EndIf - *Packet = BakaShrot_Session_OpenHello(@*Server\HelloKeys, *Sealed, PacketSize\i, @PacketSize) - FreeMemory(*Sealed) - If Not *Packet - PrintN("[Net] Client " + Str(*Client\ClientId) + " sent a hello that isn't sealed for this server (wrong ServerPublicKey?)") - ProcedureReturn #False - EndIf - - *Hello = 0 - *View = MsgPackWrapMsgBuffer(*Packet, PacketSize\i) - If *View - *Hello = BakaShrot_HelloPacket_Decode(*View) - MsgPackFree(*View, #False) - EndIf - FreeMemory(*Packet) - If Not *Hello - PrintN("[Net] Client " + Str(*Client\ClientId) + " didn't send a valid hello") - ProcedureReturn #False - EndIf - - NodeRef = *Hello\ClientNode - PublicKey = *Hello\ClientPubKeyB64 - CopyMemory(@*Hello\ClientSessionKey[0], @*Client\Metadata\ClientSessionKey[0], #BakaShrot_SessionKeySize) - FreeStructure(*Hello) - - NodeId = BakaShrot_Names_ResolveNode(NodeRef) - If NodeId < 0 - PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an unknown node '" + Left(NodeRef, 80) + "'") - ProcedureReturn #False - EndIf - - If Not DecodeKeyFromString(PublicKey, @*Client\Metadata\PublicKey[0], #BakaShrot_Ed25519_PublicKeySize) - PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an invalid public key") - ProcedureReturn #False - EndIf - - LockMutex(*Server\Mutex) - ClientName = FindClientName(*Server\Config, PublicKey, NodeId) - *Client\PeerName = FindPeerName(*Server\Config, PublicKey, NodeId) - DefaultTopicId = -1 - If ClientName <> "" And FindMapElement(*Server\Config\Clients(), ClientName) - DefaultTopicId = *Server\Config\Clients()\DefaultTopicId - *Client\Permissions\Read = *Server\Config\Clients()\Permissions\Read - *Client\Permissions\Write = *Server\Config\Clients()\Permissions\Write - *Client\Permissions\Query = *Server\Config\Clients()\Permissions\Query - CopyStructure(@*Server\Config\Clients()\PushTopics, @*Client\PushTopics, BakaShrot_NameSet) - CopyStructure(@*Server\Config\Clients()\ReadTopics, @*Client\ReadTopics, BakaShrot_NameSet) - EndIf - If *Client\PeerName <> "" And FindMapElement(*Server\Config\Peers(), *Client\PeerName) - CopyStructure(@*Server\Config\Peers()\AcceptTopics, @*Client\AcceptTopics, BakaShrot_NameSet) - CopyStructure(@*Server\Config\Peers()\AcceptNodes, @*Client\AcceptNodes, BakaShrot_NameSet) - CopyList(*Server\Config\Retention(), *Client\Retention()) - EndIf - UnlockMutex(*Server\Mutex) - If ClientName = "" - PrintN("[Net] Client " + Str(*Client\ClientId) + " isn't allowed to write as node " + BakaShrot_Names_NodeRef(NodeId) + " with its public key") - ProcedureReturn #False - EndIf - - *Client\Metadata\DefaultTopicId = DefaultTopicId - *Client\Metadata\NodeId = NodeId - - - ; 2. Challenge request, in plain text, signed by this server - If Not CryptRandomData(@*Client\Metadata\Challenge[0], #BakaShrot_ChallengeSize) - PrintN("[Net] Failed to generate a challenge for client " + Str(*Client\ClientId)) - ProcedureReturn #False - EndIf - If Not CryptRandomData(@*Client\Metadata\Nonce[0], #BakaShrot_NonceSize) - PrintN("[Net] Failed to generate a nonce for client " + Str(*Client\ClientId)) - ProcedureReturn #False - EndIf - - BakaShrot_Session_NewKeyPair(@KeyPair) - CopyMemory(@KeyPair\PublicKey[0], @*Client\Metadata\ServerSessionKey[0], #BakaShrot_SessionKeySize) - - BakaShrot_MakeHandshakeTranscript(@*Client\Metadata, #BakaShrot_TranscriptServerLabel, @Proof) - If Not BakaShrot_SignHandshake(@Proof, @*Server\PrivateKey[0]) - BakaShrot_Session_ClearKeyPair(@KeyPair) - PrintN("[Net] Failed to sign the handshake for client " + Str(*Client\ClientId)) - ProcedureReturn #False - EndIf - - ; This connection's keys, before anything else arrives: the client - ; encrypts everything after this. - CipherReady = BakaShrot_Session_StartServer(@*Client\Metadata\Cipher, @KeyPair, @*Client\Metadata\ClientSessionKey[0]) - If Not CipherReady - PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an unusable session key") - ProcedureReturn #False - EndIf - - Request\ChallengeB64 = EncodeKeyToString(@*Client\Metadata\Challenge[0], #BakaShrot_ChallengeSize) - CopyMemory(@*Client\Metadata\Nonce[0], @Request\Nonce[0], #BakaShrot_NonceSize) - CopyMemory(@*Client\Metadata\ServerSessionKey[0], @Request\ServerSessionKey[0], #BakaShrot_SessionKeySize) - CopyMemory(@Proof\Signature[0], @Request\ServerSignature[0], #BakaShrot_HandshakeSignatureSize) - - *Packet = BakaShrot_ChallengeRequestPacket_Encode(@Request, @PacketSize) - If Not *Packet - PrintN("[Net] Failed to encode the challenge request for client " + Str(*Client\ClientId)) - ProcedureReturn #False - EndIf - Sent = BakaShrot_SendPacket(*Client\ClientId, *Packet, PacketSize\i, 0) - FreeMemory(*Packet) - If Not Sent - PrintN("[Net] Failed to send the challenge request to client " + Str(*Client\ClientId)) - ProcedureReturn #False - EndIf - - *Client\Metadata\Status = #BakaShrot_ConnectionStatus_Challenged - - - ; 3. Challenge response, encrypted as everything from now on - *Packet = BakaShrot_NetClient_WaitPacket(*Client, @PacketSize, #BakaShrot_Net_HandshakeTimeout) - If Not *Packet - ProcedureReturn #False - EndIf - - *Response = 0 - *View = MsgPackWrapMsgBuffer(*Packet, PacketSize\i) - If *View - *Response = BakaShrot_ChallengeResponsePacket_Decode(*View) - MsgPackFree(*View, #False) - EndIf - FreeMemory(*Packet) - If Not *Response - PrintN("[Net] Client " + Str(*Client\ClientId) + " didn't send a valid challenge response") - ProcedureReturn #False - EndIf - - NonceMatches = CompareMemory(@*Response\Nonce[0], @*Client\Metadata\Nonce[0], #BakaShrot_NonceSize) - SignatureDecoded = DecodeKeyFromString(*Response\ChallengeResponseB64, @Proof\Signature[0], #BakaShrot_Ed25519_SignatureSize) - FreeStructure(*Response) - - If Not NonceMatches - PrintN("[Net] Client " + Str(*Client\ClientId) + " answered with the wrong nonce") - ProcedureReturn #False - EndIf - - If Not SignatureDecoded - PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an invalid signature") - ProcedureReturn #False - EndIf - - BakaShrot_MakeHandshakeTranscript(@*Client\Metadata, #BakaShrot_TranscriptClientLabel, @Proof) - If Not BakaShrot_VerifyHandshake(@Proof, @*Client\Metadata\PublicKey[0]) - PrintN("[Net] Client " + Str(*Client\ClientId) + " failed the challenge") - ProcedureReturn #False - EndIf - - - ; 4. Accepted - ; Big packets from now on, set before it hears it's accepted: the listener - ; may get its first request right after. - LockMutex(*Server\Mutex) - BakaShrot_Inbox_Lift(@*Client\Inbox) - UnlockMutex(*Server\Mutex) - - *Packet = BakaShrot_AuthAcceptedPacket_Encode(@Accepted, @PacketSize) - If Not *Packet - PrintN("[Net] Failed to encode the acceptance for client " + Str(*Client\ClientId)) - ProcedureReturn #False - EndIf - Sent = BakaShrot_SendPacket(*Client\ClientId, *Packet, PacketSize\i, @*Client\Metadata\Cipher) - FreeMemory(*Packet) - If Not Sent - PrintN("[Net] Failed to send the acceptance to client " + Str(*Client\ClientId)) - ProcedureReturn #False - EndIf - - *Client\Metadata\Status = #BakaShrot_ConnectionStatus_Authenticated - If *Client\PeerName = "" - PrintN("[Net] Client " + Str(*Client\ClientId) + " authenticated as '" + ClientName + "', node " + BakaShrot_Names_NodeRef(NodeId)) - Else - PrintN("[Net] Client " + Str(*Client\ClientId) + " authenticated as '" + ClientName + "', node " + BakaShrot_Names_NodeRef(NodeId) + ", peer '" + *Client\PeerName + "'") - EndIf - - ProcedureReturn #True -EndProcedure - - -; Encodes and sends a RequestRefused. -; Returns #False if it couldn't be sent, the client must then be aborted. -Procedure.i BakaShrot_NetClient_Refuse(*Client.BakaShrot_NetClient, Code.l, Reason.s) - Protected Refused.BakaShrot_RequestRefused - Protected *Packet, PacketSize.Integer, Sent.i - - PrintN("[Net] Refused a request from client " + Str(*Client\ClientId) + " (" + BakaShrot_ErrorName(Code) + "): " + Reason) - - Refused\Code = Code - Refused\Reason = Reason - *Packet = BakaShrot_RequestRefusedPacket_Encode(@Refused, @PacketSize) - If Not *Packet - ProcedureReturn #False - EndIf - Sent = BakaShrot_SendPacket(*Client\ClientId, *Packet, PacketSize\i, @*Client\Metadata\Cipher) - FreeMemory(*Packet) - - ProcedureReturn Sent -EndProcedure - - -; Stores the pushed message in the asked topic (its authenticated one if -; none) under the client's authenticated node, with the next message id for -; them, and answers with that id. JSON or not: SQLite flags it in is_json, -; nothing here looks inside it. -; Returns #False if the client must be aborted. -Procedure.i BakaShrot_NetClient_HandlePushMessage(*Client.BakaShrot_NetClient, *Packet, PacketSize.i) - Protected *View.MsgPackData, *Push.BakaShrot_PushMessage - Protected Pushed.BakaShrot_MessagePushed - Protected JsonData.s, TopicRef.s, TopicId.i, JsonSize.i, MessageId.q, StoreError.String, UploadId.q - Protected Blob.BakaShrot_StorageBlob - Protected *Answer, AnswerSize.Integer, Sent.i - - *Push = 0 - *View = MsgPackWrapMsgBuffer(*Packet, PacketSize) - If *View - *Push = BakaShrot_PushMessagePacket_Decode(*View) - MsgPackFree(*View, #False) - EndIf - If Not *Push - PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an invalid push") - ProcedureReturn #False - EndIf - JsonData = *Push\JsonData - TopicRef = *Push\Topic - UploadId = *Push\UploadId - FreeStructure(*Push) - - ; The node is the authenticated one, the client never sends it here. - If *Client\Metadata\Status <> #BakaShrot_ConnectionStatus_Authenticated - PrintN("[Net] Client " + Str(*Client\ClientId) + " pushed without being authenticated") - ProcedureReturn #False - EndIf - - If Not *Client\Permissions\Write - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to write") - EndIf - - If TopicRef = "" - TopicId = *Client\Metadata\DefaultTopicId - If TopicId < 0 - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NoDefaultTopic, "No default topic for this client (DefaultTopic in its server's config): name the topic") - EndIf - Else - TopicId = BakaShrot_Names_ResolveTopic(TopicRef) - If TopicId < 0 - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_UnknownName, "Unknown topic '" + Left(TopicRef, 80) + "'") - EndIf - EndIf - If Not NameSetHas(@*Client\PushTopics, TopicId, BakaShrot_Names_TopicName(TopicId)) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to push to topic '" + BakaShrot_Names_TopicRef(TopicId) + "'") - EndIf - - ; So it fits in every packet that carries it later, see Packets.pbi. - JsonSize = StringByteLength(JsonData, #PB_UTF8) - If JsonSize > #BakaShrot_MaxMessageSize - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_TooBig, "The message is too big: " + Str(JsonSize) + " bytes, at most " + Str(#BakaShrot_MaxMessageSize)) - EndIf - - ; A topic allowed by "*" may be new here, it needs its row for the - ; "messages" view. - If Not BakaShrot_Names_EnsureTopicId(TopicId, @StoreError) - PrintN("[Net] Failed to register topic " + Str(TopicId) + ": " + StoreError\s) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The message couldn't be stored") - EndIf - - ; Its attachment: one of this client's complete uploads, for that topic. - If UploadId - If Not GetStorageBlob(*Client\DbId, UploadId, @Blob) Or Blob\NodeId <> *Client\Metadata\NodeId - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotFound, "No such upload") - EndIf - If Blob\State <> #BakaShrot_Blob_Complete - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_InvalidRequest, "The upload isn't complete, or is attached already") - EndIf - If Blob\TopicId <> TopicId - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_InvalidRequest, "The upload is for topic '" + BakaShrot_Names_TopicRef(Blob\TopicId) + "'") - EndIf - EndIf - - MessageId = InsertNextMessage(TopicId, *Client\Metadata\NodeId, JsonData, @StoreError, UploadId) - If MessageId < 1 - PrintN("[Net] Failed to store a message from client " + Str(*Client\ClientId) + ": " + StoreError\s) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The message couldn't be stored") - EndIf - - Pushed\MessageId = MessageId - *Answer = BakaShrot_MessagePushedPacket_Encode(@Pushed, @AnswerSize) - If Not *Answer - ProcedureReturn #False - EndIf - Sent = BakaShrot_SendPacket(*Client\ClientId, *Answer, AnswerSize\i, @*Client\Metadata\Cipher) - FreeMemory(*Answer) - - CompilerIf #BakaShrot_Net_LogRequests - PrintN("[Net] Client " + Str(*Client\ClientId) + " pushed message " + Str(TopicId) + ":" + Str(*Client\Metadata\NodeId) + "#" + Str(MessageId)) - CompilerEndIf - ProcedureReturn Sent -EndProcedure - - -; Answers with the latest message of the asked topic/node. -; Refuses if the client may not read that topic, if either is unknown, or if -; there's no message. -; Returns #False if the client must be aborted. -Procedure.i BakaShrot_NetClient_HandleGetLatestMessage(*Client.BakaShrot_NetClient, *Packet, PacketSize.i) - Protected *View.MsgPackData, *Request.BakaShrot_GetLatestMessage - Protected Latest.BakaShrot_LatestMessage - Protected Message.BakaShrot_Message - Protected TopicId.i, NodeId.i, TopicRef.s, NodeRef.s - Protected *Answer, AnswerSize.Integer, Sent.i - - *Request = 0 - *View = MsgPackWrapMsgBuffer(*Packet, PacketSize) - If *View - *Request = BakaShrot_GetLatestMessagePacket_Decode(*View) - MsgPackFree(*View, #False) - EndIf - If Not *Request - PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an invalid latest message request") - ProcedureReturn #False - EndIf - TopicRef = *Request\Topic - NodeRef = *Request\Node - FreeStructure(*Request) - - If *Client\Metadata\Status <> #BakaShrot_ConnectionStatus_Authenticated - PrintN("[Net] Client " + Str(*Client\ClientId) + " asked for a message without being authenticated") - ProcedureReturn #False - EndIf - - If Not *Client\Permissions\Read - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to read") - EndIf - - TopicId = BakaShrot_Names_ResolveTopic(TopicRef) - If TopicId < 0 - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_UnknownName, "Unknown topic '" + Left(TopicRef, 80) + "'") - EndIf - If Not NameSetHas(@*Client\ReadTopics, TopicId, BakaShrot_Names_TopicName(TopicId)) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to read topic '" + BakaShrot_Names_TopicRef(TopicId) + "'") - EndIf - NodeId = BakaShrot_Names_ResolveNode(NodeRef) - If NodeId < 0 - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_UnknownName, "Unknown node '" + Left(NodeRef, 80) + "'") - EndIf - - If Not GetLatestMessage(*Client\DbId, TopicId, NodeId, @Message) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotFound, "No message for " + BakaShrot_Names_TopicRef(TopicId) + ":" + BakaShrot_Names_NodeRef(NodeId)) - EndIf - - Latest\TopicId = TopicId - Latest\NodeId = NodeId - Latest\TopicName = BakaShrot_Names_TopicRef(TopicId) - Latest\NodeName = BakaShrot_Names_NodeRef(NodeId) - Latest\MessageId = Message\MessageId - Latest\PushedAt = Message\PushedAt - Latest\JsonData = Message\JsonData - Latest\AttachmentSize = Message\AttachmentSize - Latest\AttachmentReady = Message\AttachmentReady - *Answer = BakaShrot_LatestMessagePacket_Encode(@Latest, @AnswerSize) - If Not *Answer - ProcedureReturn #False - EndIf - Sent = BakaShrot_SendPacket(*Client\ClientId, *Answer, AnswerSize\i, @*Client\Metadata\Cipher) - FreeMemory(*Answer) - - CompilerIf #BakaShrot_Net_LogRequests - PrintN("[Net] Client " + Str(*Client\ClientId) + " got message " + Str(TopicId) + ":" + Str(NodeId) + "#" + Str(Message\MessageId)) - CompilerEndIf - ProcedureReturn Sent -EndProcedure - - -; Answers with the messages of the asked topic/node after the asked id: as -; many as asked for that fit in about #BakaShrot_MessagesBatchBytes, a -; bigger one alone. None if there are no more, that isn't refused. -; Refuses if the client may not read that topic, or if either is unknown. -; Returns #False if the client must be aborted. -Procedure.i BakaShrot_NetClient_HandleGetMessages(*Client.BakaShrot_NetClient, *Packet, PacketSize.i) - Protected *View.MsgPackData, *Request.BakaShrot_GetMessages - Protected Answer.BakaShrot_Messages - Protected NewList Messages.BakaShrot_Message() - Protected TopicId.i, NodeId.i, TopicRef.s, NodeRef.s, AfterMessageId.q, Limit.i - Protected More.Integer, BatchSize.i, MessageSize.i - Protected *Answer, AnswerSize.Integer, Sent.i - - *Request = 0 - *View = MsgPackWrapMsgBuffer(*Packet, PacketSize) - If *View - *Request = BakaShrot_GetMessagesPacket_Decode(*View) - MsgPackFree(*View, #False) - EndIf - If Not *Request - PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an invalid messages request") - ProcedureReturn #False - EndIf - TopicRef = *Request\Topic - NodeRef = *Request\Node - AfterMessageId = *Request\AfterMessageId - Limit = *Request\Limit - FreeStructure(*Request) - - If *Client\Metadata\Status <> #BakaShrot_ConnectionStatus_Authenticated - PrintN("[Net] Client " + Str(*Client\ClientId) + " asked for messages without being authenticated") - ProcedureReturn #False - EndIf - - If Not *Client\Permissions\Read - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to read") - EndIf - - TopicId = BakaShrot_Names_ResolveTopic(TopicRef) - If TopicId < 0 - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_UnknownName, "Unknown topic '" + Left(TopicRef, 80) + "'") - EndIf - If Not NameSetHas(@*Client\ReadTopics, TopicId, BakaShrot_Names_TopicName(TopicId)) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to read topic '" + BakaShrot_Names_TopicRef(TopicId) + "'") - EndIf - NodeId = BakaShrot_Names_ResolveNode(NodeRef) - If NodeId < 0 - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_UnknownName, "Unknown node '" + Left(NodeRef, 80) + "'") - EndIf - - ; In characters, the bytes are counted below: never less than that. - If Not GetMessagesAfter(*Client\DbId, TopicId, NodeId, AfterMessageId, Limit, #BakaShrot_MessagesBatchBytes, Messages(), @More) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The messages couldn't be read") - EndIf - - ; As many as fit in #BakaShrot_MessagesBatchBytes, the rest is for the - ; next request. A bigger message goes alone, it always fits in a packet. - Answer\More = More\i - BatchSize = #BakaShrot_MessagesOverhead - ForEach Messages() - MessageSize = #BakaShrot_MessagesMessageOverhead + StringByteLength(Messages()\JsonData, #PB_UTF8) - If ListSize(Answer\Messages()) > 0 And (BatchSize + MessageSize > #BakaShrot_MessagesBatchBytes Or BatchSize + MessageSize > #BakaShrot_MaxPacketSize) - Answer\More = #True - Break - EndIf - BatchSize + MessageSize - - AddElement(Answer\Messages()) - Answer\Messages()\MessageId = Messages()\MessageId - Answer\Messages()\PushedAt = Messages()\PushedAt - Answer\Messages()\JsonData = Messages()\JsonData - Answer\Messages()\AttachmentSize = Messages()\AttachmentSize - Answer\Messages()\AttachmentReady = Messages()\AttachmentReady - Next - ClearList(Messages()) - - Answer\TopicId = TopicId - Answer\NodeId = NodeId - Answer\TopicName = BakaShrot_Names_TopicRef(TopicId) - Answer\NodeName = BakaShrot_Names_NodeRef(NodeId) - *Answer = BakaShrot_MessagesPacket_Encode(@Answer, @AnswerSize) - If Not *Answer - ProcedureReturn #False - EndIf - Sent = BakaShrot_SendPacket(*Client\ClientId, *Answer, AnswerSize\i, @*Client\Metadata\Cipher) - FreeMemory(*Answer) - - CompilerIf #BakaShrot_Net_LogRequests - PrintN("[Net] Client " + Str(*Client\ClientId) + " got " + Str(ListSize(Answer\Messages())) + " messages of " + Str(TopicId) + ":" + Str(NodeId) + " after #" + Str(AfterMessageId)) - CompilerEndIf - ProcedureReturn Sent -EndProcedure - - -; Runs a raw read-only SQL query and answers with its rows as JSON, see -; RunReadOnlyQuery() in Storage/Storage.pbi. -; Refuses clients not allowed to query, and results too big for one packet. -; Returns #False if the client must be aborted. -Procedure.i BakaShrot_NetClient_HandleQuery(*Client.BakaShrot_NetClient, *Packet, PacketSize.i) - Protected *View.MsgPackData, *Request.BakaShrot_QueryRequest - Protected Result.BakaShrot_QueryResult - Protected Sql.s, JsonResult.String, QueryError.String - Protected *Answer, AnswerSize.Integer, Sent.i - - *Request = 0 - *View = MsgPackWrapMsgBuffer(*Packet, PacketSize) - If *View - *Request = BakaShrot_QueryRequestPacket_Decode(*View) - MsgPackFree(*View, #False) - EndIf - If Not *Request - PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an invalid query") - ProcedureReturn #False - EndIf - Sql = *Request\Sql - FreeStructure(*Request) - - If Not *Client\Permissions\Query - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to query") - EndIf - - If Not RunReadOnlyQuery(*Client\Server\DatabasePath, Sql, @JsonResult, @QueryError) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_QueryFailed, "Query failed: " + QueryError\s) - EndIf - - ; Leaves room for the packet's own fields. - If StringByteLength(JsonResult\s, #PB_UTF8) > #BakaShrot_MaxPacketSize - 64 - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_TooBig, "The result is too big for one packet, add a LIMIT") - EndIf - - Result\JsonResult = JsonResult\s - *Answer = BakaShrot_QueryResultPacket_Encode(@Result, @AnswerSize) - If Not *Answer - ProcedureReturn #False - EndIf - Sent = BakaShrot_SendPacket(*Client\ClientId, *Answer, AnswerSize\i, @*Client\Metadata\Cipher) - FreeMemory(*Answer) - - CompilerIf #BakaShrot_Net_LogRequests - PrintN("[Net] Client " + Str(*Client\ClientId) + " ran a query, " + Str(AnswerSize\i) + " bytes of results") - CompilerEndIf - ProcedureReturn Sent -EndProcedure - - -; Answers with this server's id and name of a topic or node. -; Topics: only those the client may push to or read, unless it may query. -; Returns #False if the client must be aborted. -Procedure.i BakaShrot_NetClient_HandleResolveName(*Client.BakaShrot_NetClient, *Packet, PacketSize.i) - Protected *View.MsgPackData, *Request.BakaShrot_ResolveName - Protected Resolved.BakaShrot_NameResolved - Protected Kind.i, Ref.s, Id.i - Protected *Answer, AnswerSize.Integer, Sent.i - - *Request = 0 - *View = MsgPackWrapMsgBuffer(*Packet, PacketSize) - If *View - *Request = BakaShrot_ResolveNamePacket_Decode(*View) - MsgPackFree(*View, #False) - EndIf - If Not *Request - PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an invalid name request") - ProcedureReturn #False - EndIf - Kind = *Request\Kind - Ref = *Request\Ref - FreeStructure(*Request) - - If Kind = #BakaShrot_NameKind_Topic - Id = BakaShrot_Names_ResolveTopic(Ref) - If Id < 0 - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_UnknownName, "Unknown topic '" + Left(Ref, 80) + "'") - EndIf - If Not *Client\Permissions\Query And Not NameSetHas(@*Client\PushTopics, Id, BakaShrot_Names_TopicName(Id)) And Not NameSetHas(@*Client\ReadTopics, Id, BakaShrot_Names_TopicName(Id)) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_UnknownName, "Unknown topic '" + Left(Ref, 80) + "'") - EndIf - Resolved\Name = BakaShrot_Names_TopicName(Id) - Else - Id = BakaShrot_Names_ResolveNode(Ref) - If Id < 0 - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_UnknownName, "Unknown node '" + Left(Ref, 80) + "'") - EndIf - Resolved\Name = BakaShrot_Names_NodeName(Id) - EndIf - - Resolved\Kind = Kind - Resolved\Id = Id - *Answer = BakaShrot_NameResolvedPacket_Encode(@Resolved, @AnswerSize) - If Not *Answer - ProcedureReturn #False - EndIf - Sent = BakaShrot_SendPacket(*Client\ClientId, *Answer, AnswerSize\i, @*Client\Metadata\Cipher) - FreeMemory(*Answer) - - ProcedureReturn Sent -EndProcedure - - -; Lists every topic (those the client may push to or read, unless it may -; query) or node, with its id, name and origin, as many as fit in one packet. -; Returns #False if the client must be aborted. -Procedure.i BakaShrot_NetClient_HandleListNames(*Client.BakaShrot_NetClient, *Packet, PacketSize.i) - Protected *View.MsgPackData, *Request.BakaShrot_ListNames - Protected Answer.BakaShrot_NamesList, Visible.BakaShrot_NameSet - Protected NewList All.BakaShrot_NameEntry() - Protected Kind.i, Size.i, EntrySize.i - Protected *Answer, AnswerSize.Integer, Sent.i - - *Request = 0 - *View = MsgPackWrapMsgBuffer(*Packet, PacketSize) - If *View - *Request = BakaShrot_ListNamesPacket_Decode(*View) - MsgPackFree(*View, #False) - EndIf - If Not *Request - PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an invalid names list request") - ProcedureReturn #False - EndIf - Kind = *Request\Kind - FreeStructure(*Request) - - If Kind = #BakaShrot_NameKind_Topic And Not *Client\Permissions\Query - ; The topics it may push to or read. - Visible\All = Bool(*Client\PushTopics\All Or *Client\ReadTopics\All) - Visible\Known = Bool(*Client\PushTopics\Known Or *Client\ReadTopics\Known) - ForEach *Client\PushTopics\Ids() - Visible\Ids(MapKey(*Client\PushTopics\Ids())) = #True - Next - ForEach *Client\ReadTopics\Ids() - Visible\Ids(MapKey(*Client\ReadTopics\Ids())) = #True - Next - ForEach *Client\PushTopics\Patterns() - AddElement(Visible\Patterns()) : Visible\Patterns() = *Client\PushTopics\Patterns() - Next - ForEach *Client\ReadTopics\Patterns() - AddElement(Visible\Patterns()) : Visible\Patterns() = *Client\ReadTopics\Patterns() - Next - BakaShrot_Names_GetAll(Kind, All(), @Visible) - Else - BakaShrot_Names_GetAll(Kind, All()) - EndIf - - Answer\Kind = Kind - Size = #BakaShrot_NamesListOverhead - ForEach All() - EntrySize = #BakaShrot_NamesListEntryOverhead + StringByteLength(All()\Name, #PB_UTF8) + StringByteLength(All()\Origin, #PB_UTF8) - If Size + EntrySize > #BakaShrot_MaxPacketSize - Answer\Truncated = #True - Break - EndIf - Size + EntrySize - AddElement(Answer\Entries()) - Answer\Entries()\Id = All()\Id - Answer\Entries()\Name = All()\Name - Answer\Entries()\Origin = All()\Origin - Next - - *Answer = BakaShrot_NamesListPacket_Encode(@Answer, @AnswerSize) - If Not *Answer - ProcedureReturn #False - EndIf - Sent = BakaShrot_SendPacket(*Client\ClientId, *Answer, AnswerSize\i, @*Client\Metadata\Cipher) - FreeMemory(*Answer) - - ProcedureReturn Sent -EndProcedure - - -; Answers a peer with this server's sync state, see SyncStatePacket.pbi: -; every name it knows and takes from that peer (its AcceptTopics and -; AcceptNodes), their wildcards, and the highest message id it has for each -; topic/node of those. Unnamed ones don't replicate. -; Refuses regular clients. -; Returns #False if the client must be aborted. -Procedure.i BakaShrot_NetClient_HandleSyncStateRequest(*Client.BakaShrot_NetClient, *Packet, PacketSize.i) - Protected *View.MsgPackData, *Request.BakaShrot_SyncStateRequest - Protected State.BakaShrot_SyncState - Protected NewList AllPairs.BakaShrot_SyncPair() - Protected NewMap Topics.i(), NewMap Nodes.i() - Protected *Answer, AnswerSize.Integer, Sent.i - - *Request = 0 - *View = MsgPackWrapMsgBuffer(*Packet, PacketSize) - If *View - *Request = BakaShrot_SyncStateRequestPacket_Decode(*View) - MsgPackFree(*View, #False) - EndIf - If Not *Request - PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an invalid sync state request") - ProcedureReturn #False - EndIf - FreeStructure(*Request) - - If *Client\PeerName = "" - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Only peers can replicate") - EndIf - - If Not GetSyncState(*Client\DbId, AllPairs()) - PrintN("[Net] Failed to read the sync state for peer '" + *Client\PeerName + "': " + DatabaseError()) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The sync state couldn't be read") - EndIf - - ; Every name this server knows, the peer only sends those. - BakaShrot_Names_GetNamed(#BakaShrot_NameKind_Topic, State\Topics(), @*Client\AcceptTopics) - BakaShrot_Names_GetNamed(#BakaShrot_NameKind_Node, State\Nodes(), @*Client\AcceptNodes) - If *Client\AcceptTopics\All - AddElement(State\TopicPatterns()) : State\TopicPatterns() = "*" - EndIf - ForEach *Client\AcceptTopics\Patterns() - AddElement(State\TopicPatterns()) : State\TopicPatterns() = *Client\AcceptTopics\Patterns() - Next - If *Client\AcceptNodes\All - AddElement(State\NodePatterns()) : State\NodePatterns() = "*" - EndIf - ForEach *Client\AcceptNodes\Patterns() - AddElement(State\NodePatterns()) : State\NodePatterns() = *Client\AcceptNodes\Patterns() - Next - ForEach State\Topics() - Topics(Str(State\Topics()\Id)) = #True - Next - ForEach State\Nodes() - Nodes(Str(State\Nodes()\Id)) = #True - Next - ForEach AllPairs() - If FindMapElement(Topics(), Str(AllPairs()\TopicId)) And FindMapElement(Nodes(), Str(AllPairs()\NodeId)) - AddElement(State\Pairs()) - State\Pairs()\TopicId = AllPairs()\TopicId - State\Pairs()\NodeId = AllPairs()\NodeId - State\Pairs()\MessageId = AllPairs()\MessageId - EndIf - Next - - *Answer = BakaShrot_SyncStatePacket_Encode(@State, @AnswerSize) - If Not *Answer - PrintN("[Net] Failed to encode the sync state for peer '" + *Client\PeerName + "', is it too big?") - ProcedureReturn #False - EndIf - Sent = BakaShrot_SendPacket(*Client\ClientId, *Answer, AnswerSize\i, @*Client\Metadata\Cipher) - FreeMemory(*Answer) - - ProcedureReturn Sent -EndProcedure - - -; Stores a batch of messages a peer replicated, under this server's ids for -; their topic and node names and their original message ids, in one -; transaction, and answers with the last one's message id. -; Refuses regular clients, and topics or nodes this server doesn't take from -; that peer (AcceptTopics, AcceptNodes): only what's named on both servers -; replicates, unless a wildcard there takes a name this server doesn't have, -; which is then added, see Storage/Names.pbi. The sync state tells the peer -; what's taken here, so it doesn't send the rest in the first place. -; Messages already past the topic's max age here ([BakaShrot.Retention]) are -; skipped, but acknowledged like the others. -; Returns #False if the client must be aborted. -Procedure.i BakaShrot_NetClient_HandleReplicateMessages(*Client.BakaShrot_NetClient, *Packet, PacketSize.i) - Protected *View.MsgPackData, *Batch.BakaShrot_ReplicateMessages - Protected Pushed.BakaShrot_MessagePushed - Protected TopicId.i, NodeId.i, TopicRef.s, NodeRef.s, LastMessageId.q, IsStored.i, StoreError.String - Protected MaxAge.q, SkipBefore.q, Skipped.Integer - Protected *Answer, AnswerSize.Integer, Sent.i - - *Batch = 0 - *View = MsgPackWrapMsgBuffer(*Packet, PacketSize) - If *View - *Batch = BakaShrot_ReplicateMessagesPacket_Decode(*View) - MsgPackFree(*View, #False) - EndIf - If Not *Batch - PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an invalid batch of replicated messages") - ProcedureReturn #False - EndIf - TopicRef = *Batch\Topic - NodeRef = *Batch\Node - LastElement(*Batch\Messages()) - LastMessageId = *Batch\Messages()\MessageId - - If *Client\PeerName = "" - FreeStructure(*Batch) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Only peers can replicate") - EndIf - - TopicId = BakaShrot_Names_TopicByName(TopicRef) - If Not NameSetHas(@*Client\AcceptTopics, TopicId, TopicRef) - FreeStructure(*Batch) - BakaShrot_Names_NoteDropped(*Client\PeerName, "topic", TopicRef, "not taken here") - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_InvalidRequest, "Topic '" + TopicRef + "' isn't replicated here") - EndIf - NodeId = BakaShrot_Names_NodeByName(NodeRef) - If Not NameSetHas(@*Client\AcceptNodes, NodeId, NodeRef) - FreeStructure(*Batch) - BakaShrot_Names_NoteDropped(*Client\PeerName, "node", NodeRef, "not taken here") - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_InvalidRequest, "Node '" + NodeRef + "' isn't replicated here") - EndIf - - ; Taken by a wildcard, new here. - If TopicId < 0 - TopicId = BakaShrot_Names_Ingest(#BakaShrot_NameKind_Topic, TopicRef, @StoreError) - EndIf - If TopicId >= 0 And NodeId < 0 - NodeId = BakaShrot_Names_Ingest(#BakaShrot_NameKind_Node, NodeRef, @StoreError) - EndIf - If TopicId < 0 Or NodeId < 0 - FreeStructure(*Batch) - PrintN("[Net] Failed to add '" + TopicRef + "':'" + NodeRef + "' from peer '" + *Client\PeerName + "': " + StoreError\s) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The messages couldn't be stored") - EndIf - - MaxAge = RetentionMaxAgeMs(*Client\Retention(), TopicId, TopicRef) - If MaxAge > 0 - SkipBefore = BakaShrot_NowUtcMs() - MaxAge - EndIf - IsStored = InsertReplicatedMessages(TopicId, NodeId, *Batch\Messages(), @StoreError, SkipBefore, @Skipped, *Client\Server\Config\Server\MaxAttachmentSize) - FreeStructure(*Batch) - If #BakaShrot_Net_LogRequests And Skipped\i > 0 - PrintN("[Net] Skipped " + Str(Skipped\i) + " messages of " + TopicRef + ":" + NodeRef + " from peer '" + *Client\PeerName + "', past their max age here") - EndIf - If Not IsStored - PrintN("[Net] Failed to store messages from peer '" + *Client\PeerName + "': " + StoreError\s) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The messages couldn't be stored") - EndIf - - Pushed\MessageId = LastMessageId - *Answer = BakaShrot_MessagePushedPacket_Encode(@Pushed, @AnswerSize) - If Not *Answer - ProcedureReturn #False - EndIf - Sent = BakaShrot_SendPacket(*Client\ClientId, *Answer, AnswerSize\i, @*Client\Metadata\Cipher) - FreeMemory(*Answer) - - ProcedureReturn Sent -EndProcedure - -; --- Attachments ----------------------------------------------------------------- -; See Design/Attachments.md and Storage/Attachments.pbi. - -; Sends a ChunkStored. Returns #False if it couldn't be sent. -Procedure.i BakaShrot_NetClient_SendChunkStored(*Client.BakaShrot_NetClient, Received.q, Complete.i) - Protected Stored.BakaShrot_ChunkStored, *Answer, AnswerSize.Integer, Sent.i - - Stored\Received = Received - Stored\Complete = Complete - *Answer = BakaShrot_ChunkStoredPacket_Encode(@Stored, @AnswerSize) - If Not *Answer - ProcedureReturn #False - EndIf - Sent = BakaShrot_SendPacket(*Client\ClientId, *Answer, AnswerSize\i, @*Client\Metadata\Cipher) - FreeMemory(*Answer) - ProcedureReturn Sent -EndProcedure - - -; Starts an upload, for a message the client will push to that topic. -; Same permissions as pushing, and at most MaxAttachmentSize bytes. -; Returns #False if the client must be aborted. -Procedure.i BakaShrot_NetClient_HandleUploadStart(*Client.BakaShrot_NetClient, *Packet, PacketSize.i) - Protected *View.MsgPackData, *Start.BakaShrot_UploadStart - Protected Started.BakaShrot_UploadStarted - Protected TopicRef.s, TopicId.i, Size.q, MaxSize.q, BlobId.q, StoreError.String - Protected Dim Sha256.a(#BakaShrot_Sha256Size - 1) - Protected *Answer, AnswerSize.Integer, Sent.i - - *Start = 0 - *View = MsgPackWrapMsgBuffer(*Packet, PacketSize) - If *View - *Start = BakaShrot_UploadStartPacket_Decode(*View) - MsgPackFree(*View, #False) - EndIf - If Not *Start - PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an invalid upload start") - ProcedureReturn #False - EndIf - TopicRef = *Start\Topic - Size = *Start\Size - CopyMemory(@*Start\Sha256[0], @Sha256(0), #BakaShrot_Sha256Size) - FreeStructure(*Start) - - If Not *Client\Permissions\Write - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to write") - EndIf - If TopicRef = "" - TopicId = *Client\Metadata\DefaultTopicId - If TopicId < 0 - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NoDefaultTopic, "No default topic for this client (DefaultTopic in its server's config): name the topic") - EndIf - Else - TopicId = BakaShrot_Names_ResolveTopic(TopicRef) - If TopicId < 0 - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_UnknownName, "Unknown topic '" + Left(TopicRef, 80) + "'") - EndIf - EndIf - If Not NameSetHas(@*Client\PushTopics, TopicId, BakaShrot_Names_TopicName(TopicId)) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to push to topic '" + BakaShrot_Names_TopicRef(TopicId) + "'") - EndIf - - MaxSize = *Client\Server\Config\Server\MaxAttachmentSize - If Size > MaxSize - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_TooBig, "The attachment is too big: " + Str(Size) + " bytes, at most " + Str(MaxSize) + " here") - EndIf - - BlobId = CreateStorageBlob(TopicId, *Client\Metadata\NodeId, Size, @Sha256(0), @StoreError) - If Not BlobId - PrintN("[Net] Failed to start an upload for client " + Str(*Client\ClientId) + ": " + StoreError\s) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The upload couldn't be started") - EndIf - - Started\UploadId = BlobId - Started\ChunkSize = #BakaShrot_AttachmentChunkSize - *Answer = BakaShrot_UploadStartedPacket_Encode(@Started, @AnswerSize) - If Not *Answer - ProcedureReturn #False - EndIf - Sent = BakaShrot_SendPacket(*Client\ClientId, *Answer, AnswerSize\i, @*Client\Metadata\Cipher) - FreeMemory(*Answer) - ProcedureReturn Sent -EndProcedure - - -; Stores the next part of one of this client's uploads. Once all of it is -; here, checks its SHA-256: complete, or dropped and refused. -; Returns #False if the client must be aborted. -Procedure.i BakaShrot_NetClient_HandleUploadChunk(*Client.BakaShrot_NetClient, *Packet, PacketSize.i) - Protected *View.MsgPackData, *Chunk.BakaShrot_UploadChunk - Protected Blob.BakaShrot_StorageBlob, Received.q, StoreError.String, Expected.i - - *Chunk = 0 - *View = MsgPackWrapMsgBuffer(*Packet, PacketSize) - If *View - *Chunk = BakaShrot_UploadChunkPacket_Decode(*View) - MsgPackFree(*View, #False) - EndIf - If Not *Chunk - PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an invalid upload chunk") - ProcedureReturn #False - EndIf - - ; Only its own uploads: same node, a topic it may still push to. - If Not GetStorageBlob(*Client\DbId, *Chunk\UploadId, @Blob) Or Blob\NodeId <> *Client\Metadata\NodeId Or Blob\State <> #BakaShrot_Blob_Receiving - BakaShrot_UploadChunkPacket_Free(*Chunk) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotFound, "No such upload in progress") - EndIf - If Not *Client\Permissions\Write Or Not NameSetHas(@*Client\PushTopics, Blob\TopicId, BakaShrot_Names_TopicName(Blob\TopicId)) - BakaShrot_UploadChunkPacket_Free(*Chunk) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to push to topic '" + BakaShrot_Names_TopicRef(Blob\TopicId) + "'") - EndIf - Expected = BakaShrot_AttachmentChunkBytes(Blob\Size, *Chunk\ChunkIndex) - If *Chunk\ChunkIndex * #BakaShrot_AttachmentChunkSize <> Blob\Received Or *Chunk\DataSize <> Expected - BakaShrot_UploadChunkPacket_Free(*Chunk) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_InvalidRequest, "Expected part " + Str(Blob\Received / #BakaShrot_AttachmentChunkSize) + " of " + Str(BakaShrot_AttachmentChunkCount(Blob\Size)) + ", " + Str(BakaShrot_AttachmentChunkBytes(Blob\Size, Blob\Received / #BakaShrot_AttachmentChunkSize)) + " bytes") - EndIf - - Received = StoreStorageBlobChunk(Blob\BlobId, *Chunk\ChunkIndex, *Chunk\Data, *Chunk\DataSize, @StoreError) - BakaShrot_UploadChunkPacket_Free(*Chunk) - If Received < 0 - PrintN("[Net] Failed to store a part of an upload from client " + Str(*Client\ClientId) + ": " + StoreError\s) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The part couldn't be stored") - EndIf - - If Received < Blob\Size - ProcedureReturn BakaShrot_NetClient_SendChunkStored(*Client, Received, #False) - EndIf - - ; All of it: the SHA-256 given at the start must match. - If Not HashStorageBlob(*Client\DbId, Blob\BlobId, Blob\Size, @Blob\Sha256[0]) - SetStorageBlobState(Blob\BlobId, #BakaShrot_Blob_Deleted) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_DataMismatch, "The upload doesn't match its SHA-256, it's dropped") - EndIf - If Not SetStorageBlobState(Blob\BlobId, #BakaShrot_Blob_Complete) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The upload couldn't be stored") - EndIf - ProcedureReturn BakaShrot_NetClient_SendChunkStored(*Client, Received, #True) -EndProcedure - - -; Answers with a part of a message's attachment, same permissions as -; reading the message. Refuses one that isn't all here yet. -; Returns #False if the client must be aborted. -Procedure.i BakaShrot_NetClient_HandleGetAttachment(*Client.BakaShrot_NetClient, *Packet, PacketSize.i) - Protected *View.MsgPackData, *Request.BakaShrot_GetAttachment - Protected Chunk.BakaShrot_AttachmentChunk, Attachment.BakaShrot_StorageAttachment - Protected TopicId.i, NodeId.i, TopicRef.s, NodeRef.s, MessageId.q, Index.q, DataSize.Integer - Protected *Answer, AnswerSize.Integer, Sent.i - - *Request = 0 - *View = MsgPackWrapMsgBuffer(*Packet, PacketSize) - If *View - *Request = BakaShrot_GetAttachmentPacket_Decode(*View) - MsgPackFree(*View, #False) - EndIf - If Not *Request - PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an invalid attachment request") - ProcedureReturn #False - EndIf - TopicRef = *Request\Topic - NodeRef = *Request\Node - MessageId = *Request\MessageId - Index = *Request\ChunkIndex - FreeStructure(*Request) - - If Not *Client\Permissions\Read - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to read") - EndIf - TopicId = BakaShrot_Names_ResolveTopic(TopicRef) - If TopicId < 0 - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_UnknownName, "Unknown topic '" + Left(TopicRef, 80) + "'") - EndIf - If Not NameSetHas(@*Client\ReadTopics, TopicId, BakaShrot_Names_TopicName(TopicId)) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to read topic '" + BakaShrot_Names_TopicRef(TopicId) + "'") - EndIf - NodeId = BakaShrot_Names_ResolveNode(NodeRef) - If NodeId < 0 - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_UnknownName, "Unknown node '" + Left(NodeRef, 80) + "'") - EndIf - - If Not GetStorageAttachment(*Client\DbId, TopicId, NodeId, MessageId, @Attachment) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotFound, "No attachment for " + BakaShrot_Names_TopicRef(TopicId) + ":" + BakaShrot_Names_NodeRef(NodeId) + "#" + Str(MessageId)) - EndIf - Select Attachment\State - Case #BakaShrot_Attachment_NotKept - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_TooBig, "The attachment isn't kept here: " + Str(Attachment\Size) + " bytes, more than MaxAttachmentSize") - Case #BakaShrot_Attachment_Missing, #BakaShrot_Attachment_Receiving - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotReady, "The attachment isn't here yet: " + Str(Attachment\Received) + " of " + Str(Attachment\Size) + " bytes") - EndSelect - If Index >= BakaShrot_AttachmentChunkCount(Attachment\Size) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_InvalidRequest, "The attachment has " + Str(BakaShrot_AttachmentChunkCount(Attachment\Size)) + " parts") - EndIf - - Chunk\Data = ReadStorageBlobChunk(*Client\DbId, Attachment\BlobId, Index, @DataSize) - If Not Chunk\Data - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The attachment couldn't be read") - EndIf - Chunk\DataSize = DataSize\i - Chunk\TopicId = TopicId - Chunk\NodeId = NodeId - Chunk\MessageId = MessageId - Chunk\Size = Attachment\Size - Chunk\ChunkIndex = Index - CopyMemory(@Attachment\Sha256[0], @Chunk\Sha256[0], #BakaShrot_Sha256Size) - *Answer = BakaShrot_AttachmentChunkPacket_Encode(@Chunk, @AnswerSize) - FreeMemory(Chunk\Data) - If Not *Answer - ProcedureReturn #False - EndIf - Sent = BakaShrot_SendPacket(*Client\ClientId, *Answer, AnswerSize\i, @*Client\Metadata\Cipher) - FreeMemory(*Answer) - ProcedureReturn Sent -EndProcedure - - -; Tells a peer which attachments this server is missing, among what it -; takes from it (AcceptTopics, AcceptNodes): the peer sends what it has. -; Returns #False if the client must be aborted. -Procedure.i BakaShrot_NetClient_HandleMissingAttachmentsRequest(*Client.BakaShrot_NetClient, *Packet, PacketSize.i) - Protected *View.MsgPackData, *Request.BakaShrot_MissingAttachmentsRequest - Protected Answer.BakaShrot_MissingAttachments - Protected NewList Missing.BakaShrot_StorageMissingAttachment() - Protected *Answer, AnswerSize.Integer, Sent.i - - *Request = 0 - *View = MsgPackWrapMsgBuffer(*Packet, PacketSize) - If *View - *Request = BakaShrot_MissingAttachmentsRequestPacket_Decode(*View) - MsgPackFree(*View, #False) - EndIf - If Not *Request - PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an invalid missing attachments request") - ProcedureReturn #False - EndIf - FreeStructure(*Request) - - If *Client\PeerName = "" - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Only peers can replicate") - EndIf - - ; More than one answer holds, some of them may be someone else's. - If Not GetMissingStorageAttachments(*Client\DbId, 4 * #BakaShrot_MaxMissingAttachments, Missing()) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The missing attachments couldn't be read") - EndIf - ForEach Missing() - If ListSize(Answer\Attachments()) >= #BakaShrot_MaxMissingAttachments - Break - EndIf - If Not NameSetHas(@*Client\AcceptTopics, Missing()\TopicId, Missing()\Topic) Or Not NameSetHas(@*Client\AcceptNodes, Missing()\NodeId, Missing()\Node) - Continue - EndIf - If Not BakaShrot_IsValidName(Missing()\Topic) Or Not BakaShrot_IsValidName(Missing()\Node) - Continue - EndIf - AddElement(Answer\Attachments()) - Answer\Attachments()\Topic = Missing()\Topic - Answer\Attachments()\Node = Missing()\Node - Answer\Attachments()\MessageId = Missing()\MessageId - Answer\Attachments()\NextChunk = Missing()\Received / #BakaShrot_AttachmentChunkSize - Next - - *Answer = BakaShrot_MissingAttachmentsPacket_Encode(@Answer, @AnswerSize) - If Not *Answer - ProcedureReturn #False - EndIf - Sent = BakaShrot_SendPacket(*Client\ClientId, *Answer, AnswerSize\i, @*Client\Metadata\Cipher) - FreeMemory(*Answer) - ProcedureReturn Sent -EndProcedure - - -; Stores a part of an attachment a peer replicates, of a message this server -; already has: in order, resuming where a previous link stopped. Once all of -; it is here, checks its SHA-256 (the one its message came with): ready, or -; dropped to be sent again. -; Returns #False if the client must be aborted. -Procedure.i BakaShrot_NetClient_HandleReplicateAttachmentChunk(*Client.BakaShrot_NetClient, *Packet, PacketSize.i) - Protected *View.MsgPackData, *Chunk.BakaShrot_ReplicateAttachmentChunk - Protected Attachment.BakaShrot_StorageAttachment - Protected TopicId.i, NodeId.i, TopicRef.s, NodeRef.s, MessageId.q, BlobId.q, Received.q, IsValid.i, StoreError.String - - *Chunk = 0 - *View = MsgPackWrapMsgBuffer(*Packet, PacketSize) - If *View - *Chunk = BakaShrot_ReplicateAttachmentChunkPacket_Decode(*View) - MsgPackFree(*View, #False) - EndIf - If Not *Chunk - PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an invalid attachment chunk") - ProcedureReturn #False - EndIf - TopicRef = *Chunk\Topic - NodeRef = *Chunk\Node - MessageId = *Chunk\MessageId - - If *Client\PeerName = "" - BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Only peers can replicate") - EndIf - TopicId = BakaShrot_Names_TopicByName(TopicRef) - NodeId = BakaShrot_Names_NodeByName(NodeRef) - If TopicId < 0 Or NodeId < 0 Or Not NameSetHas(@*Client\AcceptTopics, TopicId, TopicRef) Or Not NameSetHas(@*Client\AcceptNodes, NodeId, NodeRef) - BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_InvalidRequest, "'" + TopicRef + "':'" + NodeRef + "' isn't replicated here") - EndIf - - If Not GetStorageAttachment(*Client\DbId, TopicId, NodeId, MessageId, @Attachment) - BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_InvalidRequest, "No attachment expected for " + TopicRef + ":" + NodeRef + "#" + Str(MessageId)) - EndIf - If Attachment\State = #BakaShrot_Attachment_Ready - ; Someone else's link was faster: done. - BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk) - ProcedureReturn BakaShrot_NetClient_SendChunkStored(*Client, Attachment\Size, #True) - EndIf - If Attachment\State = #BakaShrot_Attachment_NotKept - BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_TooBig, "The attachment isn't kept here") - EndIf - If *Chunk\ChunkIndex * #BakaShrot_AttachmentChunkSize <> Attachment\Received Or *Chunk\DataSize <> BakaShrot_AttachmentChunkBytes(Attachment\Size, *Chunk\ChunkIndex) - BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_InvalidRequest, "Expected part " + Str(Attachment\Received / #BakaShrot_AttachmentChunkSize)) - EndIf - - BlobId = Attachment\BlobId - If Not BlobId - BlobId = StartReplicatedAttachment(TopicId, NodeId, MessageId, @StoreError) - EndIf - If BlobId - Received = StoreStorageBlobChunk(BlobId, *Chunk\ChunkIndex, *Chunk\Data, *Chunk\DataSize, @StoreError) - Else - Received = -1 - EndIf - BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk) - If Received < 0 - PrintN("[Net] Failed to store an attachment's part from peer '" + *Client\PeerName + "': " + StoreError\s) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The part couldn't be stored") - EndIf - - If Received < Attachment\Size - ProcedureReturn BakaShrot_NetClient_SendChunkStored(*Client, Received, #False) - EndIf - - IsValid = HashStorageBlob(*Client\DbId, BlobId, Attachment\Size, @Attachment\Sha256[0]) - If Not FinishReplicatedAttachment(TopicId, NodeId, MessageId, BlobId, IsValid) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The attachment couldn't be stored") - EndIf - If Not IsValid - PrintN("[Net] The attachment of " + TopicRef + ":" + NodeRef + "#" + Str(MessageId) + " from peer '" + *Client\PeerName + "' doesn't match its SHA-256, dropped") - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_DataMismatch, "The attachment doesn't match its SHA-256, send it again") - EndIf - ProcedureReturn BakaShrot_NetClient_SendChunkStored(*Client, Received, #True) -EndProcedure - - -; Handles one request from an authenticated client. -; Returns #False if the client must be aborted. -Procedure.i BakaShrot_NetClient_HandleRequest(*Client.BakaShrot_NetClient, *Packet, PacketSize.i) - Select BakaShrot_GetPacketType(*Packet, PacketSize) - Case #BakaShrot_PacketType_PushMessage - ProcedureReturn BakaShrot_NetClient_HandlePushMessage(*Client, *Packet, PacketSize) - - Case #BakaShrot_PacketType_GetLatestMessage - ProcedureReturn BakaShrot_NetClient_HandleGetLatestMessage(*Client, *Packet, PacketSize) - - Case #BakaShrot_PacketType_GetMessages - ProcedureReturn BakaShrot_NetClient_HandleGetMessages(*Client, *Packet, PacketSize) - - Case #BakaShrot_PacketType_QueryRequest - ProcedureReturn BakaShrot_NetClient_HandleQuery(*Client, *Packet, PacketSize) - - Case #BakaShrot_PacketType_ResolveName - ProcedureReturn BakaShrot_NetClient_HandleResolveName(*Client, *Packet, PacketSize) - - Case #BakaShrot_PacketType_ListNames - ProcedureReturn BakaShrot_NetClient_HandleListNames(*Client, *Packet, PacketSize) - - Case #BakaShrot_PacketType_SyncStateRequest - ProcedureReturn BakaShrot_NetClient_HandleSyncStateRequest(*Client, *Packet, PacketSize) - - Case #BakaShrot_PacketType_ReplicateMessages - ProcedureReturn BakaShrot_NetClient_HandleReplicateMessages(*Client, *Packet, PacketSize) - - Case #BakaShrot_PacketType_UploadStart - ProcedureReturn BakaShrot_NetClient_HandleUploadStart(*Client, *Packet, PacketSize) - - Case #BakaShrot_PacketType_UploadChunk - ProcedureReturn BakaShrot_NetClient_HandleUploadChunk(*Client, *Packet, PacketSize) - - Case #BakaShrot_PacketType_GetAttachment - ProcedureReturn BakaShrot_NetClient_HandleGetAttachment(*Client, *Packet, PacketSize) - - Case #BakaShrot_PacketType_MissingAttachmentsRequest - ProcedureReturn BakaShrot_NetClient_HandleMissingAttachmentsRequest(*Client, *Packet, PacketSize) - - Case #BakaShrot_PacketType_ReplicateAttachmentChunk - ProcedureReturn BakaShrot_NetClient_HandleReplicateAttachmentChunk(*Client, *Packet, PacketSize) - EndSelect - - PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an unexpected packet") - ProcedureReturn #False -EndProcedure - - -Procedure BakaShrot_NetClient_Thread(*Client.BakaShrot_NetClient) - Protected *Server.BakaShrot_NetServer = *Client\Server - Protected *Packet, PacketSize.Integer, Disconnected.i, Handled.i - - If BakaShrot_NetClient_Authenticate(*Client) - *Client\DbId = OpenStorageDatabase(*Server\DatabasePath) - If Not *Client\DbId - PrintN("[Net] Failed to open the database for client " + Str(*Client\ClientId) + ": " + DatabaseError()) - EndIf - EndIf - - If *Client\DbId - Repeat - *Packet = BakaShrot_NetClient_WaitPacket(*Client, @PacketSize, 0) - If Not *Packet - Break - EndIf - - Handled = BakaShrot_NetClient_HandleRequest(*Client, *Packet, PacketSize\i) - FreeMemory(*Packet) - If Not Handled - Break - EndIf - ForEver - EndIf - - ; Removes the client so the listener stops using it, unless it already did - ; because the client disconnected. - LockMutex(*Server\Mutex) - Disconnected = *Client\Disconnected - If FindMapElement(*Server\Clients(), Str(*Client\ClientId)) - If *Server\Clients() = *Client - DeleteMapElement(*Server\Clients()) - EndIf - EndIf - UnlockMutex(*Server\Mutex) - - If Disconnected - *Client\Metadata\Status = #BakaShrot_ConnectionStatus_Disconnected - Else - *Client\Metadata\Status = #BakaShrot_ConnectionStatus_Aborted - ; Under the mutex: NetworkServerEvent() changes the same connection - ; list, unlocked it crashed the listener (Linux, Notes.md item 21). - LockMutex(*Server\Mutex) - CloseNetworkConnection(*Client\ClientId) - UnlockMutex(*Server\Mutex) - PrintN("[Net] Client " + Str(*Client\ClientId) + " aborted") - EndIf - - If *Client\DbId - CloseDatabase(*Client\DbId) - EndIf - BakaShrot_Inbox_Clear(@*Client\Inbox) - BakaShrot_ClearConnectionMetadata(@*Client\Metadata) - ; Out of Clients(), the listener can't set it anymore. - BakaShrot_Signal_Free(*Client\Signal) - FreeStructure(*Client) - - LockMutex(*Server\Mutex) - *Server\ActiveClientThreads - 1 - UnlockMutex(*Server\Mutex) -EndProcedure - - -; Called by the listener thread when a client connects. -Procedure BakaShrot_NetServer_AcceptClient(*Server.BakaShrot_NetServer, ClientId.i) - Protected *Client.BakaShrot_NetClient - - *Client = AllocateStructure(BakaShrot_NetClient) - If Not *Client - PrintN("[Net] Out of memory, refusing client " + Str(ClientId)) - CloseNetworkConnection(ClientId) - ProcedureReturn - EndIf - *Client\Server = *Server - *Client\ClientId = ClientId - *Client\Signal = BakaShrot_Signal_Create() - If Not *Client\Signal - PrintN("[Net] Failed to create a signal, refusing client " + Str(ClientId)) - FreeStructure(*Client) - CloseNetworkConnection(ClientId) - ProcedureReturn - EndIf - - LockMutex(*Server\Mutex) - *Server\Clients(Str(ClientId)) = *Client - *Server\ActiveClientThreads + 1 - UnlockMutex(*Server\Mutex) - - If Not CreateThread(@BakaShrot_NetClient_Thread(), *Client) - LockMutex(*Server\Mutex) - DeleteMapElement(*Server\Clients(), Str(ClientId)) - *Server\ActiveClientThreads - 1 - UnlockMutex(*Server\Mutex) - - BakaShrot_Signal_Free(*Client\Signal) - FreeStructure(*Client) - CloseNetworkConnection(ClientId) - PrintN("[Net] Failed to start a thread, refusing client " + Str(ClientId)) - ProcedureReturn - EndIf - - PrintN("[Net] Client " + Str(ClientId) + " connected") -EndProcedure - - -; Called by the listener thread when a client sent data. -Procedure BakaShrot_NetServer_ReceiveClientData(*Server.BakaShrot_NetServer, ClientId.i, *Buffer) - Protected *Client.BakaShrot_NetClient, Received.i - - ; Done while holding the mutex, so the client's thread can't close the - ; connection in the middle of it. - LockMutex(*Server\Mutex) - If FindMapElement(*Server\Clients(), Str(ClientId)) - *Client = *Server\Clients() - Received = ReceiveNetworkData(ClientId, *Buffer, #BakaShrot_Net_ReceiveBufferSize) - If Received > 0 - If Not BakaShrot_Inbox_Append(@*Client\Inbox, *Buffer, Received) - *Client\Overflowed = #True - EndIf - BakaShrot_Signal_Set(*Client\Signal) - EndIf - EndIf - UnlockMutex(*Server\Mutex) -EndProcedure - - -; Called by the listener thread when a client disconnected. -Procedure BakaShrot_NetServer_DropClient(*Server.BakaShrot_NetServer, ClientId.i) - Protected *Client.BakaShrot_NetClient - - LockMutex(*Server\Mutex) - If FindMapElement(*Server\Clients(), Str(ClientId)) - *Client = *Server\Clients() - *Client\Disconnected = #True - BakaShrot_Signal_Set(*Client\Signal) - DeleteMapElement(*Server\Clients()) - EndIf - UnlockMutex(*Server\Mutex) -EndProcedure - - -; Sleeps until a client sends something, connects or disconnects, for up to -; TimeoutMs. *Set is just a buffer, reused to save allocating it every time. -Procedure BakaShrot_NetServer_WaitEvent(*Server.BakaShrot_NetServer, *Set.BakaShrot_SocketSet, TimeoutMs.i) - Protected *Client.BakaShrot_NetClient - - BakaShrot_SocketSet_Clear(*Set) - BakaShrot_SocketSet_Add(*Set, ServerID(*Server\ServerId)) - LockMutex(*Server\Mutex) - ForEach *Server\Clients() - *Client = *Server\Clients() - BakaShrot_SocketSet_Add(*Set, ConnectionID(*Client\ClientId)) - Next - UnlockMutex(*Server\Mutex) - - BakaShrot_SocketSet_Wait(*Set, TimeoutMs) -EndProcedure - - -Procedure BakaShrot_NetServer_Thread(*Server.BakaShrot_NetServer) - Protected *Buffer, *Set.BakaShrot_SocketSet, Event.i - - *Buffer = AllocateMemory(#BakaShrot_Net_ReceiveBufferSize) - *Set = AllocateStructure(BakaShrot_SocketSet) - If Not *Buffer Or Not *Set - PrintN("[Net] Failed to allocate the receive buffer") - ProcedureReturn - EndIf - - While Not *Server\StopRequested - ; NetworkServerEvent() and the event's handling under the mutex: a - ; client thread aborting closes its connection under it too, and both - ; change PureBasic's connection list (unlocked, it crashed on Linux, - ; Notes.md item 21). The handlers lock it again, PureBasic's mutexes - ; are recursive. - LockMutex(*Server\Mutex) - Event = NetworkServerEvent(*Server\ServerId) - Select Event - - Case #PB_NetworkEvent_Connect - BakaShrot_NetServer_AcceptClient(*Server, EventClient()) - - Case #PB_NetworkEvent_Data - BakaShrot_NetServer_ReceiveClientData(*Server, EventClient(), *Buffer) - - Case #PB_NetworkEvent_Disconnect - BakaShrot_NetServer_DropClient(*Server, EventClient()) - - EndSelect - UnlockMutex(*Server\Mutex) - - If Event = #PB_NetworkEvent_None - ; Nothing left, sleeps until there's something (not holding the - ; mutex), waking up at least every 20 ms to check StopRequested. - BakaShrot_NetServer_WaitEvent(*Server, *Set, 20) - EndIf - Wend - - FreeStructure(*Set) - FreeMemory(*Buffer) -EndProcedure - - -; Starts listening on Host:Port, an empty Host binds to every interface. -; Clients are authenticated against *Config's [BakaShrot.Client.] -; sections, and their messages are stored in its [BakaShrot.Server] -; DatabasePath. *Config must outlive the server. -; Returns 0 on failure, stop the returned server with BakaShrot_NetServer_Stop(). -Procedure.i BakaShrot_NetServer_Start(Host.s, Port.u, *Config.BakaShrot_CoreConfig) - Protected *Server.BakaShrot_NetServer - - ; Only needed before PureBasic 6.00. - CompilerIf #PB_Compiler_Version < 600 - If Not InitNetwork() - ProcedureReturn 0 - EndIf - CompilerEndIf - - ; Verifies the challenge responses. - If Not InitCryptography() - ProcedureReturn 0 - EndIf - - ; Challenges and nonces come from it. - If Not OpenCryptRandom() - ProcedureReturn 0 - EndIf - - *Server = AllocateStructure(BakaShrot_NetServer) - If Not *Server - CloseCryptRandom() - ProcedureReturn 0 - EndIf - *Server\Config = *Config - *Server\DatabasePath = *Config\Server\DatabasePath - - ; Its identity: clients seal their Hello for it, and check it signed the - ; handshake. - If Not DecodeKeyFromString(*Config\PrivateKey, @*Server\PrivateKey[0], #BakaShrot_Ed25519_PrivateKeySize) - PrintN("[Net] [BakaShrot] PrivateKey is missing or invalid") - FreeStructure(*Server) - CloseCryptRandom() - ProcedureReturn 0 - EndIf - GetPublicKeyFromPrivateKey(@*Server\PrivateKey[0], @*Server\PublicKey[0]) - If Not BakaShrot_Session_LoadHelloKeys(@*Server\HelloKeys, @*Server\PrivateKey[0]) - PrintN("[Net] [BakaShrot] PrivateKey can't be used to open hellos") - sodium_memzero(@*Server\PrivateKey[0], #BakaShrot_Ed25519_PrivateKeySize) - FreeStructure(*Server) - CloseCryptRandom() - ProcedureReturn 0 - EndIf - ; Clients need it as their ServerPublicKey. - PrintN("[Net] Server public key: " + EncodeKeyToString(@*Server\PublicKey[0], #BakaShrot_Ed25519_PublicKeySize)) - - *Server\Mutex = CreateMutex() - If Not *Server\Mutex - FreeStructure(*Server) - CloseCryptRandom() - ProcedureReturn 0 - EndIf - - If Host = "" - *Server\ServerId = CreateNetworkServer(#PB_Any, Port, #PB_Network_TCP | #PB_Network_IPv4) - Else - *Server\ServerId = CreateNetworkServer(#PB_Any, Port, #PB_Network_TCP | #PB_Network_IPv4, Host) - EndIf - If Not *Server\ServerId - FreeMutex(*Server\Mutex) - FreeStructure(*Server) - CloseCryptRandom() - ProcedureReturn 0 - EndIf - - *Server\ThreadId = CreateThread(@BakaShrot_NetServer_Thread(), *Server) - If Not *Server\ThreadId - CloseNetworkServer(*Server\ServerId) - FreeMutex(*Server\Mutex) - FreeStructure(*Server) - CloseCryptRandom() - ProcedureReturn 0 - EndIf - - ProcedureReturn *Server -EndProcedure - - -; Stops every thread, closes the server and frees *Server. -; Connected clients are dropped. Once it returns, no client thread is left, -; so none holds a database connection either. -Procedure BakaShrot_NetServer_Stop(*Server.BakaShrot_NetServer) - Protected ActiveClientThreads.i - - *Server\StopRequested = #True - WaitThread(*Server\ThreadId) - - ; Client threads notice StopRequested within a few ms and close their connection. - Repeat - LockMutex(*Server\Mutex) - ActiveClientThreads = *Server\ActiveClientThreads - UnlockMutex(*Server\Mutex) - If ActiveClientThreads = 0 - Break - EndIf - Delay(5) - ForEver - - CloseNetworkServer(*Server\ServerId) - FreeMutex(*Server\Mutex) - ; Don't leave the private key lying around in freed memory. - sodium_memzero(@*Server\PrivateKey[0], #BakaShrot_Ed25519_PrivateKeySize) - BakaShrot_Session_ClearHelloKeys(@*Server\HelloKeys) - FreeStructure(*Server) - CloseCryptRandom() -EndProcedure diff --git a/Server/Networking/Networking.pbi.cfg b/Server/Networking/Networking.pbi.cfg deleted file mode 100644 index 489f748..0000000 --- a/Server/Networking/Networking.pbi.cfg +++ /dev/null @@ -1,7 +0,0 @@ -IDE Options = PureBasic 6.41 beta 2 (Windows - x64) -EnableThread -EnableXP -DPIAware -CompileSourceDirectory -EnableCompileCount = 0 -EnableBuildCount = 0 diff --git a/Server/Networking/Peers.pbi b/Server/Networking/Peers.pbi deleted file mode 100644 index 10966eb..0000000 --- a/Server/Networking/Peers.pbi +++ /dev/null @@ -1,733 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: Peers.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; BakaShrot Server Peers -; -; Links this server to the other servers in its config's -; [BakaShrot.Peer.] sections, one thread per peer. Each thread: -; 1. Connects to the peer and authenticates with this server's own identity -; ([BakaShrot] PrivateKey/TopicId/NodeId), like a client would. The peer -; must have it registered in one of its [BakaShrot.Client.]. -; 2. Stays connected until the link drops. -; 3. Waits [BakaShrot.Server] PeerRetryDelay seconds, then starts over. -; Same after a failed attempt. -; -; Once linked, it checks in with the peer every [BakaShrot.Server] -; PeerSyncInterval seconds, starting right away: -; 1. Asks the peer for its sync state: the topics it takes from this -; server, and the highest message id it has for each of their -; topic/node ids, in its own ids, with their names. -; 2. Compares it with this server's own (GetSyncState() in Storage.pbi), -; matching topics and nodes by name: each server has its own ids, see -; Server/Storage/Names.pbi. Only what's named on both sides replicates: -; an unnamed one, or one whose name the peer doesn't list, is dropped -; (BakaShrot_Names_NoteDropped()). -; 3. For every topic/node the peer takes, this server sends it -; (the peer section's SendTopics), and the peer is behind on, sends it -; the missing messages in order, in batches of up to -; [BakaShrot.Server] PeerBatchSize messages, about 64 KB at most (a -; bigger message goes alone, see ReplicateMessagesPacket.pbi), each -; batch stored in one transaction and answered before the next. The -; batches carry the names, the peer stores them under its own ids. -; A message's attachment only has its size and SHA-256 in the batch. -; 4. Once the messages are caught up, asks the peer which attachments it's -; missing (MissingAttachmentsRequest) and sends those it has, a part -; (1 MB) per request, from where the peer stopped (Design/Attachments.md). -; The peer does the same over its own link to this server, which covers the -; other direction. Any packet from the peer outside of a check-in drops the -; link as unexpected. -; Known issues, like two servers drifting apart: Design/ReplicationIssues.md. -; -; Each link thread opens its own database connection when it starts, and -; closes it when it ends. See the top of Storage/Storage.pbi. -; -; The peer proves itself in the handshake: the Hello is sealed for the peer -; section's PublicKey and the peer must sign the handshake with the matching -; private key, so a link only reaches the real peer, and is encrypted -; (Commons/Networking/Connections.pbi). -; -; Logs with PrintN(), so the program must have a console open. -; Must be compiled with the thread-safe option enabled. -; ============================================================================ - -CompilerIf Not #PB_Compiler_Thread - CompilerError "Peers.pbi needs the thread-safe option (Compiler Options > Create threadsafe executable)." -CompilerEndIf - -XIncludeFile "../../Commons/Networking/Outbound.pbi" -XIncludeFile "../Config/Config.pbi" -XIncludeFile "../Storage/Storage.pbi" -XIncludeFile "../Storage/Names.pbi" - - -Structure BakaShrot_PeerLink - *Links - - ; [BakaShrot.Peer.] - Name.s - Host.s - Port.i - - ; The peer section's PublicKey: who the peer must prove to be. - ServerPublicKey.a[#BakaShrot_Ed25519_PublicKeySize] - - ThreadId.i - - ; Only used by the link's thread. - Outbound.BakaShrot_Outbound - DbId.i - - ; The peer section's SendTopics and SendNodes, copied for the link's thread. - SendTopics.BakaShrot_NameSet - SendNodes.BakaShrot_NameSet -EndStructure - - -Structure BakaShrot_PeerLinks - ; Set by BakaShrot_PeerLinks_Stop(), makes every link's thread return. - StopRequested.i - - RetryDelayMs.i - SyncIntervalMs.i - - ; Most messages sent per ReplicateMessages packet. - BatchSize.i - - ; Every link's thread opens its own connection to it. - DatabasePath.s - - ; This server's identity, read by every link's thread. - Identity.BakaShrot_OutboundIdentity - PrivateKey.a[#BakaShrot_Ed25519_PrivateKeySize] - PublicKey.a[#BakaShrot_Ed25519_PublicKeySize] - - List Links.BakaShrot_PeerLink() -EndStructure - - -; Waits the retry delay, returns early if stopping. -Procedure BakaShrot_PeerLink_WaitRetry(*Link.BakaShrot_PeerLink) - Protected *Links.BakaShrot_PeerLinks = *Link\Links - Protected StartTime.i - - StartTime = ElapsedMilliseconds() - While Not *Links\StopRequested And ElapsedMilliseconds() - StartTime < *Links\RetryDelayMs - Delay(100) - Wend -EndProcedure - - -; Sends a request to the peer and waits for its answer. -; Returns the answer (free it with FreeMemory) with its size in *OutSize\i, -; or 0 if the link failed. -Procedure.i BakaShrot_PeerLink_Request(*Link.BakaShrot_PeerLink, *Request, RequestSize.i, *OutSize.Integer) - If Not BakaShrot_Outbound_Send(@*Link\Outbound, *Request, RequestSize) - ProcedureReturn 0 - EndIf - ProcedureReturn BakaShrot_Outbound_WaitPacket(@*Link\Outbound, *OutSize, #BakaShrot_Outbound_Timeout) -EndProcedure - - -; Logs a RequestRefused answer from the peer. -; Returns #False if it's malformed, the link must then be dropped. -Procedure.i BakaShrot_PeerLink_LogRefusal(*Link.BakaShrot_PeerLink, *Answer, AnswerSize.i) - Protected *View.MsgPackData, *Refused.BakaShrot_RequestRefused - - *Refused = 0 - *View = MsgPackWrapMsgBuffer(*Answer, AnswerSize) - If *View - *Refused = BakaShrot_RequestRefusedPacket_Decode(*View) - MsgPackFree(*View, #False) - EndIf - If Not *Refused - ProcedureReturn #False - EndIf - - PrintN("[Peer] '" + *Link\Name + "' refused (" + BakaShrot_ErrorName(*Refused\Code) + "): " + *Refused\Reason) - FreeStructure(*Refused) - ProcedureReturn #True -EndProcedure - - -; Sends the peer the attachment it's missing, *Missing, from the part it -; asked for on, if this server has all of it and sends that topic/node to it. -; Returns 1 once the peer has it, 0 if it's skipped (not here, not sent to -; that peer, refused: logged), -1 if the link must be dropped. -Procedure.i BakaShrot_PeerLink_SendAttachment(*Link.BakaShrot_PeerLink, *Missing.BakaShrot_MissingAttachment) - Protected *Links.BakaShrot_PeerLinks = *Link\Links - Protected Attachment.BakaShrot_StorageAttachment, Chunk.BakaShrot_ReplicateAttachmentChunk - Protected *Stored.BakaShrot_ChunkStored - Protected TopicId.i, NodeId.i, Index.q, Count.q, DataSize.Integer, Complete.i - Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer, *View.MsgPackData, IsRefusal.i - - TopicId = BakaShrot_Names_TopicByName(*Missing\Topic) - NodeId = BakaShrot_Names_NodeByName(*Missing\Node) - If TopicId < 0 Or NodeId < 0 - ProcedureReturn 0 - EndIf - If Not NameSetHas(@*Link\SendTopics, TopicId, *Missing\Topic) Or Not NameSetHas(@*Link\SendNodes, NodeId, *Missing\Node) - ProcedureReturn 0 - EndIf - ; Not here either (yet, or not kept): another server may have it. - If Not GetStorageAttachment(*Link\DbId, TopicId, NodeId, *Missing\MessageId, @Attachment) Or Attachment\State <> #BakaShrot_Attachment_Ready - ProcedureReturn 0 - EndIf - - Count = BakaShrot_AttachmentChunkCount(Attachment\Size) - Chunk\Topic = *Missing\Topic - Chunk\Node = *Missing\Node - Chunk\MessageId = *Missing\MessageId - For Index = *Missing\NextChunk To Count - 1 - If *Links\StopRequested - ProcedureReturn -1 - EndIf - - Chunk\ChunkIndex = Index - Chunk\Data = ReadStorageBlobChunk(*Link\DbId, Attachment\BlobId, Index, @DataSize) - If Not Chunk\Data - PrintN("[Peer] Can't read part " + Str(Index) + " of the attachment of " + *Missing\Topic + ":" + *Missing\Node + "#" + Str(*Missing\MessageId) + " for '" + *Link\Name + "'") - ProcedureReturn 0 - EndIf - Chunk\DataSize = DataSize\i - *Packet = BakaShrot_ReplicateAttachmentChunkPacket_Encode(@Chunk, @PacketSize) - FreeMemory(Chunk\Data) - Chunk\Data = 0 - If Not *Packet - ProcedureReturn -1 - EndIf - *Answer = BakaShrot_PeerLink_Request(*Link, *Packet, PacketSize\i, @AnswerSize) - FreeMemory(*Packet) - If Not *Answer - ProcedureReturn -1 - EndIf - - If BakaShrot_GetPacketType(*Answer, AnswerSize\i) = #BakaShrot_PacketType_RequestRefused - IsRefusal = BakaShrot_PeerLink_LogRefusal(*Link, *Answer, AnswerSize\i) - FreeMemory(*Answer) - If Not IsRefusal - ProcedureReturn -1 - EndIf - ProcedureReturn 0 - EndIf - - *Stored = 0 - *View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i) - If *View - *Stored = BakaShrot_ChunkStoredPacket_Decode(*View) - MsgPackFree(*View, #False) - EndIf - FreeMemory(*Answer) - If Not *Stored - PrintN("[Peer] '" + *Link\Name + "' sent an invalid answer to an attachment's part") - ProcedureReturn -1 - EndIf - Complete = *Stored\Complete - FreeStructure(*Stored) - If Complete - ProcedureReturn 1 - EndIf - Next - - ; All sent, and the peer didn't say it's complete: it'll ask again. - ProcedureReturn 0 -EndProcedure - - -; Once the messages are caught up: asks the peer which attachments it's -; missing, and sends those this server has, one after the other. -; Returns #False if the link must be dropped. -Procedure.i BakaShrot_PeerLink_SendAttachments(*Link.BakaShrot_PeerLink) - Protected Request.BakaShrot_MissingAttachmentsRequest, *Missing.BakaShrot_MissingAttachments - Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer, *View.MsgPackData, IsRefusal.i - Protected Result.i, StartTime.i, Attachment.BakaShrot_StorageAttachment, Key.s - - *Packet = BakaShrot_MissingAttachmentsRequestPacket_Encode(@Request, @PacketSize) - If Not *Packet - ProcedureReturn #False - EndIf - *Answer = BakaShrot_PeerLink_Request(*Link, *Packet, PacketSize\i, @AnswerSize) - FreeMemory(*Packet) - If Not *Answer - PrintN("[Peer] '" + *Link\Name + "' didn't answer which attachments it's missing") - ProcedureReturn #False - EndIf - - If BakaShrot_GetPacketType(*Answer, AnswerSize\i) = #BakaShrot_PacketType_RequestRefused - IsRefusal = BakaShrot_PeerLink_LogRefusal(*Link, *Answer, AnswerSize\i) - FreeMemory(*Answer) - ProcedureReturn IsRefusal - EndIf - - *Missing = 0 - *View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i) - If *View - *Missing = BakaShrot_MissingAttachmentsPacket_Decode(*View) - MsgPackFree(*View, #False) - EndIf - FreeMemory(*Answer) - If Not *Missing - PrintN("[Peer] '" + *Link\Name + "' sent an invalid list of missing attachments") - ProcedureReturn #False - EndIf - - ForEach *Missing\Attachments() - StartTime = ElapsedMilliseconds() - Result = BakaShrot_PeerLink_SendAttachment(*Link, @*Missing\Attachments()) - If Result < 0 - FreeStructure(*Missing) - ProcedureReturn #False - EndIf - If Result > 0 - Key = *Missing\Attachments()\Topic + ":" + *Missing\Attachments()\Node + "#" + Str(*Missing\Attachments()\MessageId) - PrintN("[Peer] Sent the attachment of " + Key + " to '" + *Link\Name + "' in " + Str(ElapsedMilliseconds() - StartTime) + " ms, from part " + Str(*Missing\Attachments()\NextChunk)) - EndIf - Next - FreeStructure(*Missing) - ProcedureReturn #True -EndProcedure - - -; Sends a batch of messages the peer is missing and checks its answer. -; Returns 1 once stored, 0 if the peer refused it (logged), or -1 if the -; link must be dropped. -Procedure.i BakaShrot_PeerLink_SendBatch(*Link.BakaShrot_PeerLink, *Batch.BakaShrot_ReplicateMessages) - Protected *Pushed.BakaShrot_MessagePushed - Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer - Protected *View.MsgPackData, IsRefusal.i, IsAcknowledged.i, LastMessageId.q - - LastElement(*Batch\Messages()) - LastMessageId = *Batch\Messages()\MessageId - - *Packet = BakaShrot_ReplicateMessagesPacket_Encode(*Batch, @PacketSize) - If Not *Packet - ProcedureReturn -1 - EndIf - *Answer = BakaShrot_PeerLink_Request(*Link, *Packet, PacketSize\i, @AnswerSize) - FreeMemory(*Packet) - If Not *Answer - ProcedureReturn -1 - EndIf - - If BakaShrot_GetPacketType(*Answer, AnswerSize\i) = #BakaShrot_PacketType_RequestRefused - IsRefusal = BakaShrot_PeerLink_LogRefusal(*Link, *Answer, AnswerSize\i) - FreeMemory(*Answer) - If Not IsRefusal - ProcedureReturn -1 - EndIf - ProcedureReturn 0 - EndIf - - *Pushed = 0 - *View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i) - If *View - *Pushed = BakaShrot_MessagePushedPacket_Decode(*View) - MsgPackFree(*View, #False) - EndIf - FreeMemory(*Answer) - If Not *Pushed - ProcedureReturn -1 - EndIf - - ; An acknowledgement for anything but the batch's last message is out of order. - IsAcknowledged = Bool(*Pushed\MessageId = LastMessageId) - FreeStructure(*Pushed) - If Not IsAcknowledged - ProcedureReturn -1 - EndIf - - ProcedureReturn 1 -EndProcedure - - -; Sends every message of a topic/node id above AfterMessageId, in order, in -; batches of up to [BakaShrot.Server] PeerBatchSize messages, each one cut -; short at about #BakaShrot_ReplicateBatchBytes (a bigger message alone). TopicRef and NodeRef are what they -; go by on the wire: their names, or their ids in digits. -; Stops at the first refusal, or if the server is stopping. -; Returns how many were stored, or -1 if the link must be dropped. -Procedure.i BakaShrot_PeerLink_SendMissing(*Link.BakaShrot_PeerLink, TopicId.i, NodeId.i, TopicRef.s, NodeRef.s, AfterMessageId.q) - Protected *Links.BakaShrot_PeerLinks = *Link\Links - Protected NewList Messages.BakaShrot_Message() - Protected Batch.BakaShrot_ReplicateMessages - Protected SentCount.i, Result.i, BatchSize.i, MessageSize.i - - Batch\Topic = TopicRef - Batch\Node = NodeRef - - Repeat - If *Links\StopRequested - ProcedureReturn SentCount - EndIf - - If Not GetMessagesAfter(*Link\DbId, TopicId, NodeId, AfterMessageId, *Links\BatchSize, #BakaShrot_ReplicateBatchBytes, Messages()) - PrintN("[Peer] Failed to read the messages to send to '" + *Link\Name + "': " + DatabaseError()) - ProcedureReturn SentCount - EndIf - If ListSize(Messages()) = 0 - ProcedureReturn SentCount - EndIf - - ; As many as fit in #BakaShrot_ReplicateBatchBytes, the rest goes in the - ; next batch. A bigger message goes alone, if it fits in a packet. - ClearList(Batch\Messages()) - BatchSize = #BakaShrot_ReplicateBatchOverhead - ForEach Messages() - MessageSize = #BakaShrot_ReplicateMessageOverhead + StringByteLength(Messages()\JsonData, #PB_UTF8) - If ListSize(Batch\Messages()) > 0 And BatchSize + MessageSize > #BakaShrot_ReplicateBatchBytes - Break - EndIf - If BatchSize + MessageSize > #BakaShrot_MaxPacketSize - Break - EndIf - BatchSize + MessageSize - - AddElement(Batch\Messages()) - Batch\Messages()\MessageId = Messages()\MessageId - ; As stored: when it was pushed to its origin, whichever server that was. - Batch\Messages()\PushedAt = Messages()\PushedAt - Batch\Messages()\JsonData = Messages()\JsonData - ; Its attachment's size and SHA-256 only: the data goes once the - ; messages are caught up (BakaShrot_PeerLink_SendAttachments()). - Batch\Messages()\AttachmentSize = Messages()\AttachmentSize - CopyMemory(@Messages()\AttachmentSha256[0], @Batch\Messages()\AttachmentSha256[0], #BakaShrot_Sha256Size) - Next - - If ListSize(Batch\Messages()) = 0 - FirstElement(Messages()) - PrintN("[Peer] Message " + TopicRef + ":" + NodeRef + "#" + Str(Messages()\MessageId) + " is too big to replicate to '" + *Link\Name + "', skipping the rest of this pair") - ProcedureReturn SentCount - EndIf - - Result = BakaShrot_PeerLink_SendBatch(*Link, @Batch) - If Result = -1 - ProcedureReturn -1 - EndIf - If Result = 0 - ProcedureReturn SentCount - EndIf - - SentCount + ListSize(Batch\Messages()) - LastElement(Batch\Messages()) - AfterMessageId = Batch\Messages()\MessageId - ForEver -EndProcedure - - -; #True if Name matches one of Patterns() (Commons/Networking/Names.pbi). -Procedure.i BakaShrot_MatchesAny(List Patterns.s(), Name.s) - ForEach Patterns() - If BakaShrot_GlobMatch(Patterns(), Name) - ProcedureReturn #True - EndIf - Next - ProcedureReturn #False -EndProcedure - - -; Asks the peer where it's at, and sends it the messages it's missing. -; Returns #False if the link must be dropped. -Procedure.i BakaShrot_PeerLink_CheckIn(*Link.BakaShrot_PeerLink) - Protected *Links.BakaShrot_PeerLinks = *Link\Links - Protected Request.BakaShrot_SyncStateRequest - Protected *State.BakaShrot_SyncState - Protected NewList LocalPairs.BakaShrot_SyncPair() - Protected NewMap RemoteTopics.i(), NewMap RemoteNodes.i() - Protected NewList RemoteTopicPatterns.s(), NewList RemoteNodePatterns.s() - Protected NewMap RemoteMessageIds.q() - Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer - Protected *View.MsgPackData, IsRefusal.i, Key.s, RemoteMessageId.q, SentCount.i, StartTime.i - Protected TopicRef.s, NodeRef.s, RemoteTopicId.i, RemoteNodeId.i - - ; 1. The peer's state - *Packet = BakaShrot_SyncStateRequestPacket_Encode(@Request, @PacketSize) - If Not *Packet - ProcedureReturn #False - EndIf - *Answer = BakaShrot_PeerLink_Request(*Link, *Packet, PacketSize\i, @AnswerSize) - FreeMemory(*Packet) - If Not *Answer - PrintN("[Peer] '" + *Link\Name + "' didn't answer the check-in") - ProcedureReturn #False - EndIf - - If BakaShrot_GetPacketType(*Answer, AnswerSize\i) = #BakaShrot_PacketType_RequestRefused - IsRefusal = BakaShrot_PeerLink_LogRefusal(*Link, *Answer, AnswerSize\i) - FreeMemory(*Answer) - ProcedureReturn IsRefusal - EndIf - - *State = 0 - *View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i) - If *View - *State = BakaShrot_SyncStatePacket_Decode(*View) - MsgPackFree(*View, #False) - EndIf - FreeMemory(*Answer) - If Not *State - PrintN("[Peer] '" + *Link\Name + "' sent an invalid sync state") - ProcedureReturn #False - EndIf - - ; The peer's ids, by LCase(name): every name it knows. - ForEach *State\Topics() - RemoteTopics(LCase(*State\Topics()\Name)) = *State\Topics()\Id - Next - ForEach *State\Nodes() - RemoteNodes(LCase(*State\Nodes()\Name)) = *State\Nodes()\Id - Next - ; And what it takes without having it yet. - CopyList(*State\TopicPatterns(), RemoteTopicPatterns()) - CopyList(*State\NodePatterns(), RemoteNodePatterns()) - ForEach *State\Pairs() - RemoteMessageIds(Str(*State\Pairs()\TopicId) + ":" + Str(*State\Pairs()\NodeId)) = *State\Pairs()\MessageId - Next - FreeStructure(*State) - - ; 2. This server's state - If Not GetSyncState(*Link\DbId, LocalPairs()) - PrintN("[Peer] Failed to read the sync state for '" + *Link\Name + "': " + DatabaseError()) - ProcedureReturn #True - EndIf - - ; 3. The delta, matching this server's topics and nodes to the peer's by - ; name. Anything not named on both sides is dropped, unless a wildcard - ; of the peer takes it. - ForEach LocalPairs() - TopicRef = BakaShrot_Names_TopicName(LocalPairs()\TopicId) - NodeRef = BakaShrot_Names_NodeName(LocalPairs()\NodeId) - If Not NameSetHas(@*Link\SendTopics, LocalPairs()\TopicId, TopicRef) Or Not NameSetHas(@*Link\SendNodes, LocalPairs()\NodeId, NodeRef) - Continue - EndIf - - If TopicRef = "" - BakaShrot_Names_NoteDropped(*Link\Name, "topic", Str(LocalPairs()\TopicId), "unnamed here") - Continue - EndIf - If NodeRef = "" - BakaShrot_Names_NoteDropped(*Link\Name, "node", Str(LocalPairs()\NodeId), "unnamed here") - Continue - EndIf - - ; -1: the peer doesn't have it yet, but a wildcard of its takes it. - RemoteTopicId = -1 - If FindMapElement(RemoteTopics(), LCase(TopicRef)) - RemoteTopicId = RemoteTopics() - ElseIf Not BakaShrot_MatchesAny(RemoteTopicPatterns(), TopicRef) - BakaShrot_Names_NoteDropped(*Link\Name, "topic", TopicRef, "not taken by the peer") - Continue - EndIf - RemoteNodeId = -1 - If FindMapElement(RemoteNodes(), LCase(NodeRef)) - RemoteNodeId = RemoteNodes() - ElseIf Not BakaShrot_MatchesAny(RemoteNodePatterns(), NodeRef) - BakaShrot_Names_NoteDropped(*Link\Name, "node", NodeRef, "not taken by the peer") - Continue - EndIf - - RemoteMessageId = 0 - If RemoteTopicId >= 0 And RemoteNodeId >= 0 And FindMapElement(RemoteMessageIds(), Str(RemoteTopicId) + ":" + Str(RemoteNodeId)) - RemoteMessageId = RemoteMessageIds() - EndIf - - Key = TopicRef + ":" + NodeRef - If LocalPairs()\MessageId > RemoteMessageId - StartTime = ElapsedMilliseconds() - SentCount = BakaShrot_PeerLink_SendMissing(*Link, LocalPairs()\TopicId, LocalPairs()\NodeId, TopicRef, NodeRef, RemoteMessageId) - If SentCount < 0 - ProcedureReturn #False - EndIf - If SentCount > 0 - PrintN("[Peer] Sent " + Str(SentCount) + " messages of " + Key + " to '" + *Link\Name + "' in " + Str(ElapsedMilliseconds() - StartTime) + " ms, it had up to #" + Str(RemoteMessageId)) - EndIf - EndIf - Next - - ; 4. Then the attachments: only for messages the peer has now. - ProcedureReturn BakaShrot_PeerLink_SendAttachments(*Link) -EndProcedure - - -; Keeps a linked peer's connection, checking in every sync interval, until it -; drops, a check-in fails, the peer sends something unasked, or the server is -; stopping. The connection is closed when it returns. -Procedure BakaShrot_PeerLink_StayLinked(*Link.BakaShrot_PeerLink) - Protected *Links.BakaShrot_PeerLinks = *Link\Links - Protected LastCheckIn.i - - ; Checks in right away. - LastCheckIn = ElapsedMilliseconds() - *Links\SyncIntervalMs - - While Not *Links\StopRequested - If ElapsedMilliseconds() - LastCheckIn >= *Links\SyncIntervalMs - If Not BakaShrot_PeerLink_CheckIn(*Link) - PrintN("[Peer] Dropping the link to '" + *Link\Name + "', the check-in failed") - BakaShrot_Outbound_Close(@*Link\Outbound, #BakaShrot_ConnectionStatus_Aborted) - ProcedureReturn - EndIf - LastCheckIn = ElapsedMilliseconds() - EndIf - - Select NetworkClientEvent(*Link\Outbound\ConnectionId) - - Case #PB_NetworkEvent_Data - PrintN("[Peer] '" + *Link\Name + "' sent a packet it wasn't asked for") - BakaShrot_Outbound_Close(@*Link\Outbound, #BakaShrot_ConnectionStatus_Aborted) - ProcedureReturn - - Case #PB_NetworkEvent_Disconnect - PrintN("[Peer] Lost the link to '" + *Link\Name + "'") - BakaShrot_Outbound_Close(@*Link\Outbound, #BakaShrot_ConnectionStatus_Disconnected) - ProcedureReturn - - Default - Delay(50) - - EndSelect - Wend - - BakaShrot_Outbound_Close(@*Link\Outbound, #BakaShrot_ConnectionStatus_Disconnected) -EndProcedure - - -Procedure BakaShrot_PeerLink_Thread(*Link.BakaShrot_PeerLink) - Protected *Links.BakaShrot_PeerLinks = *Link\Links - Protected Target.s = "'" + *Link\Name + "' (" + *Link\Host + ":" + Str(*Link\Port) + ")" - - *Link\DbId = OpenStorageDatabase(*Links\DatabasePath) - If Not *Link\DbId - PrintN("[Peer] Failed to open the database for " + Target + ", not linking to it: " + DatabaseError()) - ProcedureReturn - EndIf - - ; Waits for the peer's answers stop early when the server is stopping. - *Link\Outbound\StopRequested = @*Links\StopRequested - - While Not *Links\StopRequested - If BakaShrot_Outbound_Connect(@*Link\Outbound, *Link\Host, *Link\Port, @*Links\Identity, @*Link\ServerPublicKey[0]) - PrintN("[Peer] Linked to " + Target) - BakaShrot_PeerLink_StayLinked(*Link) - Else - PrintN("[Peer] Failed to link to " + Target + ", unreachable, or the handshake failed (is its PublicKey right?)") - EndIf - - If Not *Links\StopRequested - PrintN("[Peer] Retrying " + Target + " in " + Str(*Links\RetryDelayMs / 1000) + "s") - BakaShrot_PeerLink_WaitRetry(*Link) - EndIf - Wend - - CloseDatabase(*Link\DbId) - *Link\DbId = 0 -EndProcedure - - -; Stops every link's thread, closes their connections and frees *Links. -; Once it returns, no link thread is left, so none holds a database -; connection either. -; Waits for a peer's answer stop within a few ms, but a thread opening a -; connection is blocked in OpenNetworkConnection() until it succeeds or -; fails. -Procedure BakaShrot_PeerLinks_Stop(*Links.BakaShrot_PeerLinks) - *Links\StopRequested = #True - - ForEach *Links\Links() - If *Links\Links()\ThreadId - WaitThread(*Links\Links()\ThreadId) - EndIf - Next - - ; Don't leave the private key lying around in freed memory. - FillMemory(@*Links\PrivateKey[0], #BakaShrot_Ed25519_PrivateKeySize, 0) - FreeStructure(*Links) -EndProcedure - - -; Starts a link to every [BakaShrot.Peer.] in *Config, replicating -; the messages in its [BakaShrot.Server] DatabasePath. *Config must outlive -; the links. -; Returns 0 if *Config's PrivateKey is invalid or a thread couldn't start, -; stop the returned links with BakaShrot_PeerLinks_Stop(). -Procedure.i BakaShrot_PeerLinks_Start(*Config.BakaShrot_CoreConfig) - Protected *Links.BakaShrot_PeerLinks - - If Not InitCryptography() - ProcedureReturn 0 - EndIf - - *Links = AllocateStructure(BakaShrot_PeerLinks) - If Not *Links - ProcedureReturn 0 - EndIf - - ; Identity - If Not DecodeKeyFromString(*Config\PrivateKey, @*Links\PrivateKey[0], #BakaShrot_Ed25519_PrivateKeySize) - FreeStructure(*Links) - ProcedureReturn 0 - EndIf - GetPublicKeyFromPrivateKey(@*Links\PrivateKey[0], @*Links\PublicKey[0]) - - ; By name: the peer has its own ids for them. - *Links\Identity\Node = BakaShrot_Names_NodeRef(*Config\NodeId) - *Links\Identity\PublicKey = EncodeKeyToString(@*Links\PublicKey[0], #BakaShrot_Ed25519_PublicKeySize) - *Links\Identity\PrivateKey = @*Links\PrivateKey[0] - - *Links\DatabasePath = *Config\Server\DatabasePath - - *Links\RetryDelayMs = *Config\Server\PeerRetryDelay * 1000 - If *Links\RetryDelayMs < 1000 - *Links\RetryDelayMs = 1000 - EndIf - - *Links\SyncIntervalMs = *Config\Server\PeerSyncInterval * 1000 - If *Links\SyncIntervalMs < 1000 - *Links\SyncIntervalMs = 1000 - EndIf - - *Links\BatchSize = *Config\Server\PeerBatchSize - If *Links\BatchSize < 1 - *Links\BatchSize = 1 - EndIf - If *Links\BatchSize > #BakaShrot_MaxReplicateBatch - *Links\BatchSize = #BakaShrot_MaxReplicateBatch - EndIf - - ; Links - ForEach *Config\Peers() - AddElement(*Links\Links()) - *Links\Links()\Links = *Links - *Links\Links()\Name = MapKey(*Config\Peers()) - *Links\Links()\Host = *Config\Peers()\Host - *Links\Links()\Port = *Config\Peers()\Port - If Not DecodeKeyFromString(*Config\Peers()\PublicKey, @*Links\Links()\ServerPublicKey[0], #BakaShrot_Ed25519_PublicKeySize) - PrintN("[Peer] [BakaShrot.Peer." + MapKey(*Config\Peers()) + "] PublicKey is missing or invalid") - BakaShrot_PeerLinks_Stop(*Links) - ProcedureReturn 0 - EndIf - CopyStructure(@*Config\Peers()\SendTopics, @*Links\Links()\SendTopics, BakaShrot_NameSet) - CopyStructure(@*Config\Peers()\SendNodes, @*Links\Links()\SendNodes, BakaShrot_NameSet) - - ; List elements never move, so the thread can keep this pointer. - *Links\Links()\ThreadId = CreateThread(@BakaShrot_PeerLink_Thread(), @*Links\Links()) - If Not *Links\Links()\ThreadId - BakaShrot_PeerLinks_Stop(*Links) - ProcedureReturn 0 - EndIf - Next - - ProcedureReturn *Links -EndProcedure diff --git a/Server/Root.pbi b/Server/Root.pbi deleted file mode 100644 index f03ee95..0000000 --- a/Server/Root.pbi +++ /dev/null @@ -1,256 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: Root.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; BakaShrot Server Root -; -; What the main ("root") thread owns and does: -; - The config. -; - Its own database connection: setup, and maintenance while the workers -; are stopped. -; - The workers: the network server (its listener and one thread per -; client, see Networking/Networking.pbi) and the peer links (one thread -; per peer, see Networking/Peers.pbi). -; -; Stopping the workers is the root's signal to every other thread. -; BakaShrot_Root_StopWorkers() sets the StopRequested flag of the network -; server and the peer links, which every one of their threads checks within a -; few ms, then waits until each of those threads has exited. Each one closes -; its own database connection on its way out. So once it returns, the root's -; connection is the only one left, and the root can: -; - BakaShrot_Root_Restart(): reload the config, reopen the database, start -; again. Picks up config changes, like a client's permissions. -; - BakaShrot_Root_Vacuum(): VACUUM the database, start again. -; - Anything else that needs the database or the config to itself. -; Clients and peer links are dropped meanwhile. Peers relink on their own, -; clients have to reconnect. -; -; Only call these from the root thread. -; ============================================================================ - -XIncludeFile "Config/Config.pbi" -XIncludeFile "Storage/Storage.pbi" -XIncludeFile "Storage/Names.pbi" -XIncludeFile "Storage/Retention.pbi" -XIncludeFile "Networking/Networking.pbi" -XIncludeFile "Networking/Peers.pbi" - - -Structure BakaShrot_Root - ConfigPath.s - *Config.BakaShrot_CoreConfig - - ; The root's own connection, only used for setup, and while the workers - ; are stopped. - DbId.i - - ; Both 0 while the workers are stopped. - *Server.BakaShrot_NetServer - *Peers.BakaShrot_PeerLinks -EndStructure - - -; Loads *Root\ConfigPath into *Root\Config, replacing the current one. -; Returns #False if it can't be loaded, the current one is then kept. -; Only while the workers are stopped, they use the config. -Procedure.i BakaShrot_Root_LoadConfig(*Root.BakaShrot_Root) - Protected *Config.BakaShrot_CoreConfig - Protected Known.BakaShrot_KnownNames, KnownError.String, DatabasePath.s, DbId.i - - ; The names the database has first, so the ones the config lists without - ; an id keep theirs (Storage/Names.pbi). Nothing to read on a new one. - DatabasePath = ReadConfigDatabasePath(*Root\ConfigPath) - If DatabasePath <> "" And FileSize(DatabasePath) > 0 - DbId = OpenStorageDatabase(DatabasePath) - If Not DbId Or Not SetupStorageDatabase(DbId) Or Not BakaShrot_Names_ReadKnown(DbId, @Known, @KnownError) - PrintN("[Root] Failed to read the names of the database '" + DatabasePath + "': " + KnownError\s + DatabaseError()) - If DbId - CloseDatabase(DbId) - EndIf - ProcedureReturn #False - EndIf - CloseDatabase(DbId) - EndIf - - *Config = LoadConfig(*Root\ConfigPath, @Known) - If Not *Config - PrintN("[Root] Failed to load the config from '" + *Root\ConfigPath + "': " + BakaShrot_ConfigError) - ProcedureReturn #False - EndIf - - If *Root\Config - FreeConfig(*Root\Config) - EndIf - *Root\Config = *Config - - PrintN("[Root] Loaded config '" + *Root\ConfigPath + "' (Node=" + *Config\NodeText + ", " + Str(MapSize(*Config\TopicNames())) + " named topics, " + - Str(MapSize(*Config\NodeNames())) + " named nodes, " + Str(MapSize(*Config\Peers())) + " peers, " + Str(MapSize(*Config\Clients())) + " clients)") - ProcedureReturn #True -EndProcedure - - -; Opens the root's connection to the config's database, sets it up, and -; reconciles the config's topic and node names with it (Storage/Names.pbi). -; Returns #False if it can't be opened or set up, or if the names conflict. -Procedure.i BakaShrot_Root_OpenDatabase(*Root.BakaShrot_Root) - Protected DatabasePath.s = *Root\Config\Server\DatabasePath - Protected NamesError.String - - ; Every connection opened from here on, the workers' included (they're - ; stopped meanwhile), takes it. - BakaShrot_Storage_Synchronous = *Root\Config\Server\Synchronous - - *Root\DbId = OpenStorageDatabase(DatabasePath) - If Not *Root\DbId - PrintN("[Root] Failed to open the database '" + DatabasePath + "': " + DatabaseError()) - ProcedureReturn #False - EndIf - - If Not SetupStorageDatabase(*Root\DbId) - PrintN("[Root] Failed to set up the database '" + DatabasePath + "': " + DatabaseError()) - CloseDatabase(*Root\DbId) - *Root\DbId = 0 - ProcedureReturn #False - EndIf - - If Not BakaShrot_Names_Load(*Root\DbId, *Root\Config, @NamesError) - PrintN("[Root] The config's names don't match the database '" + DatabasePath + "': " + NamesError\s) - CloseDatabase(*Root\DbId) - *Root\DbId = 0 - ProcedureReturn #False - EndIf - - PrintN("[Root] Database '" + DatabasePath + "' is ready (synchronous " + BakaShrot_Storage_Synchronous + ")") - ProcedureReturn #True -EndProcedure - - -Procedure BakaShrot_Root_CloseDatabase(*Root.BakaShrot_Root) - If *Root\DbId - CloseDatabase(*Root\DbId) - *Root\DbId = 0 - EndIf -EndProcedure - - -; Starts the network server and the peer links. -; Returns #False if either can't start, nothing is left running then. -Procedure.i BakaShrot_Root_StartWorkers(*Root.BakaShrot_Root) - Protected *Config.BakaShrot_CoreConfig = *Root\Config - Protected WriterError.String - - ; Every write goes through it, see Storage/Writer.pbi. - If Not OpenStorageWriter(*Config\Server\DatabasePath, @WriterError) - PrintN("[Root] Failed to open the storage writer: " + WriterError\s) - ProcedureReturn #False - EndIf - - ; Deletes the messages past their topic's max age, see Storage/Retention.pbi. - If Not StartStorageRetention(*Config) - PrintN("[Root] Failed to start the retention thread") - CloseStorageWriter() - ProcedureReturn #False - EndIf - - *Root\Server = BakaShrot_NetServer_Start(*Config\Server\Host, *Config\Server\Port, *Config) - If Not *Root\Server - PrintN("[Root] Failed to listen on '" + *Config\Server\Host + ":" + Str(*Config\Server\Port) + "'") - StopStorageRetention() - CloseStorageWriter() - ProcedureReturn #False - EndIf - PrintN("[Root] Listening on '" + *Config\Server\Host + ":" + Str(*Config\Server\Port) + "'") - - *Root\Peers = BakaShrot_PeerLinks_Start(*Config) - If Not *Root\Peers - PrintN("[Root] Failed to start the peer links, are [BakaShrot] PrivateKey and every peer's PublicKey valid?") - BakaShrot_NetServer_Stop(*Root\Server) - *Root\Server = 0 - StopStorageRetention() - CloseStorageWriter() - ProcedureReturn #False - EndIf - - ProcedureReturn #True -EndProcedure - - -; The signal: stops every worker thread and waits until they've all exited, -; which closes every database connection but the root's own. -; Peer links first, so they don't relink to a server that's going away. -Procedure BakaShrot_Root_StopWorkers(*Root.BakaShrot_Root) - Protected StartTime.i = ElapsedMilliseconds() - - If *Root\Peers - BakaShrot_PeerLinks_Stop(*Root\Peers) - *Root\Peers = 0 - EndIf - - If *Root\Server - BakaShrot_NetServer_Stop(*Root\Server) - *Root\Server = 0 - EndIf - - StopStorageRetention() - - ; Nothing writes anymore. Checkpoints the WAL into the database file. - CloseStorageWriter() - - PrintN("[Root] Workers stopped in " + Str(ElapsedMilliseconds() - StartTime) + " ms") -EndProcedure - - -; Stops the workers, reloads the config (keeping the current one if the new -; one can't be loaded), reopens the database, and starts the workers again. -; Returns #False if the database can't be reopened or the workers can't -; start again, the server is then left stopped. -Procedure.i BakaShrot_Root_Restart(*Root.BakaShrot_Root) - PrintN("[Root] Restarting") - BakaShrot_Root_StopWorkers(*Root) - - If Not BakaShrot_Root_LoadConfig(*Root) - PrintN("[Root] Keeping the current config") - EndIf - - ; The database path may have changed. - BakaShrot_Root_CloseDatabase(*Root) - If Not BakaShrot_Root_OpenDatabase(*Root) - ProcedureReturn #False - EndIf - - ProcedureReturn BakaShrot_Root_StartWorkers(*Root) -EndProcedure - - -; Stops the workers, VACUUMs the database, and starts the workers again. -; Returns #False if the workers can't start again, a failed VACUUM is only -; logged. -Procedure.i BakaShrot_Root_Vacuum(*Root.BakaShrot_Root) - Protected StartTime.i - - PrintN("[Root] Vacuuming the database") - BakaShrot_Root_StopWorkers(*Root) - - StartTime = ElapsedMilliseconds() - If VacuumStorageDatabase(*Root\DbId) - PrintN("[Root] Vacuumed in " + Str(ElapsedMilliseconds() - StartTime) + " ms") - Else - PrintN("[Root] Failed to vacuum: " + DatabaseError()) - EndIf - - ProcedureReturn BakaShrot_Root_StartWorkers(*Root) -EndProcedure diff --git a/Server/Storage/Attachments.pbi b/Server/Storage/Attachments.pbi deleted file mode 100644 index 31647c3..0000000 --- a/Server/Storage/Attachments.pbi +++ /dev/null @@ -1,467 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: Attachments.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; BakaShrot Storage Attachments -; -; A message has at most one attachment, of any size up to the server's -; MaxAttachmentSize, stored in parts (Design/Attachments.md): -; blobs the data of one attachment, being received or stored -; blob_chunks its parts, #BakaShrot_AttachmentChunkSize bytes each, the -; last one what's left -; attachments a message's: its size and SHA-256, and its blob once any -; of it is here -; See SetupStorageDatabase() in Storage.pbi for the columns and states. -; -; Pushed with a message: -; CreateStorageBlob() an upload starts (state 0), owned by the -; client's topic and node -; StoreStorageBlobChunk() each part, in order -; HashStorageBlob() once all of it is here, checked against the -; SHA-256 given at the start: complete (1), or -; dropped (3) -; then InsertNextMessage() (Writer.pbi) with its blob id attaches it to -; the message, in the same transaction (2). -; Replicated: the message comes first (ReplicateMessages), its attachments -; row in state 0, then once the messages are caught up: -; GetMissingStorageAttachments() what's missing, or started -; StartReplicatedAttachment() the first part makes its blob -; StoreStorageBlobChunk() each part, resuming where it stopped -; FinishReplicatedAttachment() ready (2), or back to missing if its -; SHA-256 doesn't match -; Deleting a message (the retention) deletes its attachments row (trigger), -; which marks its blob (3); CleanUpStorageBlobs() deletes it a part at a -; time, along with uploads never completed or never attached. -; -; Writes go through the writer (Writer.pbi), under its mutex; reads take -; the caller's own connection. -; ============================================================================ - -; SHA-256 (BakaShrot_Sha256_*). -XIncludeFile "../../Commons/Cryptography/Libsodium.pbi" - - -Structure BakaShrot_StorageBlob - BlobId.q - TopicId.i - NodeId.i - Size.q - Sha256.a[#BakaShrot_Sha256Size] - Received.q - State.i -EndStructure - -Structure BakaShrot_StorageAttachment - Size.q - Sha256.a[#BakaShrot_Sha256Size] - ; 0 while none of it is here. - BlobId.q - ; 0 missing, 1 receiving, 2 ready, 3 not kept here. - State.i - ; Of its blob, 0 without one. - Received.q -EndStructure - -Structure BakaShrot_StorageMissingAttachment - TopicId.i - NodeId.i - Topic.s - Node.s - MessageId.q - Received.q -EndStructure - -#BakaShrot_Blob_Receiving = 0 -#BakaShrot_Blob_Complete = 1 -#BakaShrot_Blob_Attached = 2 -#BakaShrot_Blob_Deleted = 3 - -#BakaShrot_Attachment_Missing = 0 -#BakaShrot_Attachment_Receiving = 1 -#BakaShrot_Attachment_Ready = 2 -#BakaShrot_Attachment_NotKept = 3 - - -; --- Reads, on the caller's connection ----------------------------------------- - -; Fills *Blob with blob BlobId. Returns #False if there's none. -Procedure.i GetStorageBlob(DbId.i, BlobId.q, *Blob.BakaShrot_StorageBlob) - Protected Found.i - - SetDatabaseQuad(DbId, 0, BlobId) - If Not DatabaseQuery(DbId, "SELECT topic_id, node_id, size, sha256, received, state FROM blobs WHERE blob_id = ?") - ProcedureReturn #False - EndIf - Found = NextDatabaseRow(DbId) - If Found - *Blob\BlobId = BlobId - *Blob\TopicId = GetDatabaseLong(DbId, 0) - *Blob\NodeId = GetDatabaseLong(DbId, 1) - *Blob\Size = GetDatabaseQuad(DbId, 2) - FillMemory(@*Blob\Sha256[0], #BakaShrot_Sha256Size, 0) - If DatabaseColumnSize(DbId, 3) = #BakaShrot_Sha256Size - GetDatabaseBlob(DbId, 3, @*Blob\Sha256[0], #BakaShrot_Sha256Size) - EndIf - *Blob\Received = GetDatabaseQuad(DbId, 4) - *Blob\State = GetDatabaseLong(DbId, 5) - EndIf - FinishDatabaseQuery(DbId) - ProcedureReturn Found -EndProcedure - - -; Fills *Attachment with the attachment of TopicId:NodeId#MessageId. -; Returns #False if that message has none (or doesn't exist). -Procedure.i GetStorageAttachment(DbId.i, TopicId.i, NodeId.i, MessageId.q, *Attachment.BakaShrot_StorageAttachment) - Protected Found.i - - SetDatabaseLong(DbId, 0, TopicId) - SetDatabaseLong(DbId, 1, NodeId) - SetDatabaseQuad(DbId, 2, MessageId) - If Not DatabaseQuery(DbId, "SELECT a.size, a.sha256, COALESCE(a.blob_id, 0), a.state, COALESCE(b.received, 0) " + - "FROM attachments a LEFT JOIN blobs b ON b.blob_id = a.blob_id " + - "WHERE a.topic_id = ? AND a.node_id = ? AND a.message_id = ?") - ProcedureReturn #False - EndIf - Found = NextDatabaseRow(DbId) - If Found - *Attachment\Size = GetDatabaseQuad(DbId, 0) - FillMemory(@*Attachment\Sha256[0], #BakaShrot_Sha256Size, 0) - If DatabaseColumnSize(DbId, 1) = #BakaShrot_Sha256Size - GetDatabaseBlob(DbId, 1, @*Attachment\Sha256[0], #BakaShrot_Sha256Size) - EndIf - *Attachment\BlobId = GetDatabaseQuad(DbId, 2) - *Attachment\State = GetDatabaseLong(DbId, 3) - *Attachment\Received = GetDatabaseQuad(DbId, 4) - EndIf - FinishDatabaseQuery(DbId) - ProcedureReturn Found -EndProcedure - - -; Part Index of blob BlobId, in a freshly allocated buffer, its size in -; *OutSize\i. Returns 0 if it isn't stored. The caller frees it. -Procedure.i ReadStorageBlobChunk(DbId.i, BlobId.q, Index.q, *OutSize.Integer) - Protected *Data, Size.i - - SetDatabaseQuad(DbId, 0, BlobId) - SetDatabaseQuad(DbId, 1, Index) - If Not DatabaseQuery(DbId, "SELECT chunk_data FROM blob_chunks WHERE blob_id = ? AND chunk_index = ?") - ProcedureReturn 0 - EndIf - If NextDatabaseRow(DbId) - Size = DatabaseColumnSize(DbId, 0) - If Size > 0 - *Data = AllocateMemory(Size, #PB_Memory_NoClear) - If *Data - GetDatabaseBlob(DbId, 0, *Data, Size) - *OutSize\i = Size - EndIf - EndIf - EndIf - FinishDatabaseQuery(DbId) - ProcedureReturn *Data -EndProcedure - - -; Reads all of blob BlobId back (Size bytes, in parts) and checks its SHA-256 -; is *Sha256. Returns #False if it isn't, or a part is missing or the wrong -; size. ~3 s per GB. -Procedure.i HashStorageBlob(DbId.i, BlobId.q, Size.q, *Sha256) - Protected Hash.BakaShrot_Sha256, Index.q, Count.q, *Data, DataSize.Integer - Protected Dim Result.a(#BakaShrot_Sha256Size - 1) - - If Not BakaShrot_Sha256_Start(@Hash) - ProcedureReturn #False - EndIf - Count = BakaShrot_AttachmentChunkCount(Size) - For Index = 0 To Count - 1 - *Data = ReadStorageBlobChunk(DbId, BlobId, Index, @DataSize) - If Not *Data - ProcedureReturn #False - EndIf - If DataSize\i <> BakaShrot_AttachmentChunkBytes(Size, Index) - FreeMemory(*Data) - ProcedureReturn #False - EndIf - BakaShrot_Sha256_Add(@Hash, *Data, DataSize\i) - FreeMemory(*Data) - Next - BakaShrot_Sha256_Finish(@Hash, @Result(0)) - ProcedureReturn CompareMemory(@Result(0), *Sha256, #BakaShrot_Sha256Size) -EndProcedure - - -; Fills Missing() with attachments of messages here that aren't all here -; yet (missing or receiving), with their topic and node names, up to Limit. -; Unnamed topics or nodes are left out: replication goes by name. -; Returns #False if the query failed. -Procedure.i GetMissingStorageAttachments(DbId.i, Limit.i, List Missing.BakaShrot_StorageMissingAttachment()) - ClearList(Missing()) - SetDatabaseLong(DbId, 0, Limit) - If Not DatabaseQuery(DbId, "SELECT a.topic_id, a.node_id, t.name, n.name, a.message_id, COALESCE(b.received, 0) " + - "FROM attachments a JOIN topics t ON t.topic_id = a.topic_id JOIN nodes n ON n.node_id = a.node_id " + - "LEFT JOIN blobs b ON b.blob_id = a.blob_id " + - "WHERE a.state IN (0, 1) ORDER BY a.topic_id, a.node_id, a.message_id LIMIT ?") - ProcedureReturn #False - EndIf - While NextDatabaseRow(DbId) - AddElement(Missing()) - Missing()\TopicId = GetDatabaseLong(DbId, 0) - Missing()\NodeId = GetDatabaseLong(DbId, 1) - Missing()\Topic = GetDatabaseString(DbId, 2) - Missing()\Node = GetDatabaseString(DbId, 3) - Missing()\MessageId = GetDatabaseQuad(DbId, 4) - Missing()\Received = GetDatabaseQuad(DbId, 5) - Wend - FinishDatabaseQuery(DbId) - ProcedureReturn #True -EndProcedure - - -; --- Writes, through the writer ------------------------------------------------ - -; Starts an upload for TopicId/NodeId: Size bytes whose SHA-256 is *Sha256. -; Returns its blob id, 0 with the reason in *Error\s. -Procedure.q CreateStorageBlob(TopicId.i, NodeId.i, Size.q, *Sha256, *Error.String) - Protected DbId.i, BlobId.q - - LockMutex(BakaShrot_Storage_WriteMutex) - DbId = BakaShrot_Storage_Writer\DbId - If Not DbId - UnlockMutex(BakaShrot_Storage_WriteMutex) - *Error\s = "the storage writer isn't open" - ProcedureReturn 0 - EndIf - - SetDatabaseLong(DbId, 0, TopicId) - SetDatabaseLong(DbId, 1, NodeId) - SetDatabaseQuad(DbId, 2, Size) - SetDatabaseBlob(DbId, 3, *Sha256, #BakaShrot_Sha256Size) - SetDatabaseQuad(DbId, 4, BakaShrot_NowUtcMs()) - If DatabaseUpdate(DbId, "INSERT INTO blobs (topic_id, node_id, size, sha256, received, state, created_at) VALUES (?, ?, ?, ?, 0, 0, ?)") - If DatabaseQuery(DbId, "SELECT last_insert_rowid()") - If NextDatabaseRow(DbId) - BlobId = GetDatabaseQuad(DbId, 0) - EndIf - FinishDatabaseQuery(DbId) - EndIf - EndIf - If Not BlobId - *Error\s = DatabaseError() - EndIf - - UnlockMutex(BakaShrot_Storage_WriteMutex) - ProcedureReturn BlobId -EndProcedure - - -; Stores part Index (DataSize bytes at *Data) of blob BlobId, which must be -; the next one: Index * #BakaShrot_AttachmentChunkSize bytes received so far. -; Returns how many are received now, -1 with the reason in *Error\s (nothing -; stored then). -Procedure.q StoreStorageBlobChunk(BlobId.q, Index.q, *Data, DataSize.i, *Error.String) - Protected DbId.i, Received.q = -1, Ok.i - - LockMutex(BakaShrot_Storage_WriteMutex) - DbId = BakaShrot_Storage_Writer\DbId - If Not DbId - UnlockMutex(BakaShrot_Storage_WriteMutex) - *Error\s = "the storage writer isn't open" - ProcedureReturn -1 - EndIf - - If DatabaseUpdate(DbId, "BEGIN IMMEDIATE") - ; Only if it's the next one, and the blob is still being received. - SetDatabaseQuad(DbId, 0, DataSize) - SetDatabaseQuad(DbId, 1, BlobId) - SetDatabaseQuad(DbId, 2, Index * #BakaShrot_AttachmentChunkSize) - Ok = DatabaseUpdate(DbId, "UPDATE blobs SET received = received + ? WHERE blob_id = ? AND received = ? AND state = 0") - If Ok And AffectedDatabaseRows(DbId) <> 1 - Ok = #False - *Error\s = "not the next part, or not being received" - ElseIf Not Ok - *Error\s = DatabaseError() - EndIf - If Ok - SetDatabaseQuad(DbId, 0, BlobId) - SetDatabaseQuad(DbId, 1, Index) - SetDatabaseBlob(DbId, 2, *Data, DataSize) - Ok = DatabaseUpdate(DbId, "INSERT INTO blob_chunks (blob_id, chunk_index, chunk_data) VALUES (?, ?, ?)") - If Not Ok - *Error\s = DatabaseError() - EndIf - EndIf - If Ok And DatabaseUpdate(DbId, "COMMIT") - Received = Index * #BakaShrot_AttachmentChunkSize + DataSize - Else - If Ok - *Error\s = DatabaseError() - EndIf - DatabaseUpdate(DbId, "ROLLBACK") - EndIf - Else - *Error\s = DatabaseError() - EndIf - - UnlockMutex(BakaShrot_Storage_WriteMutex) - ProcedureReturn Received -EndProcedure - - -; Sets blob BlobId's state (#BakaShrot_Blob_*). Returns #False if it failed. -Procedure.i SetStorageBlobState(BlobId.q, State.i) - Protected DbId.i, Ok.i - - LockMutex(BakaShrot_Storage_WriteMutex) - DbId = BakaShrot_Storage_Writer\DbId - If DbId - SetDatabaseLong(DbId, 0, State) - SetDatabaseQuad(DbId, 1, BlobId) - Ok = DatabaseUpdate(DbId, "UPDATE blobs SET state = ? WHERE blob_id = ?") - EndIf - UnlockMutex(BakaShrot_Storage_WriteMutex) - ProcedureReturn Ok -EndProcedure - - -; Makes the blob of a replicated attachment that's still missing (state 0), -; from its row's size and SHA-256, and links it: receiving (1). -; Returns its blob id, 0 with the reason in *Error\s. -Procedure.q StartReplicatedAttachment(TopicId.i, NodeId.i, MessageId.q, *Error.String) - Protected DbId.i, BlobId.q, Ok.i - - LockMutex(BakaShrot_Storage_WriteMutex) - DbId = BakaShrot_Storage_Writer\DbId - If Not DbId - UnlockMutex(BakaShrot_Storage_WriteMutex) - *Error\s = "the storage writer isn't open" - ProcedureReturn 0 - EndIf - - If DatabaseUpdate(DbId, "BEGIN IMMEDIATE") - SetDatabaseLong(DbId, 0, TopicId) - SetDatabaseLong(DbId, 1, NodeId) - SetDatabaseQuad(DbId, 2, BakaShrot_NowUtcMs()) - SetDatabaseLong(DbId, 3, TopicId) - SetDatabaseLong(DbId, 4, NodeId) - SetDatabaseQuad(DbId, 5, MessageId) - Ok = DatabaseUpdate(DbId, "INSERT INTO blobs (topic_id, node_id, size, sha256, received, state, created_at) " + - "SELECT ?, ?, size, sha256, 0, 0, ? FROM attachments WHERE topic_id = ? AND node_id = ? AND message_id = ? AND state = 0 AND blob_id IS NULL") - If Ok And AffectedDatabaseRows(DbId) = 1 And DatabaseQuery(DbId, "SELECT last_insert_rowid()") - If NextDatabaseRow(DbId) - BlobId = GetDatabaseQuad(DbId, 0) - EndIf - FinishDatabaseQuery(DbId) - EndIf - If BlobId - SetDatabaseQuad(DbId, 0, BlobId) - SetDatabaseLong(DbId, 1, TopicId) - SetDatabaseLong(DbId, 2, NodeId) - SetDatabaseQuad(DbId, 3, MessageId) - Ok = DatabaseUpdate(DbId, "UPDATE attachments SET blob_id = ?, state = 1 WHERE topic_id = ? AND node_id = ? AND message_id = ?") - EndIf - If BlobId And Ok And DatabaseUpdate(DbId, "COMMIT") - ; Done. - Else - *Error\s = DatabaseError() - If *Error\s = "" - *Error\s = "the attachment isn't missing" - EndIf - DatabaseUpdate(DbId, "ROLLBACK") - BlobId = 0 - EndIf - Else - *Error\s = DatabaseError() - EndIf - - UnlockMutex(BakaShrot_Storage_WriteMutex) - ProcedureReturn BlobId -EndProcedure - - -; A replicated attachment is all here: ready (2) if its SHA-256 checked out -; (IsValid), else its blob is dropped and it's missing again (0), to be sent -; again from the start. Returns #False if it failed. -Procedure.i FinishReplicatedAttachment(TopicId.i, NodeId.i, MessageId.q, BlobId.q, IsValid.i) - Protected DbId.i, Ok.i - - LockMutex(BakaShrot_Storage_WriteMutex) - DbId = BakaShrot_Storage_Writer\DbId - If DbId And DatabaseUpdate(DbId, "BEGIN IMMEDIATE") - SetDatabaseQuad(DbId, 0, BlobId) - If IsValid - Ok = DatabaseUpdate(DbId, "UPDATE blobs SET state = 2 WHERE blob_id = ?") - Else - Ok = DatabaseUpdate(DbId, "UPDATE blobs SET state = 3 WHERE blob_id = ?") - EndIf - If Ok - SetDatabaseLong(DbId, 0, TopicId) - SetDatabaseLong(DbId, 1, NodeId) - SetDatabaseQuad(DbId, 2, MessageId) - If IsValid - Ok = DatabaseUpdate(DbId, "UPDATE attachments SET state = 2 WHERE topic_id = ? AND node_id = ? AND message_id = ?") - Else - Ok = DatabaseUpdate(DbId, "UPDATE attachments SET state = 0, blob_id = NULL WHERE topic_id = ? AND node_id = ? AND message_id = ?") - EndIf - EndIf - If Ok - Ok = DatabaseUpdate(DbId, "COMMIT") - EndIf - If Not Ok - DatabaseUpdate(DbId, "ROLLBACK") - EndIf - EndIf - UnlockMutex(BakaShrot_Storage_WriteMutex) - ProcedureReturn Ok -EndProcedure - - -; Marks uploads never completed nor attached, started before BeforeMs (ms -; since 1970 UTC), to delete, then deletes up to Limit parts of what's to -; delete, and the blobs left with none. Call it again while it returns -; Limit. Returns how many parts were deleted, -1 with the reason in *Error\s. -Procedure.i CleanUpStorageBlobs(BeforeMs.q, Limit.i, *Error.String) - Protected DbId.i, Deleted.i = -1 - - LockMutex(BakaShrot_Storage_WriteMutex) - DbId = BakaShrot_Storage_Writer\DbId - If Not DbId - UnlockMutex(BakaShrot_Storage_WriteMutex) - *Error\s = "the storage writer isn't open" - ProcedureReturn -1 - EndIf - - ; Uploads (no attachments row points to them) left behind. - SetDatabaseQuad(DbId, 0, BeforeMs) - If DatabaseUpdate(DbId, "UPDATE blobs SET state = 3 WHERE state IN (0, 1) AND created_at < ? " + - "AND NOT EXISTS (SELECT 1 FROM attachments a WHERE a.blob_id = blobs.blob_id)") - SetDatabaseLong(DbId, 0, Limit) - If DatabaseUpdate(DbId, "DELETE FROM blob_chunks WHERE rowid IN (SELECT c.rowid FROM blob_chunks c JOIN blobs b ON b.blob_id = c.blob_id WHERE b.state = 3 LIMIT ?)") - Deleted = AffectedDatabaseRows(DbId) - If Deleted < Limit - DatabaseUpdate(DbId, "DELETE FROM blobs WHERE state = 3 AND NOT EXISTS (SELECT 1 FROM blob_chunks c WHERE c.blob_id = blobs.blob_id)") - EndIf - EndIf - EndIf - If Deleted < 0 - *Error\s = DatabaseError() - EndIf - - UnlockMutex(BakaShrot_Storage_WriteMutex) - ProcedureReturn Deleted -EndProcedure diff --git a/Server/Storage/Names.pbi b/Server/Storage/Names.pbi deleted file mode 100644 index d208fb2..0000000 --- a/Server/Storage/Names.pbi +++ /dev/null @@ -1,548 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: Names.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; BakaShrot Storage Names -; -; Which name every topic and node id has on this server. Names are what's -; shared between servers (Commons/Networking/Names.pbi): replication sends -; them, and each server stores the messages under its own ids for them. Say -; topic "logs" is 1 here and 200 on a peer: the peer sends "logs", this -; server stores it under 1. Hand-written configs drift, the names keep them -; matching anyway. -; -; Only what's named on BOTH servers replicates: a topic or node without a -; name, or with a name the other server doesn't know, is dropped. Unless the -; receiver takes it by a wildcard: "*" or a pattern ("sensors.*") in that -; peer's AcceptTopics / AcceptNodes takes matching names it doesn't have, -; and adds them (BakaShrot_Names_Ingest(), origin "peer") under the highest -; free id counting down from 65535, out of the way of the ids picked in the -; config. To not be refused over and over, each check-in's sync state lists -; every name the receiver knows and takes, and its patterns, and the sender -; only sends those. Every drop goes through BakaShrot_Names_NoteDropped(). -; -; Kept in the "topics" and "nodes" tables (Storage.pbi), so raw queries can -; join on them (the "messages" view), and in memory for the server, guarded -; by BakaShrot_Names_Mutex. Every id in "data" has a row: -; origin "config" named by the config: in [BakaShrot.Topics] / -; [BakaShrot.Nodes], or a peer's or client's Node -; origin "id" unnamed, its name is its id in digits -; origin "peer" sent by a peer, taken by a wildcard, named by the peer -; -; Ids are this server's to pick: a name the config lists without one keeps -; the one these tables have for it, a new one gets the lowest free one -; (LoadConfig(), after BakaShrot_Names_ReadKnown()). The config may still -; pin one ("logs = 1"). -; -; BakaShrot_Names_Load() reconciles the config with the tables at start (and -; on restart). The config wins, except when it would give a name to another -; id than the one the database has it under (or rename a "peer" one): that -; would relabel stored messages, so the server refuses to start and says -; which id to use. -; -; Lock order: BakaShrot_Names_Mutex, then the write mutex (Writer.pbi). -; ============================================================================ - -XIncludeFile "../Config/Config.pbi" -XIncludeFile "Storage.pbi" -XIncludeFile "../../Commons/Networking/Packets/NamesListPacket.pbi" - - -#BakaShrot_Names_OriginConfig = "config" -#BakaShrot_Names_OriginPeer = "peer" -#BakaShrot_Names_OriginId = "id" - -; One of the two tables, in memory. -Structure BakaShrot_NameTable - Table.s - IdColumn.s - Kind.s - - ; LCase(name) -> id, named ones only. - Map IdByName.i() - - ; Str(id) -> name, "" if unnamed. Every id with a row. - Map NameById.s() - - ; Str(id) -> origin. - Map OriginById.s() -EndStructure - -Global BakaShrot_Names_Mutex.i = CreateMutex() -Global BakaShrot_Names_Topics.BakaShrot_NameTable -Global BakaShrot_Names_Nodes.BakaShrot_NameTable - -BakaShrot_Names_Topics\Table = "topics" -BakaShrot_Names_Topics\IdColumn = "topic_id" -BakaShrot_Names_Topics\Kind = "topic" -BakaShrot_Names_Nodes\Table = "nodes" -BakaShrot_Names_Nodes\IdColumn = "node_id" -BakaShrot_Names_Nodes\Kind = "node" - - -; --- Loading ----------------------------------------------------------------- - -; Reconciles one table with the config's names (ConfigNames: Str(id) -> -; name) and the ids it uses (UsedIds), plus every id already in "data" -; (node_heads), then fills *Names from it. -; Runs inside the transaction of BakaShrot_Names_Load(). -Procedure.i BakaShrot_Names_LoadTable(DbId.i, *Names.BakaShrot_NameTable, Map ConfigNames.s(), Map UsedIds.i(), *Error.String) - Protected NewMap DbName.s(), NewMap DbOrigin.s(), NewMap DbIdByName.i(), NewMap AllIds.i() - Protected Id.i, Name.s, Key.s, Section.s - - If *Names = @BakaShrot_Names_Topics - Section = "[BakaShrot.Topics]" - Else - Section = "[BakaShrot.Nodes]" - EndIf - - ; What the database has. - If Not DatabaseQuery(DbId, "SELECT " + *Names\IdColumn + ", name, origin FROM " + *Names\Table) - *Error\s = "can't read the " + *Names\Table + " table: " + DatabaseError() - ProcedureReturn #False - EndIf - While NextDatabaseRow(DbId) - Key = Str(GetDatabaseLong(DbId, 0)) - DbName(Key) = GetDatabaseString(DbId, 1) - DbOrigin(Key) = GetDatabaseString(DbId, 2) - If Not BakaShrot_IsDigits(DbName(Key)) - DbIdByName(LCase(DbName(Key))) = Val(Key) - EndIf - Wend - FinishDatabaseQuery(DbId) - - ; The config's names. - ForEach ConfigNames() - Key = MapKey(ConfigNames()) - Name = ConfigNames() - Id = Val(Key) - - If FindMapElement(DbIdByName(), LCase(Name)) And DbIdByName() <> Id - *Error\s = *Names\Kind + " '" + Name + "' is id " + Str(Id) + " in " + Section + ", but its messages are stored under id " + - Str(DbIdByName()) + ": give it id " + Str(DbIdByName()) + " in the config" - ProcedureReturn #False - EndIf - - If FindMapElement(DbName(), Key) - If DbName(Key) = Name And DbOrigin(Key) = #BakaShrot_Names_OriginConfig - Continue - EndIf - If DbOrigin(Key) = #BakaShrot_Names_OriginPeer And LCase(DbName(Key)) <> LCase(Name) - *Error\s = *Names\Kind + " id " + Str(Id) + " is '" + DbName(Key) + "', added by a peer, " + Section + " can't rename it to '" + Name + - "': give '" + Name + "' another id, or name id " + Str(Id) + " '" + DbName(Key) + "'" - ProcedureReturn #False - EndIf - If LCase(DbName(Key)) <> LCase(Name) And DbOrigin(Key) = #BakaShrot_Names_OriginConfig - PrintN("[Names] Renaming " + *Names\Kind + " " + Key + " from '" + DbName(Key) + "' to '" + Name + "'") - EndIf - EndIf - - SetDatabaseLong(DbId, 0, Id) - SetDatabaseString(DbId, 1, Name) - SetDatabaseString(DbId, 2, #BakaShrot_Names_OriginConfig) - If Not DatabaseUpdate(DbId, "INSERT INTO " + *Names\Table + " (" + *Names\IdColumn + ", name, origin) VALUES (?, ?, ?) " + - "ON CONFLICT (" + *Names\IdColumn + ") DO UPDATE SET name = excluded.name, origin = excluded.origin") - *Error\s = "can't store " + *Names\Kind + " '" + Name + "': " + DatabaseError() - ProcedureReturn #False - EndIf - Next - - ; Every id the config uses, and every one already in "data", gets a row. - ForEach UsedIds() - AllIds(MapKey(UsedIds())) = #True - Next - If Not DatabaseQuery(DbId, "SELECT DISTINCT " + *Names\IdColumn + " FROM node_heads") - *Error\s = "can't read node_heads: " + DatabaseError() - ProcedureReturn #False - EndIf - While NextDatabaseRow(DbId) - AllIds(Str(GetDatabaseLong(DbId, 0))) = #True - Wend - FinishDatabaseQuery(DbId) - - ForEach AllIds() - Key = MapKey(AllIds()) - If FindMapElement(ConfigNames(), Key) Or FindMapElement(DbName(), Key) - Continue - EndIf - SetDatabaseLong(DbId, 0, Val(Key)) - SetDatabaseString(DbId, 1, Key) - SetDatabaseString(DbId, 2, #BakaShrot_Names_OriginId) - If Not DatabaseUpdate(DbId, "INSERT OR IGNORE INTO " + *Names\Table + " (" + *Names\IdColumn + ", name, origin) VALUES (?, ?, ?)") - *Error\s = "can't store " + *Names\Kind + " id " + Key + ": " + DatabaseError() - ProcedureReturn #False - EndIf - Next - - ; In memory, from what the table now holds. - ClearMap(*Names\IdByName()) - ClearMap(*Names\NameById()) - ClearMap(*Names\OriginById()) - If Not DatabaseQuery(DbId, "SELECT " + *Names\IdColumn + ", name, origin FROM " + *Names\Table) - *Error\s = "can't read the " + *Names\Table + " table: " + DatabaseError() - ProcedureReturn #False - EndIf - While NextDatabaseRow(DbId) - Id = GetDatabaseLong(DbId, 0) - Name = GetDatabaseString(DbId, 1) - *Names\OriginById(Str(Id)) = GetDatabaseString(DbId, 2) - If BakaShrot_IsDigits(Name) - *Names\NameById(Str(Id)) = "" - Else - *Names\NameById(Str(Id)) = Name - *Names\IdByName(LCase(Name)) = Id - EndIf - Wend - FinishDatabaseQuery(DbId) - - ProcedureReturn #True -EndProcedure - - -; Reconciles the config's names with the database, see the top of this -; file. Only from the root, with the workers stopped, on its own connection. -; Returns #False with the reason in *Error\s, nothing is changed then. -Procedure.i BakaShrot_Names_Load(DbId.i, *Config.BakaShrot_CoreConfig, *Error.String) - Protected Loaded.i - - LockMutex(BakaShrot_Names_Mutex) - If Not DatabaseUpdate(DbId, "BEGIN IMMEDIATE") - *Error\s = DatabaseError() - UnlockMutex(BakaShrot_Names_Mutex) - ProcedureReturn #False - EndIf - - Loaded = Bool(BakaShrot_Names_LoadTable(DbId, @BakaShrot_Names_Topics, *Config\TopicNames(), *Config\UsedTopicIds(), *Error) And - BakaShrot_Names_LoadTable(DbId, @BakaShrot_Names_Nodes, *Config\NodeNames(), *Config\UsedNodeIds(), *Error)) - - If Loaded And Not DatabaseUpdate(DbId, "COMMIT") - *Error\s = DatabaseError() - Loaded = #False - EndIf - If Not Loaded - DatabaseUpdate(DbId, "ROLLBACK") - EndIf - - UnlockMutex(BakaShrot_Names_Mutex) - ProcedureReturn Loaded -EndProcedure - - -; Fills *Known with what the database has, for LoadConfig() (Config.pbi): -; the id of every name, and every id with a row or messages. Before the -; config is loaded, on a connection of its own, the database set up. -; Returns #False with the reason in *Error\s. -Procedure.i BakaShrot_Names_ReadKnown(DbId.i, *Known.BakaShrot_KnownNames, *Error.String) - Protected Name.s, Id.i - - ; Topics - If Not DatabaseQuery(DbId, "SELECT topic_id, name FROM topics UNION SELECT DISTINCT topic_id, '' FROM node_heads") - *Error\s = "can't read the topics: " + DatabaseError() - ProcedureReturn #False - EndIf - While NextDatabaseRow(DbId) - Id = GetDatabaseLong(DbId, 0) - Name = GetDatabaseString(DbId, 1) - *Known\TopicUsed(Str(Id)) = #True - If Name <> "" And Not BakaShrot_IsDigits(Name) - *Known\TopicIds(LCase(Name)) = Id - EndIf - Wend - FinishDatabaseQuery(DbId) - - ; Nodes - If Not DatabaseQuery(DbId, "SELECT node_id, name FROM nodes UNION SELECT DISTINCT node_id, '' FROM node_heads") - *Error\s = "can't read the nodes: " + DatabaseError() - ProcedureReturn #False - EndIf - While NextDatabaseRow(DbId) - Id = GetDatabaseLong(DbId, 0) - Name = GetDatabaseString(DbId, 1) - *Known\NodeUsed(Str(Id)) = #True - If Name <> "" And Not BakaShrot_IsDigits(Name) - *Known\NodeIds(LCase(Name)) = Id - EndIf - Wend - FinishDatabaseQuery(DbId) - - ProcedureReturn #True -EndProcedure - - -; --- Lookups ----------------------------------------------------------------- - -; The id Ref stands for: an id in digits is that id, a name must be known. -; -1 if it's neither. Holding the names mutex. -Procedure.i BakaShrot_Names_ResolveIn(*Names.BakaShrot_NameTable, Ref.s) - Protected Id.i = BakaShrot_RefToId(Ref) - - If Id >= 0 - ProcedureReturn Id - EndIf - If BakaShrot_IsValidName(Ref) And FindMapElement(*Names\IdByName(), LCase(Ref)) - ProcedureReturn *Names\IdByName() - EndIf - ProcedureReturn -1 -EndProcedure - -; Its name, "" if it has none. Holding the names mutex. -Procedure.s BakaShrot_Names_NameIn(*Names.BakaShrot_NameTable, Id.i) - If FindMapElement(*Names\NameById(), Str(Id)) - ProcedureReturn *Names\NameById() - EndIf - ProcedureReturn "" -EndProcedure - - -; The topic id Ref stands for here, -1 if none. -Procedure.i BakaShrot_Names_ResolveTopic(Ref.s) - Protected Id.i - LockMutex(BakaShrot_Names_Mutex) - Id = BakaShrot_Names_ResolveIn(@BakaShrot_Names_Topics, Ref) - UnlockMutex(BakaShrot_Names_Mutex) - ProcedureReturn Id -EndProcedure - -; The node id Ref stands for here, -1 if none. -Procedure.i BakaShrot_Names_ResolveNode(Ref.s) - Protected Id.i - LockMutex(BakaShrot_Names_Mutex) - Id = BakaShrot_Names_ResolveIn(@BakaShrot_Names_Nodes, Ref) - UnlockMutex(BakaShrot_Names_Mutex) - ProcedureReturn Id -EndProcedure - -; The topic id of a known name (never an id in digits), -1 if none: what -; replication goes by. -Procedure.i BakaShrot_Names_TopicByName(Name.s) - If Not BakaShrot_IsValidName(Name) - ProcedureReturn -1 - EndIf - ProcedureReturn BakaShrot_Names_ResolveTopic(Name) -EndProcedure - -; Same for a node. -Procedure.i BakaShrot_Names_NodeByName(Name.s) - If Not BakaShrot_IsValidName(Name) - ProcedureReturn -1 - EndIf - ProcedureReturn BakaShrot_Names_ResolveNode(Name) -EndProcedure - -; A topic's name, "" if it has none. -Procedure.s BakaShrot_Names_TopicName(Id.i) - Protected Name.s - LockMutex(BakaShrot_Names_Mutex) - Name = BakaShrot_Names_NameIn(@BakaShrot_Names_Topics, Id) - UnlockMutex(BakaShrot_Names_Mutex) - ProcedureReturn Name -EndProcedure - -; A node's name, "" if it has none. -Procedure.s BakaShrot_Names_NodeName(Id.i) - Protected Name.s - LockMutex(BakaShrot_Names_Mutex) - Name = BakaShrot_Names_NameIn(@BakaShrot_Names_Nodes, Id) - UnlockMutex(BakaShrot_Names_Mutex) - ProcedureReturn Name -EndProcedure - -; What a topic goes by in answers and logs: its name, or its id in digits. -Procedure.s BakaShrot_Names_TopicRef(Id.i) - Protected Name.s = BakaShrot_Names_TopicName(Id) - If Name = "" - ProcedureReturn Str(Id) - EndIf - ProcedureReturn Name -EndProcedure - -; Same for a node. -Procedure.s BakaShrot_Names_NodeRef(Id.i) - Protected Name.s = BakaShrot_Names_NodeName(Id) - If Name = "" - ProcedureReturn Str(Id) - EndIf - ProcedureReturn Name -EndProcedure - - -; Fills Names() with every named topic (Kind #BakaShrot_NameKind_Topic) or -; node, by id, for the sync state. *Filter: only the ones it holds, 0 for -; all of them. -Procedure BakaShrot_Names_GetNamed(Kind.i, List Names.BakaShrot_SyncName(), *Filter.BakaShrot_NameSet = 0) - Protected *Names.BakaShrot_NameTable, Id.i - - *Names = @BakaShrot_Names_Topics - If Kind = #BakaShrot_NameKind_Node - *Names = @BakaShrot_Names_Nodes - EndIf - - ClearList(Names()) - LockMutex(BakaShrot_Names_Mutex) - ForEach *Names\IdByName() - Id = *Names\IdByName() - If *Filter And Not NameSetHas(*Filter, Id, BakaShrot_Names_NameIn(*Names, Id)) - Continue - EndIf - AddElement(Names()) - Names()\Id = Id - Names()\Name = BakaShrot_Names_NameIn(*Names, Id) - Next - UnlockMutex(BakaShrot_Names_Mutex) - - SortStructuredList(Names(), #PB_Sort_Ascending, OffsetOf(BakaShrot_SyncName\Id), #PB_Long) -EndProcedure - - -; Fills Entries() with every topic or node (Kind), named or not, by id, with -; where its name comes from. *Filter: only the topics it holds, 0 for all. -Procedure BakaShrot_Names_GetAll(Kind.i, List Entries.BakaShrot_NameEntry(), *Filter.BakaShrot_NameSet = 0) - Protected *Names.BakaShrot_NameTable, Id.i - - *Names = @BakaShrot_Names_Topics - If Kind = #BakaShrot_NameKind_Node - *Names = @BakaShrot_Names_Nodes - EndIf - - ClearList(Entries()) - LockMutex(BakaShrot_Names_Mutex) - ForEach *Names\NameById() - Id = Val(MapKey(*Names\NameById())) - If *Filter And Not NameSetHas(*Filter, Id, *Names\NameById()) - Continue - EndIf - AddElement(Entries()) - Entries()\Id = Id - Entries()\Name = *Names\NameById() - Entries()\Origin = *Names\OriginById(Str(Id)) - Next - UnlockMutex(BakaShrot_Names_Mutex) - - SortStructuredList(Entries(), #PB_Sort_Ascending, OffsetOf(BakaShrot_NameEntry\Id), #PB_Long) -EndProcedure - - -; Prints every topic and node with its id, for the server's "names" command. -Procedure BakaShrot_Names_Print() - Protected NewList Entries.BakaShrot_NameEntry() - Protected Kind.i, Label.s, Name.s - - For Kind = #BakaShrot_NameKind_Topic To #BakaShrot_NameKind_Node - BakaShrot_Names_GetAll(Kind, Entries()) - If Kind = #BakaShrot_NameKind_Topic - Label = "Topics" - Else - Label = "Nodes" - EndIf - PrintN(Label + " (" + Str(ListSize(Entries())) + "):") - ForEach Entries() - Name = Entries()\Name - If Name = "" - Name = "(unnamed, not replicated)" - EndIf - PrintN(" " + RSet(Str(Entries()\Id), 5) + " " + LSet(Name, 30) + " " + Entries()\Origin) - Next - Next -EndProcedure - - -; --- Adding ------------------------------------------------------------------ - -; Makes sure Id has a row, as unnamed if it's new: for messages stored under -; an id the database didn't know yet (a push to a topic allowed by "*"). -; Holding the names mutex. Returns #False with the reason in *Error\s. -Procedure.i BakaShrot_Names_EnsureIdIn(*Names.BakaShrot_NameTable, Id.i, *Error.String) - If FindMapElement(*Names\NameById(), Str(Id)) - ProcedureReturn #True - EndIf - If Not RegisterStorageName(*Names\Table, Id, Str(Id), #BakaShrot_Names_OriginId, *Error) - ProcedureReturn #False - EndIf - *Names\NameById(Str(Id)) = "" - *Names\OriginById(Str(Id)) = #BakaShrot_Names_OriginId - ProcedureReturn #True -EndProcedure - -Procedure.i BakaShrot_Names_EnsureTopicId(Id.i, *Error.String) - Protected Done.i - LockMutex(BakaShrot_Names_Mutex) - Done = BakaShrot_Names_EnsureIdIn(@BakaShrot_Names_Topics, Id, *Error) - UnlockMutex(BakaShrot_Names_Mutex) - ProcedureReturn Done -EndProcedure - - -; The id of a topic (Kind #BakaShrot_NameKind_Topic) or node a peer sent, -; by its name, which a wildcard in that peer's AcceptTopics / AcceptNodes -; took (the caller checks): a name this server doesn't have yet is added, -; under the highest free id counting down from 65535 (origin "peer"). -; Returns -1 with the reason in *Error\s. -Procedure.i BakaShrot_Names_Ingest(Kind.i, Name.s, *Error.String) - Protected *Names.BakaShrot_NameTable, Id.i - - *Names = @BakaShrot_Names_Topics - If Kind = #BakaShrot_NameKind_Node - *Names = @BakaShrot_Names_Nodes - EndIf - - If Not BakaShrot_IsValidName(Name) - *Error\s = "'" + Name + "' isn't a valid " + *Names\Kind + " name" - ProcedureReturn -1 - EndIf - - LockMutex(BakaShrot_Names_Mutex) - If FindMapElement(*Names\IdByName(), LCase(Name)) - Id = *Names\IdByName() - UnlockMutex(BakaShrot_Names_Mutex) - ProcedureReturn Id - EndIf - - For Id = #BakaShrot_MaxId To 0 Step -1 - If Not FindMapElement(*Names\NameById(), Str(Id)) - Break - EndIf - Next - If Id < 0 - UnlockMutex(BakaShrot_Names_Mutex) - *Error\s = "no " + *Names\Kind + " id left for '" + Name + "'" - ProcedureReturn -1 - EndIf - - If Not RegisterStorageName(*Names\Table, Id, Name, #BakaShrot_Names_OriginPeer, *Error) - UnlockMutex(BakaShrot_Names_Mutex) - ProcedureReturn -1 - EndIf - *Names\NameById(Str(Id)) = Name - *Names\OriginById(Str(Id)) = #BakaShrot_Names_OriginPeer - *Names\IdByName(LCase(Name)) = Id - UnlockMutex(BakaShrot_Names_Mutex) - - PrintN("[Names] New " + *Names\Kind + " '" + Name + "' from a peer, id " + Str(Id) + " here") - ProcedureReturn Id -EndProcedure - - -; --- Drops ------------------------------------------------------------------- - -; Called whenever a topic or node isn't replicated because one side doesn't -; know it: Peer is the peer section's name, Kind "topic" or "node", Ref what -; it goes by on the side that has it, Reason why it was dropped. -; !!! Does nothing for now, on purpose: it's called at every check-in for -; !!! every such pair, so logging each one would spam. Later: warn once per -; !!! peer and name (and again only if it changes), see Notes.md. -Procedure BakaShrot_Names_NoteDropped(Peer.s, Kind.s, Ref.s, Reason.s) -EndProcedure diff --git a/Server/Storage/Retention.pbi b/Server/Storage/Retention.pbi deleted file mode 100644 index 14ba8b1..0000000 --- a/Server/Storage/Retention.pbi +++ /dev/null @@ -1,214 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: Retention.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; BakaShrot Storage Retention -; -; Deletes the messages past their topic's max age, so a server's database -; stops growing: [BakaShrot.Retention] in its config, see -; BakaShrot_RetentionRule in Server/Config/Config.pbi. -; -; A thread, started with the workers (StartStorageRetention(), see -; Server/Root.pbi), runs a pass right away then every [BakaShrot.Server] -; RetentionInterval seconds: -; - every topic of the database (node_heads), with its name (topics); -; - its max age from the rules; kept forever (0) is skipped; -; - deletes its messages pushed (pushed_at) before now minus that age, -; #BakaShrot_Retention_BatchSize at a time through the writer -; (DeleteStorageMessagesBefore(), Writer.pbi), so pushes go on between -; the batches; -; - then the attachments' leftovers (CleanUpStorageBlobs(), -; Attachments.pbi): those of the deleted messages, and uploads not -; pushed with a message within [BakaShrot.Server] UploadTimeout, -; #BakaShrot_Retention_ChunkBatchSize parts at a time. -; It runs without any [BakaShrot.Retention] too, for the leftovers. -; -; Messages "may be" deleted past their max age: up to RetentionInterval -; later. Those a peer replicates here already past it aren't stored at all -; (InsertReplicatedMessages() in Writer.pbi), only counted as received. pushed_at is the time the message was pushed to its origin, kept as -; is by replication, so a server deletes a replicated message by when it -; was first pushed, not when it got it. -; -; What deleting doesn't change: -; - node_heads: a pair's head stays its highest id ever. The next push -; still gets the next id, and the sync state still tells peers this -; server had those messages: they aren't sent again. -; - The file's size: SQLite reuses the freed pages for new messages, so -; it stops growing once deletions keep up with pushes. VACUUM (the -; "vacuum" console command) gives the space back to the disk. -; ============================================================================ - -; Most messages deleted in one statement, under the write mutex: a few ms. -#BakaShrot_Retention_BatchSize = 5000 - -; Most attachment parts (1 MB each) deleted in one statement. -#BakaShrot_Retention_ChunkBatchSize = 32 - - -Structure BakaShrot_RetentionTopic - TopicId.i - Name.s -EndStructure - -Structure BakaShrot_RetentionState - ThreadId.i - StopRequested.i - IntervalMs.i - UploadTimeoutMs.q - DatabasePath.s - List Rules.BakaShrot_RetentionRule() -EndStructure - -Global BakaShrot_Retention.BakaShrot_RetentionState - - -; Ms (since 1970 UTC) as "2026-11-08T14:03:59Z", for the logs. -Procedure.s BakaShrot_Retention_FormatUtc(Ms.q) - ProcedureReturn FormatDate("%yyyy-%mm-%ddT%hh:%ii:%ssZ", Ms / 1000) -EndProcedure - - -; Deletes the attachments' leftovers, a few parts at a time. -Procedure BakaShrot_Retention_CleanUp() - Protected Deleted.i, Total.q, Error.String - - Repeat - Deleted = CleanUpStorageBlobs(BakaShrot_NowUtcMs() - BakaShrot_Retention\UploadTimeoutMs, #BakaShrot_Retention_ChunkBatchSize, @Error) - If Deleted < 0 - PrintN("[Storage] Retention: failed to delete the attachments' leftovers: " + Error\s) - Break - EndIf - Total + Deleted - Until Deleted < #BakaShrot_Retention_ChunkBatchSize Or BakaShrot_Retention\StopRequested - - If Total > 0 - PrintN("[Storage] Retention: deleted " + Str(Total) + " attachment parts (of deleted messages, or uploads never pushed)") - EndIf -EndProcedure - - -; Deletes what's past its max age in every topic. DbId is the thread's own -; connection, only read from (the deletes go through the writer). -; Returns how many messages were deleted. -Procedure.q BakaShrot_Retention_Pass(DbId.i) - Protected NewList Topics.BakaShrot_RetentionTopic() - Protected MaxAge.q, Before.q, Deleted.i, TopicDeleted.q, Total.q, Error.String - - If Not DatabaseQuery(DbId, "SELECT DISTINCT h.topic_id, COALESCE(t.name, '') FROM node_heads h LEFT JOIN topics t ON t.topic_id = h.topic_id") - PrintN("[Storage] Retention: can't list the topics: " + DatabaseError()) - ProcedureReturn 0 - EndIf - While NextDatabaseRow(DbId) - AddElement(Topics()) - Topics()\TopicId = GetDatabaseLong(DbId, 0) - Topics()\Name = GetDatabaseString(DbId, 1) - Wend - FinishDatabaseQuery(DbId) - - ForEach Topics() - MaxAge = RetentionMaxAgeMs(BakaShrot_Retention\Rules(), Topics()\TopicId, Topics()\Name) - If MaxAge <= 0 - Continue - EndIf - - Before = BakaShrot_NowUtcMs() - MaxAge - TopicDeleted = 0 - Repeat - Deleted = DeleteStorageMessagesBefore(Topics()\TopicId, Before, #BakaShrot_Retention_BatchSize, @Error) - If Deleted < 0 - PrintN("[Storage] Retention: failed to delete from topic " + Str(Topics()\TopicId) + ": " + Error\s) - Break - EndIf - TopicDeleted + Deleted - Until Deleted < #BakaShrot_Retention_BatchSize Or BakaShrot_Retention\StopRequested - - If TopicDeleted > 0 - If Topics()\Name <> "" - PrintN("[Storage] Retention: deleted " + Str(TopicDeleted) + " messages of topic '" + Topics()\Name + "' pushed before " + BakaShrot_Retention_FormatUtc(Before)) - Else - PrintN("[Storage] Retention: deleted " + Str(TopicDeleted) + " messages of topic " + Str(Topics()\TopicId) + " pushed before " + BakaShrot_Retention_FormatUtc(Before)) - EndIf - EndIf - Total + TopicDeleted - - If BakaShrot_Retention\StopRequested - Break - EndIf - Next - - BakaShrot_Retention_CleanUp() - ProcedureReturn Total -EndProcedure - - -Procedure BakaShrot_Retention_Thread(Unused.i) - Protected DbId.i, LastPass.i - - DbId = OpenStorageDatabase(BakaShrot_Retention\DatabasePath) - If Not DbId - PrintN("[Storage] Retention: can't open the database, nothing will be deleted: " + DatabaseError()) - ProcedureReturn - EndIf - - BakaShrot_Retention_Pass(DbId) - LastPass = ElapsedMilliseconds() - While Not BakaShrot_Retention\StopRequested - Delay(100) - If ElapsedMilliseconds() - LastPass >= BakaShrot_Retention\IntervalMs - BakaShrot_Retention_Pass(DbId) - LastPass = ElapsedMilliseconds() - EndIf - Wend - - CloseDatabase(DbId) -EndProcedure - - -; Starts deleting what's past *Config's [BakaShrot.Retention] max ages, and -; the attachments' leftovers, once the writer is open. -; Returns #False if the thread can't start. -Procedure.i StartStorageRetention(*Config.BakaShrot_CoreConfig) - With BakaShrot_Retention - ClearList(\Rules()) - CopyList(*Config\Retention(), \Rules()) - ForEach \Rules() - If \Rules()\MaxAgeMs > 0 - PrintN("[Storage] Retention: " + \Rules()\Ref + " = " + \Rules()\AgeText + ", checked every " + Str(*Config\Server\RetentionInterval) + " s") - EndIf - Next - - \DatabasePath = *Config\Server\DatabasePath - \IntervalMs = *Config\Server\RetentionInterval * 1000 - \UploadTimeoutMs = *Config\Server\UploadTimeout * 1000 - \StopRequested = #False - \ThreadId = CreateThread(@BakaShrot_Retention_Thread(), 0) - ProcedureReturn Bool(\ThreadId) - EndWith -EndProcedure - - -; Stops it, before the writer closes. Waits for a pass under way to end its -; current batch. -Procedure StopStorageRetention() - With BakaShrot_Retention - If \ThreadId - \StopRequested = #True - WaitThread(\ThreadId) - \ThreadId = 0 - EndIf - EndWith -EndProcedure diff --git a/Server/Storage/Storage.pbi b/Server/Storage/Storage.pbi deleted file mode 100644 index 36a7b03..0000000 --- a/Server/Storage/Storage.pbi +++ /dev/null @@ -1,971 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: Storage.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; BakaShrot Storage -; -; Opens the SQLite database file that backs the node's local storage, and -; provides the basic read/write operations on top of it. -; Schema: see db_schema_v8.dbml in this same folder. Attachments: see -; Attachments.pbi and Design/Attachments.md. -; -; Needs SQLite 3.38+ with its JSON functions (json_valid, ->>), which the one -; bundled with PureBasic 5.73 (3.33.0) doesn't have. On Windows, the official -; sqlite3.dll is used instead, it must be next to the program. Build.ps1 -; extracts it from Libs/sqlite-dll-win-*.zip and copies it. -; On Linux, the system's libsqlite3.so.0 (libsqlite3-0 on Debian/Ubuntu, -; sqlite-libs on Fedora) is used, whatever the compiler, it must be 3.38+. -; Either way it's #BakaShrot_Storage_SqliteLibrary, which RunReadOnlyQuery() -; and the writer (Writer.pbi) also call directly. Elsewhere, PureBasic's own -; SQLite is linked in, and they make do without it. -; -; Threads: ONE CONNECTION PER THREAD, never share a handle. -; The SetDatabase*() parameters and query results belong to a handle, so two -; threads using the same one overwrite each other's. Every thread that touches -; the database opens its own with OpenStorageDatabase() and closes it when it -; ends: each client thread, each peer link thread, each raw query, and the -; root's own one (setup and maintenance, see Server/Root.pbi). -; The one exception: every write goes through the writer (Writer.pbi), a -; single connection only used while holding BakaShrot_Storage_WriteMutex. -; SQLite still serializes writes from other processes -; (#BakaShrot_Storage_BusyTimeout). WAL mode lets reads run alongside them. -; See Design/StorageConcurrency.md. -; ============================================================================ - - -; For BakaShrot_SyncPair and BakaShrot_ReplicatedMessage. -XIncludeFile "../../Commons/Networking/Packets/SyncStatePacket.pbi" -XIncludeFile "../../Commons/Networking/Packets/ReplicateMessagesPacket.pbi" - - -CompilerSelect #PB_Compiler_OS - CompilerCase #PB_OS_Windows - #BakaShrot_Storage_ExternalSqlite = #True - #BakaShrot_Storage_SqliteLibrary = "sqlite3.dll" - CompilerCase #PB_OS_Linux - #BakaShrot_Storage_ExternalSqlite = #True - #BakaShrot_Storage_SqliteLibrary = "libsqlite3.so.0" - CompilerDefault - #BakaShrot_Storage_ExternalSqlite = #False - #BakaShrot_Storage_SqliteLibrary = "" -CompilerEndSelect - -CompilerIf #BakaShrot_Storage_ExternalSqlite - UseSQLiteDatabase(#BakaShrot_Storage_SqliteLibrary) -CompilerElse - UseSQLiteDatabase() -CompilerEndIf - - -; One row of the "data" table (see db_schema_v8.dbml). -; PushedAt: when it was pushed, ms since 1970 UTC (Packets.pbi). -; AttachmentSize: its attachment's size, 0 for none (the "attachments" -; table), AttachmentReady #True once all of it is here, AttachmentSha256 its -; SHA-256. -Structure BakaShrot_Message - MessageId.q - PushedAt.q - JsonData.s - AttachmentSize.q - AttachmentReady.i - AttachmentSha256.a[#BakaShrot_Sha256Size] -EndStructure - - -CompilerIf #PB_Compiler_OS <> #PB_OS_Windows - ImportC "" - BakaShrot_GetTimeOfDay.l(*TimeVal, *TimeZone) As "gettimeofday" - EndImport -CompilerEndIf - -; Now, in milliseconds since 1970-01-01 00:00:00 UTC: what a pushed message -; is stamped with (pushed_at). -Procedure.q BakaShrot_NowUtcMs() - CompilerIf #PB_Compiler_OS = #PB_OS_Windows - ; 100 ns intervals since 1601-01-01 UTC. - Protected FileTime.q - GetSystemTimeAsFileTime_(@FileTime) - ProcedureReturn (FileTime - 116444736000000000) / 10000 - CompilerElse - ; struct timeval, 64-bit (checked on Linux x64 by Tests/Retention-Test.ps1). - Protected Dim TimeVal.q(1) - BakaShrot_GetTimeOfDay(@TimeVal(0), 0) - ProcedureReturn TimeVal(0) * 1000 + TimeVal(1) / 1000 - CompilerEndIf -EndProcedure - - -; How long a connection waits for another one's lock before a statement -; fails with "database is locked", in ms. -#BakaShrot_Storage_BusyTimeout = 5000 - -; The database runs in WAL mode (set up by SetupStorageDatabase(), stored in -; the file): readers and the writer don't block each other anymore, so a -; long raw query no longer stalls every push. -; PRAGMA synchronous of every connection: [BakaShrot.Server] Synchronous, -; set by the root before it opens any (Server/Root.pbi). FULL by default. -; FULL syncs the WAL on every commit: an acknowledged push is on disk. It -; costs one flush per transaction, shared by a group commit's pushes. -; NORMAL only syncs at checkpoints (about every second, Writer.pbi): the -; database can't get corrupted, but the last commits before a power loss or -; an OS crash (not a crash of the server itself) can be lost. Those messages -; were acknowledged, and maybe replicated already, so their ids could then -; be handed out again for other messages: drift, see -; Design/ReplicationIssues.md #1. Measured: Design/StorageConcurrency.md. -#BakaShrot_Storage_DefaultSynchronous = "FULL" -Global BakaShrot_Storage_Synchronous.s = #BakaShrot_Storage_DefaultSynchronous - - -; Opens (and creates, if missing) the SQLite database at DatabasePath, as a -; new connection for the calling thread only. -; Returns the PureBasic database number, or 0 if the file could not be opened. -Procedure.i OpenStorageDatabase(DatabasePath.s) - Protected FileId.i, DbId.i - - ; PureBasic's SQLite driver refuses to open a file that doesn't exist, - ; so an empty one has to be created first. - If FileSize(DatabasePath) = -1 - FileId = CreateFile(#PB_Any, DatabasePath) - If Not FileId - ProcedureReturn 0 - EndIf - CloseFile(FileId) - EndIf - - DbId = OpenDatabase(#PB_Any, DatabasePath, "", "") - If Not DbId - ProcedureReturn 0 - EndIf - - ; Without it, a write fails right away while another connection writes. - If Not DatabaseUpdate(DbId, "PRAGMA busy_timeout = " + Str(#BakaShrot_Storage_BusyTimeout)) - CloseDatabase(DbId) - ProcedureReturn 0 - EndIf - - ; Per connection, see BakaShrot_Storage_Synchronous. - If Not DatabaseUpdate(DbId, "PRAGMA synchronous = " + BakaShrot_Storage_Synchronous) - CloseDatabase(DbId) - ProcedureReturn 0 - EndIf - - ProcedureReturn DbId -EndProcedure - - -; Rebuilds the database file, reclaiming the space of deleted rows. -; Only run it from the root while every worker is stopped: it needs every -; other connection to be idle. See BakaShrot_Root_Vacuum() in Server/Root.pbi. -Procedure.i VacuumStorageDatabase(DbId.i) - ProcedureReturn DatabaseUpdate(DbId, "VACUUM") -EndProcedure - - -; #True if Table has a column named Column, #False if not (or no such table), -; -1 on failure. -Procedure.i StorageHasColumn(DbId.i, Table.s, Column.s) - Protected Found.i = #False - - SetDatabaseString(DbId, 0, Table) - SetDatabaseString(DbId, 1, Column) - If Not DatabaseQuery(DbId, "SELECT COUNT(*) FROM pragma_table_info(?) WHERE name = ?") - ProcedureReturn -1 - EndIf - If NextDatabaseRow(DbId) - Found = Bool(GetDatabaseLong(DbId, 0) > 0) - EndIf - FinishDatabaseQuery(DbId) - - ProcedureReturn Found -EndProcedure - - -; v3 -> v4: "group_id" became "topic_id" in every table. Renames the -; columns of a database made before, in one transaction. The trigger and the -; attachements index are dropped, SetupStorageDatabase() makes them again -; with the new names. The UNIQUE and PRIMARY KEY indexes follow the columns. -; Nothing to do on a new or already renamed database. -Procedure.i MigrateStorageTopicIds(DbId.i) - Protected Table.s, Has.i, i.i - - Has = StorageHasColumn(DbId, "data", "group_id") - If Has = -1 - ProcedureReturn #False - ElseIf Not Has - ProcedureReturn #True - EndIf - - If Not DatabaseUpdate(DbId, "BEGIN IMMEDIATE") - ProcedureReturn #False - EndIf - If Not DatabaseUpdate(DbId, "DROP TRIGGER IF EXISTS trg_data_node_heads") Or - Not DatabaseUpdate(DbId, "DROP INDEX IF EXISTS idx_attachements_group_node") - DatabaseUpdate(DbId, "ROLLBACK") - ProcedureReturn #False - EndIf - For i = 1 To 3 - Table = StringField("data,node_heads,attachements", i, ",") - Has = StorageHasColumn(DbId, Table, "group_id") - If Has = -1 Or (Has And Not DatabaseUpdate(DbId, "ALTER TABLE " + Table + " RENAME COLUMN group_id TO topic_id")) - DatabaseUpdate(DbId, "ROLLBACK") - ProcedureReturn #False - EndIf - Next - If Not DatabaseUpdate(DbId, "COMMIT") - DatabaseUpdate(DbId, "ROLLBACK") - ProcedureReturn #False - EndIf - - ProcedureReturn #True -EndProcedure - - -; v5 -> v6: "data" got pushed_at. Adds it to a database made before, every -; message stamped with the time of the upgrade (their real one is unknown), -; in one transaction. Nothing to do on a new or already upgraded database. -Procedure.i MigrateStoragePushedAt(DbId.i) - Protected Has.i - - Has = StorageHasColumn(DbId, "data", "pushed_at") - If Has = -1 - ProcedureReturn #False - ElseIf Has - ProcedureReturn #True - EndIf - - If Not DatabaseUpdate(DbId, "BEGIN IMMEDIATE") - ProcedureReturn #False - EndIf - If Not DatabaseUpdate(DbId, "ALTER TABLE data ADD COLUMN pushed_at INTEGER NOT NULL DEFAULT 0") - DatabaseUpdate(DbId, "ROLLBACK") - ProcedureReturn #False - EndIf - ; Bound for the next statement run, so right before it. - SetDatabaseQuad(DbId, 0, BakaShrot_NowUtcMs()) - If Not DatabaseUpdate(DbId, "UPDATE data SET pushed_at = ?") - DatabaseUpdate(DbId, "ROLLBACK") - ProcedureReturn #False - EndIf - If Not DatabaseUpdate(DbId, "COMMIT") - DatabaseUpdate(DbId, "ROLLBACK") - ProcedureReturn #False - EndIf - - ProcedureReturn #True -EndProcedure - - -; Creates the tables and indexes described by db_schema_v8.dbml, if they -; don't exist yet. Plain "CREATE IF NOT EXISTS" for now - a real versioned -; upgrade mechanism (DbUpdater) will replace this later. -; Fails on a database made with an older schema, since it would be left as is. -Procedure.i SetupStorageDatabase(DbId.i) - Protected JournalMode.s, HeadsExist.i - - ; Stored in the file, every later connection uses it. Fails while another - ; connection has the database open, so only the root does it, at start. - If Not DatabaseQuery(DbId, "PRAGMA journal_mode = WAL") - ProcedureReturn #False - EndIf - If NextDatabaseRow(DbId) - JournalMode = LCase(GetDatabaseString(DbId, 0)) - EndIf - FinishDatabaseQuery(DbId) - If JournalMode <> "wal" - ProcedureReturn #False - EndIf - - ; Before anything below, which uses the new names. - If Not MigrateStorageTopicIds(DbId) - ProcedureReturn #False - EndIf - - ; A leftover of the first schemas, never used: the retention deletes - ; instead (Retention.pbi). - If Not DatabaseUpdate(DbId, "DROP TABLE IF EXISTS archives") - ProcedureReturn #False - EndIf - - ; is_json is set by SQLite on insert, and can't be written. - ; pushed_at: when it was pushed to its origin, ms since 1970 UTC, kept as - ; is when replicated. Last, like the ALTER TABLE below adds it. - ; The UNIQUE constraint's index also serves (topic_id, node_id) lookups. - If Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS data (" + - "topic_id INTEGER NOT NULL, " + - "node_id INTEGER NOT NULL, " + - "message_id INTEGER NOT NULL, " + - "message_data TEXT NOT NULL, " + - "is_json INTEGER NOT NULL GENERATED ALWAYS AS (json_valid(message_data)) STORED, " + - "pushed_at INTEGER NOT NULL DEFAULT 0, " + - "UNIQUE (topic_id, node_id, message_id))") - ProcedureReturn #False - EndIf - - ; An older "data" table is kept by CREATE IF NOT EXISTS, its lack of - ; is_json gives it away. Fails with "no such column: is_json". - If Not DatabaseQuery(DbId, "SELECT is_json FROM data LIMIT 0") - ProcedureReturn #False - EndIf - FinishDatabaseQuery(DbId) - If Not DatabaseUpdate(DbId, "CREATE INDEX IF NOT EXISTS idx_data_message_id ON data (message_id)") - ProcedureReturn #False - EndIf - - ; A database from before pushed_at: its messages get the time of this - ; upgrade, so a topic's max age (Server/Storage/Retention.pbi) counts - ; from now for them instead of deleting them all at once. - If Not MigrateStoragePushedAt(DbId) - ProcedureReturn #False - EndIf - - ; What the retention deletes by: a topic's messages pushed before a time. - If Not DatabaseUpdate(DbId, "CREATE INDEX IF NOT EXISTS idx_data_topic_pushed_at ON data (topic_id, pushed_at)") - ProcedureReturn #False - EndIf - - ; The first schemas' placeholder, never used (and misspelled), replaced - ; by the three tables below. Its indexes go with it. - If Not DatabaseUpdate(DbId, "DROP TABLE IF EXISTS attachements") - ProcedureReturn #False - EndIf - - ; Attachments, see Attachments.pbi and Design/Attachments.md. - ; blobs: an attachment's data, being uploaded or replicated, or stored. - ; topic_id, node_id: an upload's, who may attach it (or the message's). - ; received: bytes stored so far, in blob_chunks. - ; state: 0 receiving, 1 complete (an upload waiting for its message), - ; 2 attached to its message, 3 to delete (Retention.pbi deletes it). - ; created_at: ms since 1970 UTC, uploads left incomplete expire. - ; blob_chunks: its parts, #BakaShrot_AttachmentChunkSize bytes each. - ; attachments: a message's (one at most), with its size and SHA-256 - ; from the start, its data in blob_id once any is here. - ; state: 0 missing (a replicated message, none of it here yet), - ; 1 receiving, 2 ready, 3 not kept (bigger than this server takes). - If Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS blobs (" + - "blob_id INTEGER PRIMARY KEY, " + - "topic_id INTEGER NOT NULL, " + - "node_id INTEGER NOT NULL, " + - "size INTEGER NOT NULL, " + - "sha256 BLOB NOT NULL, " + - "received INTEGER NOT NULL DEFAULT 0, " + - "state INTEGER NOT NULL, " + - "created_at INTEGER NOT NULL)") Or - Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS blob_chunks (" + - "blob_id INTEGER NOT NULL, " + - "chunk_index INTEGER NOT NULL, " + - "chunk_data BLOB NOT NULL, " + - "PRIMARY KEY (blob_id, chunk_index))") Or - Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS attachments (" + - "topic_id INTEGER NOT NULL, " + - "node_id INTEGER NOT NULL, " + - "message_id INTEGER NOT NULL, " + - "size INTEGER NOT NULL, " + - "sha256 BLOB NOT NULL, " + - "blob_id INTEGER, " + - "state INTEGER NOT NULL, " + - "PRIMARY KEY (topic_id, node_id, message_id)) WITHOUT ROWID") Or - Not DatabaseUpdate(DbId, "CREATE INDEX IF NOT EXISTS idx_blobs_state ON blobs (state)") Or - Not DatabaseUpdate(DbId, "CREATE INDEX IF NOT EXISTS idx_attachments_state ON attachments (state)") - ProcedureReturn #False - EndIf - - ; A message deleted (the retention) takes its attachment with it, and an - ; attachment its data: marked, Retention.pbi deletes it a bit at a time. - If Not DatabaseUpdate(DbId, "CREATE TRIGGER IF NOT EXISTS trg_data_attachments AFTER DELETE ON data BEGIN " + - "DELETE FROM attachments WHERE topic_id = OLD.topic_id AND node_id = OLD.node_id AND message_id = OLD.message_id; " + - "END") Or - Not DatabaseUpdate(DbId, "CREATE TRIGGER IF NOT EXISTS trg_attachments_blobs AFTER DELETE ON attachments WHEN OLD.blob_id IS NOT NULL BEGIN " + - "UPDATE blobs SET state = 3 WHERE blob_id = OLD.blob_id; " + - "END") - ProcedureReturn #False - EndIf - - ; The highest message id of every topic/node id, kept by a trigger on - ; every insert, whoever does it. The sync state comes from it instead of - ; a GROUP BY over every message (131 ms at 1.9M rows, on every check-in). - ; Filled from "data" when it's created on an existing database. - ; Deleting from "data" (the retention) leaves it alone, on purpose: a - ; pair's head stays its highest id ever, so the next push still gets the - ; id after it, and peers aren't sent again what was deleted here. - If Not DatabaseQuery(DbId, "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'node_heads'") - ProcedureReturn #False - EndIf - HeadsExist = #False - If NextDatabaseRow(DbId) - HeadsExist = Bool(GetDatabaseLong(DbId, 0) > 0) - EndIf - FinishDatabaseQuery(DbId) - - If Not HeadsExist - If Not DatabaseUpdate(DbId, "BEGIN IMMEDIATE") - ProcedureReturn #False - EndIf - If Not DatabaseUpdate(DbId, "CREATE TABLE node_heads (" + - "topic_id INTEGER NOT NULL, " + - "node_id INTEGER NOT NULL, " + - "max_message_id INTEGER NOT NULL, " + - "PRIMARY KEY (topic_id, node_id)) WITHOUT ROWID") Or - Not DatabaseUpdate(DbId, "INSERT INTO node_heads (topic_id, node_id, max_message_id) " + - "SELECT topic_id, node_id, MAX(message_id) FROM data GROUP BY topic_id, node_id") - DatabaseUpdate(DbId, "ROLLBACK") - ProcedureReturn #False - EndIf - If Not DatabaseUpdate(DbId, "COMMIT") - DatabaseUpdate(DbId, "ROLLBACK") - ProcedureReturn #False - EndIf - EndIf - - ; Only fires for rows actually inserted, not the ones INSERT OR IGNORE drops. - If Not DatabaseUpdate(DbId, "CREATE TRIGGER IF NOT EXISTS trg_data_node_heads AFTER INSERT ON data BEGIN " + - "INSERT INTO node_heads (topic_id, node_id, max_message_id) VALUES (NEW.topic_id, NEW.node_id, NEW.message_id) " + - "ON CONFLICT (topic_id, node_id) DO UPDATE SET max_message_id = MAX(max_message_id, excluded.max_message_id); " + - "END") - ProcedureReturn #False - EndIf - - ; Every topic and node id in "data" has a row, with its name, or its id - ; in digits if it has none. origin: "config" (named in the config), - ; "peer" (a node a peer sent messages of, given an id here), "id" - ; (unnamed). Kept up to date by Server/Storage/Names.pbi. - ; No foreign keys from "data": see Notes.md, a replicated batch would - ; fail as a whole on an unknown id. - If Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS topics (" + - "topic_id INTEGER PRIMARY KEY, " + - "name TEXT NOT NULL UNIQUE COLLATE NOCASE, " + - "origin TEXT NOT NULL)") Or - Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS nodes (" + - "node_id INTEGER PRIMARY KEY, " + - "name TEXT NOT NULL UNIQUE COLLATE NOCASE, " + - "origin TEXT NOT NULL)") - ProcedureReturn #False - EndIf - - ; For queries by name: SELECT * FROM messages WHERE topic = 'logs' AND - ; node = 'kitchen' still goes through the indexes. pushed_utc is - ; pushed_at as text, "2026-11-08T14:03:59.123Z". - ; Made again on every start, so an older one gets the newer columns. - If Not DatabaseUpdate(DbId, "DROP VIEW IF EXISTS messages") Or - Not DatabaseUpdate(DbId, "CREATE VIEW messages AS " + - "SELECT t.name AS topic, n.name AS node, d.message_id, d.message_data, d.is_json, d.topic_id, d.node_id, " + - "d.pushed_at, strftime('%Y-%m-%dT%H:%M:%fZ', d.pushed_at / 1000.0, 'unixepoch') AS pushed_utc " + - "FROM data d JOIN topics t ON t.topic_id = d.topic_id JOIN nodes n ON n.node_id = d.node_id") - ProcedureReturn #False - EndIf - - ; For browsing with a database tool: set browse's one row to a topic - ; (and optionally a node), open browse_messages. The foreign keys are - ; only there for the tools: SQLiteStudio shows a dropdown of the names - ; for a column that references them. The server never turns foreign keys - ; on, so they never get in its way (a topic renamed in the config only - ; leaves a stale name here). The server never writes to browse either. - If Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS browse (" + - "id INTEGER PRIMARY KEY CHECK (id = 1), " + - "topic TEXT COLLATE NOCASE REFERENCES topics (name), " + - "node TEXT COLLATE NOCASE REFERENCES nodes (name))") Or - Not DatabaseUpdate(DbId, "INSERT OR IGNORE INTO browse (id) VALUES (1)") - ProcedureReturn #False - EndIf - - ; Newest first, by the (topic_id, pushed_at) index. Made again on every - ; start, like messages. - If Not DatabaseUpdate(DbId, "DROP VIEW IF EXISTS browse_messages") Or - Not DatabaseUpdate(DbId, "CREATE VIEW browse_messages AS " + - "SELECT m.node, m.message_id, m.pushed_utc, m.message_data, m.is_json, " + - "a.size AS attachment_size, m.topic " + - "FROM browse b JOIN messages m ON m.topic = b.topic " + - "LEFT JOIN attachments a ON a.topic_id = m.topic_id AND a.node_id = m.node_id AND a.message_id = m.message_id " + - "WHERE b.id = 1 AND (b.node IS NULL OR m.node = b.node) " + - "ORDER BY m.pushed_at DESC, m.node, m.message_id DESC") - ProcedureReturn #False - EndIf - - ProcedureReturn #True -EndProcedure - - -; Inserts one JSON message into the "data" table, pushed now. -Procedure.i Insert(DbId.i, TopicId.i, NodeId.i, MessageId.i, JsonData.s) - SetDatabaseLong(DbId, 0, TopicId) - SetDatabaseLong(DbId, 1, NodeId) - SetDatabaseLong(DbId, 2, MessageId) - SetDatabaseString(DbId, 3, JsonData) - SetDatabaseQuad(DbId, 4, BakaShrot_NowUtcMs()) - - ProcedureReturn DatabaseUpdate(DbId, "INSERT INTO data (topic_id, node_id, message_id, message_data, pushed_at) VALUES (?, ?, ?, ?, ?)") -EndProcedure - - -; Gets every message stored for a given topic_id/node_id pair - the -; "(topic_id, node_id)" index - ordered by message_id. -Procedure.i GetMessagesByTopicAndNode(DbId.i, TopicId.i, NodeId.i, List Messages.BakaShrot_Message()) - ClearList(Messages()) - - SetDatabaseLong(DbId, 0, TopicId) - SetDatabaseLong(DbId, 1, NodeId) - - If Not DatabaseQuery(DbId, "SELECT message_id, message_data FROM data WHERE topic_id = ? AND node_id = ? ORDER BY message_id") - ProcedureReturn #False - EndIf - - While NextDatabaseRow(DbId) - AddElement(Messages()) - Messages()\MessageId = GetDatabaseLong(DbId, 0) - Messages()\JsonData = GetDatabaseString(DbId, 1) - Wend - FinishDatabaseQuery(DbId) - - ProcedureReturn #True -EndProcedure - - -; Gets every message stored under a given message_id, regardless of which -; topic/node it belongs to - the standalone "message_id" index. -Procedure.i GetMessagesByMessageId(DbId.i, MessageId.i, List Messages.BakaShrot_Message()) - ClearList(Messages()) - - SetDatabaseLong(DbId, 0, MessageId) - - If Not DatabaseQuery(DbId, "SELECT message_id, message_data FROM data WHERE message_id = ?") - ProcedureReturn #False - EndIf - - While NextDatabaseRow(DbId) - AddElement(Messages()) - Messages()\MessageId = GetDatabaseLong(DbId, 0) - Messages()\JsonData = GetDatabaseString(DbId, 1) - Wend - FinishDatabaseQuery(DbId) - - ProcedureReturn #True -EndProcedure - - -; Test helper: scans every stored message and collects the value found at -; JsonPath (e.g. "$.messageData.MsgType"), skipping messages where it's -; missing or null, and those that aren't JSON (is_json = 0: ->> fails the -; whole query on one). Kept basic on purpose - no paging, no topic/node filter. -Procedure.i GetValuesAtJsonPath(DbId.i, JsonPath.s, List Values.s()) - ClearList(Values()) - - SetDatabaseString(DbId, 0, JsonPath) - SetDatabaseString(DbId, 1, JsonPath) - - If Not DatabaseQuery(DbId, "SELECT message_data ->> ? FROM data WHERE is_json = 1 AND message_data ->> ? IS NOT NULL") - ProcedureReturn #False - EndIf - - While NextDatabaseRow(DbId) - AddElement(Values()) - Values() = GetDatabaseString(DbId, 0) - Wend - FinishDatabaseQuery(DbId) - - ProcedureReturn #True -EndProcedure - - -; Returns the highest message_id stored for a given topic_id/node_id pair, -; or -1 if there's none yet. Will likely grow into a cached counter later. -Procedure.i GetLatestMessageId(DbId.i, TopicId.i, NodeId.i) - Protected MessageId.i = -1 - - SetDatabaseLong(DbId, 0, TopicId) - SetDatabaseLong(DbId, 1, NodeId) - - If DatabaseQuery(DbId, "SELECT COALESCE(MAX(message_id), -1) FROM data WHERE topic_id = ? AND node_id = ?") - If NextDatabaseRow(DbId) - MessageId = GetDatabaseLong(DbId, 0) - EndIf - FinishDatabaseQuery(DbId) - EndIf - - ProcedureReturn MessageId -EndProcedure - - - -; Reads the attachment's size, state and SHA-256 (COALESCE(a.size, 0), -; COALESCE(a.state, 0), a.sha256) from Column on into *Message. -Procedure BakaShrot_ReadAttachmentColumns(DbId.i, Column.i, *Message.BakaShrot_Message) - *Message\AttachmentSize = GetDatabaseQuad(DbId, Column) - *Message\AttachmentReady = Bool(*Message\AttachmentSize > 0 And GetDatabaseLong(DbId, Column + 1) = 2) - FillMemory(@*Message\AttachmentSha256[0], #BakaShrot_Sha256Size, 0) - If *Message\AttachmentSize > 0 And DatabaseColumnSize(DbId, Column + 2) = #BakaShrot_Sha256Size - GetDatabaseBlob(DbId, Column + 2, @*Message\AttachmentSha256[0], #BakaShrot_Sha256Size) - EndIf -EndProcedure - - -; Fills *Message with the message that has the highest message_id for a -; topic_id/node_id pair. -; Returns #False if there's none, or if the query failed. -Procedure.i GetLatestMessage(DbId.i, TopicId.i, NodeId.i, *Message.BakaShrot_Message) - Protected Found.i - - SetDatabaseLong(DbId, 0, TopicId) - SetDatabaseLong(DbId, 1, NodeId) - If Not DatabaseQuery(DbId, "SELECT d.message_id, d.message_data, d.pushed_at, COALESCE(a.size, 0), COALESCE(a.state, 0), a.sha256 " + - "FROM data d LEFT JOIN attachments a ON a.topic_id = d.topic_id AND a.node_id = d.node_id AND a.message_id = d.message_id " + - "WHERE d.topic_id = ? AND d.node_id = ? ORDER BY d.message_id DESC LIMIT 1") - ProcedureReturn #False - EndIf - - Found = NextDatabaseRow(DbId) - If Found - *Message\MessageId = GetDatabaseQuad(DbId, 0) - *Message\JsonData = GetDatabaseString(DbId, 1) - *Message\PushedAt = GetDatabaseQuad(DbId, 2) - BakaShrot_ReadAttachmentColumns(DbId, 3, *Message) - EndIf - FinishDatabaseQuery(DbId) - - ProcedureReturn Found -EndProcedure - - -; --- Raw queries ------------------------------------------------------------- - -; Most rows a raw query can return. -#BakaShrot_Query_MaxRows = 10000 - -; Telling the end of a query's rows from an error that cut them short. -; PureBasic's NextDatabaseRow() returns #False for both, and DatabaseError() -; stays empty after such an error: a JSON function (->>, json_extract()) -; reaching a row that isn't JSON stops the query with "malformed JSON", and -; the query looked like it simply had no (more) rows. So once the rows end, -; SQLite itself is asked: sqlite3_errcode() on the connection is SQLITE_DONE -; (or SQLITE_ROW/SQLITE_OK) if they really ended, the error otherwise, with -; sqlite3_errmsg16() telling which. Same #BakaShrot_Storage_SqliteLibrary as -; PureBasic's (DatabaseID() is its sqlite3 handle), like Writer.pbi. -; Without #BakaShrot_Storage_ExternalSqlite, PureBasic's own SQLite is linked -; in and not reachable this way: DatabaseError() is checked instead, which -; misses it. -#BakaShrot_Query_SqliteOk = 0 -#BakaShrot_Query_SqliteRow = 100 -#BakaShrot_Query_SqliteDone = 101 - -CompilerIf #BakaShrot_Storage_ExternalSqlite - PrototypeC.l BakaShrot_Query_SqliteErrCode(Db.i) - PrototypeC.i BakaShrot_Query_SqliteErrMsg16(Db.i) - - Structure BakaShrot_Query_SqliteApi - Library.i - ErrCode.BakaShrot_Query_SqliteErrCode - ErrMsg16.BakaShrot_Query_SqliteErrMsg16 - EndStructure - - Global BakaShrot_Query_Sqlite.BakaShrot_Query_SqliteApi - ; Queries run on every client's thread, the first one loads it. - Global BakaShrot_Query_SqliteMutex.i = CreateMutex() - - ; Returns #False if the SQLite library or its functions can't be found. - Procedure.i BakaShrot_Query_LoadSqlite() - Protected Loaded.i - - LockMutex(BakaShrot_Query_SqliteMutex) - With BakaShrot_Query_Sqlite - If Not \Library - \Library = OpenLibrary(#PB_Any, #BakaShrot_Storage_SqliteLibrary) - If \Library - \ErrCode = GetFunction(\Library, "sqlite3_errcode") - \ErrMsg16 = GetFunction(\Library, "sqlite3_errmsg16") - If Not \ErrCode Or Not \ErrMsg16 - CloseLibrary(\Library) - \Library = 0 - EndIf - EndIf - EndIf - Loaded = Bool(\Library) - EndWith - UnlockMutex(BakaShrot_Query_SqliteMutex) - - ProcedureReturn Loaded - EndProcedure -CompilerEndIf - -; Runs a raw SQL query from a client, read-only, and fills *Result\s with its -; rows as JSON: {"columns": ["name", ...], "rows": [["value", ...], ...]}. -; Every value is a string, or null for NULL: PureBasic reports no column -; types for SQLite. Wrap a blob in hex() to read it. -; -; Read-only, enforced three ways: -; 1. It must start with SELECT or WITH. -; 2. It runs on its own connection to DatabasePath, opened just for it, -; with PRAGMA query_only = ON. Writes fail, even WITH ... DELETE, and a -; query that turns the pragma off only does so for its own connection. -; 3. Only the first statement runs, anything after a ";" is ignored. -; -; An error while reading the rows fails the whole query, with SQLite's -; message: a JSON function on a row that isn't JSON gives "malformed JSON", -; add "is_json = 1" to the WHERE. Never a partial or empty result instead. -; -; Thread-safe, since it never touches a shared handle. -; Returns #False with *Error\s set if it's refused, fails, or has more than -; #BakaShrot_Query_MaxRows rows. -Procedure.i RunReadOnlyQuery(DatabasePath.s, Sql.s, *Result.String, *Error.String) - Protected DbId.i, JsonId.i, *Root, *Columns, *Rows, *Row - Protected Column.i, RowCount.i, Start.s, ErrorCode.l - - Start = UCase(Trim(ReplaceString(ReplaceString(ReplaceString(Sql, #CR$, " "), #LF$, " "), #TAB$, " "))) - If Left(Start, 6) <> "SELECT" And Left(Start, 4) <> "WITH" - *Error\s = "Only SELECT and WITH queries are allowed" - ProcedureReturn #False - EndIf - - ; Without it, errors in the rows would go unnoticed: refused instead. - CompilerIf #BakaShrot_Storage_ExternalSqlite - If Not BakaShrot_Query_LoadSqlite() - *Error\s = "Queries can't be checked for errors: sqlite3_errcode() not found" - ProcedureReturn #False - EndIf - CompilerEndIf - - DbId = OpenStorageDatabase(DatabasePath) - If Not DbId - *Error\s = "The database couldn't be opened" - ProcedureReturn #False - EndIf - - If Not DatabaseUpdate(DbId, "PRAGMA query_only = ON") - *Error\s = "The database couldn't be made read-only" - CloseDatabase(DbId) - ProcedureReturn #False - EndIf - - If Not DatabaseQuery(DbId, Sql) - *Error\s = DatabaseError() - CloseDatabase(DbId) - ProcedureReturn #False - EndIf - - ; WITH ... DELETE and the likes have no columns. query_only stops them - ; anyway, but PureBasic doesn't report that, they'd look like no rows. - If DatabaseColumns(DbId) = 0 - *Error\s = "The query doesn't return any column, only SELECT queries are allowed" - FinishDatabaseQuery(DbId) - CloseDatabase(DbId) - ProcedureReturn #False - EndIf - - JsonId = CreateJSON(#PB_Any) - If Not JsonId - *Error\s = "Out of memory" - FinishDatabaseQuery(DbId) - CloseDatabase(DbId) - ProcedureReturn #False - EndIf - *Root = SetJSONObject(JSONValue(JsonId)) - - *Columns = SetJSONArray(AddJSONMember(*Root, "columns")) - For Column = 0 To DatabaseColumns(DbId) - 1 - SetJSONString(AddJSONElement(*Columns), DatabaseColumnName(DbId, Column)) - Next - - *Rows = SetJSONArray(AddJSONMember(*Root, "rows")) - While NextDatabaseRow(DbId) - RowCount + 1 - If RowCount > #BakaShrot_Query_MaxRows - *Error\s = "More than " + Str(#BakaShrot_Query_MaxRows) + " rows, add a LIMIT" - FreeJSON(JsonId) - FinishDatabaseQuery(DbId) - CloseDatabase(DbId) - ProcedureReturn #False - EndIf - - *Row = SetJSONArray(AddJSONElement(*Rows)) - For Column = 0 To DatabaseColumns(DbId) - 1 - If CheckDatabaseNull(DbId, Column) - SetJSONNull(AddJSONElement(*Row)) - Else - SetJSONString(AddJSONElement(*Row), GetDatabaseString(DbId, Column)) - EndIf - Next - Wend - - ; Did the rows end, or did an error end them? (see above): "malformed - ; JSON", a write stopped by query_only (DELETE ... RETURNING), ... - ; Asked before FinishDatabaseQuery(), while the failed step is the last - ; thing done on this connection. A false alarm would refuse a good - ; query, it can't hide a bad one. - CompilerIf #BakaShrot_Storage_ExternalSqlite - ErrorCode = BakaShrot_Query_Sqlite\ErrCode(DatabaseID(DbId)) - If ErrorCode <> #BakaShrot_Query_SqliteOk And ErrorCode <> #BakaShrot_Query_SqliteRow And ErrorCode <> #BakaShrot_Query_SqliteDone - *Error\s = PeekS(BakaShrot_Query_Sqlite\ErrMsg16(DatabaseID(DbId)), -1, #PB_Unicode) - If *Error\s = "" - *Error\s = "SQLite error " + Str(ErrorCode) - EndIf - If FindString(*Error\s, "JSON", 1, #PB_String_NoCase) - *Error\s + " (a row isn't JSON: add is_json = 1 to the WHERE)" - EndIf - FreeJSON(JsonId) - FinishDatabaseQuery(DbId) - CloseDatabase(DbId) - ProcedureReturn #False - EndIf - CompilerEndIf - FinishDatabaseQuery(DbId) - - ; Without #BakaShrot_Storage_ExternalSqlite, the only check there is. It - ; misses errors in the rows: PureBasic doesn't report them. - ; !!! DatabaseError() may be shared by every thread, see - ; !!! Design/StorageConcurrency.md, another thread's error could show up here. - CompilerIf Not #BakaShrot_Storage_ExternalSqlite - If DatabaseError() <> "" - *Error\s = DatabaseError() - FreeJSON(JsonId) - CloseDatabase(DbId) - ProcedureReturn #False - EndIf - CompilerEndIf - - *Result\s = ComposeJSON(JsonId) - FreeJSON(JsonId) - CloseDatabase(DbId) - - ProcedureReturn #True -EndProcedure - - -; --- Replication ------------------------------------------------------------- - -; Fills Pairs() with where this node is at: the highest message id it has for -; every topic/node id combination, ordered by topic then node id. Read from -; node_heads, kept up to date by a trigger, see SetupStorageDatabase(). -; Returns #False if the query failed. -Procedure.i GetSyncState(DbId.i, List Pairs.BakaShrot_SyncPair()) - ClearList(Pairs()) - - If Not DatabaseQuery(DbId, "SELECT topic_id, node_id, max_message_id FROM node_heads ORDER BY topic_id, node_id") - ProcedureReturn #False - EndIf - - While NextDatabaseRow(DbId) - AddElement(Pairs()) - Pairs()\TopicId = GetDatabaseLong(DbId, 0) - Pairs()\NodeId = GetDatabaseLong(DbId, 1) - Pairs()\MessageId = GetDatabaseQuad(DbId, 2) - Wend - FinishDatabaseQuery(DbId) - - ProcedureReturn #True -EndProcedure - - -; Fills Messages() with up to Limit messages of a topic/node id combination -; whose message_id is above AfterMessageId, in message_id order. Stops early -; once their JSON adds up to MaxChars characters or more (0: no such limit), -; the one that got there included, so big messages aren't all read at once. -; If *More is given, *More\i is set to #True if more messages follow the -; last one read. -; Returns #False if the query failed. -Procedure.i GetMessagesAfter(DbId.i, TopicId.i, NodeId.i, AfterMessageId.q, Limit.i, MaxChars.i, List Messages.BakaShrot_Message(), *More.Integer = 0) - Protected Chars.i, More.i - - ClearList(Messages()) - - ; One more than asked for, to tell if more follow. - SetDatabaseLong(DbId, 0, TopicId) - SetDatabaseLong(DbId, 1, NodeId) - SetDatabaseQuad(DbId, 2, AfterMessageId) - SetDatabaseLong(DbId, 3, Limit + 1) - If Not DatabaseQuery(DbId, "SELECT d.message_id, d.message_data, d.pushed_at, COALESCE(a.size, 0), COALESCE(a.state, 0), a.sha256 " + - "FROM data d LEFT JOIN attachments a ON a.topic_id = d.topic_id AND a.node_id = d.node_id AND a.message_id = d.message_id " + - "WHERE d.topic_id = ? AND d.node_id = ? AND d.message_id > ? ORDER BY d.message_id LIMIT ?") - ProcedureReturn #False - EndIf - - While NextDatabaseRow(DbId) - If ListSize(Messages()) >= Limit Or (MaxChars > 0 And Chars >= MaxChars) - More = #True - Break - EndIf - AddElement(Messages()) - Messages()\MessageId = GetDatabaseQuad(DbId, 0) - Messages()\JsonData = GetDatabaseString(DbId, 1) - Messages()\PushedAt = GetDatabaseQuad(DbId, 2) - BakaShrot_ReadAttachmentColumns(DbId, 3, @Messages()) - Chars + Len(Messages()\JsonData) - Wend - FinishDatabaseQuery(DbId) - - If *More - *More\i = More - EndIf - ProcedureReturn #True -EndProcedure - - -; Stores a message replicated from a peer, under the ids it has on its origin. -; If that topic/node/message id is already stored, it's kept as is, and the -; new one is dropped, even if it differs. See Design/ReplicationIssues.md. -; On its own connection: for tools writing while the server is stopped -; (BenchSeed). The server itself writes through Writer.pbi. -; PushedAt: when it was pushed to its origin, ms since 1970 UTC. -; Returns #False if the insert failed. -Procedure.i InsertReplicatedMessage(DbId.i, TopicId.i, NodeId.i, MessageId.q, JsonData.s, PushedAt.q) - SetDatabaseLong(DbId, 0, TopicId) - SetDatabaseLong(DbId, 1, NodeId) - SetDatabaseQuad(DbId, 2, MessageId) - SetDatabaseString(DbId, 3, JsonData) - SetDatabaseQuad(DbId, 4, PushedAt) - ProcedureReturn DatabaseUpdate(DbId, "INSERT OR IGNORE INTO data (topic_id, node_id, message_id, message_data, pushed_at) VALUES (?, ?, ?, ?, ?)") -EndProcedure - - - -; Every write: pushes (group commit), replicated batches, the WAL checkpoints. -XIncludeFile "Writer.pbi" - -; Attachments: uploads, parts, reading them back, the replicated ones. -XIncludeFile "Attachments.pbi" - - -; Usage example. Only compiled when this file is run directly (F5 in the -; IDE), not when it's included as a module by the rest of the project. -CompilerIf #PB_Compiler_IsMainFile - - Define DbId = OpenStorageDatabase("storage.sqlite") - - If DbId - If SetupStorageDatabase(DbId) - Insert(DbId, 1, 1, 1, ~"{\"messageData\": {\"MsgType\": \"hello\"}}") - Insert(DbId, 1, 1, 2, ~"{\"messageData\": {\"MsgType\": \"world\"}}") - - NewList Messages.BakaShrot_Message() - GetMessagesByTopicAndNode(DbId, 1, 1, Messages()) - ForEach Messages() - Debug "Message #" + Str(Messages()\MessageId) + ": " + Messages()\JsonData - Next - - NewList MsgTypes.s() - GetValuesAtJsonPath(DbId, "$.messageData.MsgType", MsgTypes()) - ForEach MsgTypes() - Debug "MsgType: " + MsgTypes() - Next - - Debug "Latest message id: " + Str(GetLatestMessageId(DbId, 1, 1)) - Else - Debug "Failed to set up database: " + DatabaseError() - EndIf - - CloseDatabase(DbId) - Else - Debug "Failed to open database: " + DatabaseError() - EndIf - -CompilerEndIf diff --git a/Server/Storage/Writer.pbi b/Server/Storage/Writer.pbi deleted file mode 100644 index 2de5b67..0000000 --- a/Server/Storage/Writer.pbi +++ /dev/null @@ -1,1016 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: Writer.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; BakaShrot Storage Writer -; -; Every write the server does to its database goes through here: -; InsertNextMessage() pushes, grouped (group commit), stamped -; with the time they arrived (pushed_at) -; InsertReplicatedMessages() batches from peers, with their pushed_at, -; skipping those already past their max age -; DeleteStorageMessagesBefore() the retention (Retention.pbi) -; 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 #BakaShrot_Storage_SqliteLibrary as PureBasic's (DatabaseID() is -; its sqlite3 handle). Without #BakaShrot_Storage_ExternalSqlite (see -; Storage.pbi), 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 (node_heads, which deleting messages leaves as is: -; ids never go back), 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 - - -#BakaShrot_Storage_RawSqlite = #BakaShrot_Storage_ExternalSqlite - -#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 - ; When it arrived, ms since 1970 UTC. - PushedAt.q - ; Its attachment, a complete upload (blobs), 0 for none. - BlobId.q - - ; 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 - Delete.i - RaiseHead.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, PushedAt.q) - 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) - BakaShrot_Sqlite\BindInt64(Statement, 5, PushedAt) - 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) - SetDatabaseQuad(DbId, 4, PushedAt) - If Not DatabaseUpdate(DbId, PeekS(Statement)) - BakaShrot_Storage_Writer\LastError = DatabaseError() - ProcedureReturn -1 - EndIf - ProcedureReturn AffectedDatabaseRows(DbId) - CompilerEndIf -EndProcedure - - -; The highest message id ever stored for a topic/node id, 0 if none, -1 on -; failure. Still there once deleted: node_heads keeps it. -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 - - -; Raises a topic/node id's head (node_heads) to MessageId, if it's lower, -; like inserting that message would. Returns #False if it failed. -Procedure.i BakaShrot_Writer_RaiseHead(TopicId.i, NodeId.i, MessageId.q) - CompilerIf #BakaShrot_Storage_RawSqlite - Protected Statement.i = BakaShrot_Storage_Writer\RaiseHead - BakaShrot_Sqlite\BindInt64(Statement, 1, TopicId) - BakaShrot_Sqlite\BindInt64(Statement, 2, NodeId) - BakaShrot_Sqlite\BindInt64(Statement, 3, MessageId) - If BakaShrot_Sqlite\Step_(Statement) <> #BakaShrot_Sqlite_Done - BakaShrot_Storage_Writer\LastError = BakaShrot_Writer_Error() - BakaShrot_Sqlite\Reset(Statement) - ProcedureReturn #False - EndIf - BakaShrot_Sqlite\Reset(Statement) - ProcedureReturn #True - CompilerElse - Protected DbId.i = BakaShrot_Storage_Writer\DbId - SetDatabaseLong(DbId, 0, TopicId) - SetDatabaseLong(DbId, 1, NodeId) - SetDatabaseQuad(DbId, 2, MessageId) - If Not DatabaseUpdate(DbId, PeekS(BakaShrot_Storage_Writer\RaiseHead)) - BakaShrot_Storage_Writer\LastError = DatabaseError() - ProcedureReturn #False - EndIf - ProcedureReturn #True - CompilerEndIf -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, #BakaShrot_Storage_SqliteLibrary) - 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) - BakaShrot_Writer_Finalize(@\Delete) - BakaShrot_Writer_Finalize(@\RaiseHead) - 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 = #BakaShrot_Storage_SqliteLibrary + " 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, pushed_at) VALUES (?1, ?2, ?3, ?4, ?5)") - \InsertOrIgnore = BakaShrot_Writer_Prepare("INSERT OR IGNORE INTO data (topic_id, node_id, message_id, message_data, pushed_at) VALUES (?1, ?2, ?3, ?4, ?5)") - ; node_heads first: it outlives the deleted messages. data too, in - ; case a database was written to by something without the trigger. - \MaxId = BakaShrot_Writer_Prepare("SELECT COALESCE(MAX(m), 0) FROM (SELECT max_message_id AS m FROM node_heads WHERE topic_id = ?1 AND node_id = ?2 " + - "UNION ALL SELECT MAX(message_id) FROM data WHERE topic_id = ?1 AND node_id = ?2)") - ; Some at a time (?3), so pushes get the write mutex in between. - \Delete = BakaShrot_Writer_Prepare("DELETE FROM data WHERE rowid IN (SELECT rowid FROM data WHERE topic_id = ?1 AND pushed_at < ?2 LIMIT ?3)") - ; What the trigger does on an insert, for the messages skipped instead. - \RaiseHead = BakaShrot_Writer_Prepare("INSERT INTO node_heads (topic_id, node_id, max_message_id) VALUES (?1, ?2, ?3) " + - "ON CONFLICT (topic_id, node_id) DO UPDATE SET max_message_id = MAX(max_message_id, excluded.max_message_id)") - If Not \Begin Or Not \Commit Or Not \Rollback Or Not \Insert Or Not \InsertOrIgnore Or Not \MaxId Or Not \Delete Or Not \RaiseHead - *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 - - -; Claims a complete upload (blobs state 1) of TopicId/NodeId for a message: -; state 2. Returns #False if it isn't one, someone else's, or attached already. -Procedure.i BakaShrot_Writer_ClaimBlob(BlobId.q, TopicId.i, NodeId.i) - Protected DbId.i = BakaShrot_Storage_Writer\DbId - SetDatabaseQuad(DbId, 0, BlobId) - SetDatabaseLong(DbId, 1, TopicId) - SetDatabaseLong(DbId, 2, NodeId) - If Not DatabaseUpdate(DbId, "UPDATE blobs SET state = 2 WHERE blob_id = ? AND topic_id = ? AND node_id = ? AND state = 1") - BakaShrot_Storage_Writer\LastError = DatabaseError() - ProcedureReturn #False - EndIf - If AffectedDatabaseRows(DbId) <> 1 - BakaShrot_Storage_Writer\LastError = "the upload isn't complete, or isn't this client's for that topic" - ProcedureReturn #False - EndIf - ProcedureReturn #True -EndProcedure - -; Gives a claimed upload back (state 1), its message couldn't be stored. -Procedure BakaShrot_Writer_UnclaimBlob(BlobId.q) - Protected DbId.i = BakaShrot_Storage_Writer\DbId - SetDatabaseQuad(DbId, 0, BlobId) - DatabaseUpdate(DbId, "UPDATE blobs SET state = 1 WHERE blob_id = ?") -EndProcedure - -; The attachments row of a pushed message, from its claimed upload. -Procedure.i BakaShrot_Writer_LinkBlob(TopicId.i, NodeId.i, MessageId.q, BlobId.q) - Protected DbId.i = BakaShrot_Storage_Writer\DbId - SetDatabaseLong(DbId, 0, TopicId) - SetDatabaseLong(DbId, 1, NodeId) - SetDatabaseQuad(DbId, 2, MessageId) - SetDatabaseQuad(DbId, 3, BlobId) - If Not DatabaseUpdate(DbId, "INSERT INTO attachments (topic_id, node_id, message_id, size, sha256, blob_id, state) " + - "SELECT ?, ?, ?, size, sha256, blob_id, 2 FROM blobs WHERE blob_id = ?") Or AffectedDatabaseRows(DbId) <> 1 - BakaShrot_Storage_Writer\LastError = "can't attach the upload: " + DatabaseError() - ProcedureReturn #False - EndIf - ProcedureReturn #True -EndProcedure - -; Deletes a message just inserted in this transaction, its attachment failed. -Procedure BakaShrot_Writer_DropMessage(TopicId.i, NodeId.i, MessageId.q) - Protected DbId.i = BakaShrot_Storage_Writer\DbId - SetDatabaseLong(DbId, 0, TopicId) - SetDatabaseLong(DbId, 1, NodeId) - SetDatabaseQuad(DbId, 2, MessageId) - DatabaseUpdate(DbId, "DELETE FROM data WHERE topic_id = ? AND node_id = ? AND message_id = ?") -EndProcedure - -; The attachments row of a replicated message: its data comes later -; (Attachments.pbi), state 0 (missing), or 3 (not kept here) past MaxSize. -Procedure.i BakaShrot_Writer_AddReplicatedAttachment(TopicId.i, NodeId.i, *Message.BakaShrot_ReplicatedMessage, MaxSize.q) - Protected DbId.i = BakaShrot_Storage_Writer\DbId - SetDatabaseLong(DbId, 0, TopicId) - SetDatabaseLong(DbId, 1, NodeId) - SetDatabaseQuad(DbId, 2, *Message\MessageId) - SetDatabaseQuad(DbId, 3, *Message\AttachmentSize) - SetDatabaseBlob(DbId, 4, @*Message\AttachmentSha256[0], #BakaShrot_Sha256Size) - If *Message\AttachmentSize > MaxSize - SetDatabaseLong(DbId, 5, 3) - Else - SetDatabaseLong(DbId, 5, 0) - EndIf - If Not DatabaseUpdate(DbId, "INSERT OR IGNORE INTO attachments (topic_id, node_id, message_id, size, sha256, blob_id, state) VALUES (?, ?, ?, ?, ?, NULL, ?)") - BakaShrot_Storage_Writer\LastError = DatabaseError() - ProcedureReturn #False - EndIf - ProcedureReturn #True -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 - *Job\MessageId = -1 - - ; Its upload first: nothing is stored if it can't be claimed. - If MessageId > 0 And *Job\BlobId And Not BakaShrot_Writer_ClaimBlob(*Job\BlobId, *Job\TopicId, *Job\NodeId) - MessageId = -1 - EndIf - - If MessageId > 0 And BakaShrot_Writer_InsertRow(BakaShrot_Storage_Writer\Insert, *Job\TopicId, *Job\NodeId, MessageId, JsonData, *Job\PushedAt) = 1 - If *Job\BlobId And Not BakaShrot_Writer_LinkBlob(*Job\TopicId, *Job\NodeId, MessageId, *Job\BlobId) - BakaShrot_Writer_DropMessage(*Job\TopicId, *Job\NodeId, MessageId) - BakaShrot_Writer_UnclaimBlob(*Job\BlobId) - Else - *Job\MessageId = MessageId - EndIf - ; Taken either way: node_heads went up. - BakaShrot_Storage_Writer\NextIds(Key) = MessageId + 1 - ElseIf MessageId > 0 And *Job\BlobId - BakaShrot_Writer_UnclaimBlob(*Job\BlobId) - EndIf - - If *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. Stamped with the time it got here (pushed_at). -; BlobId: its attachment, a complete upload of this topic and node -; (Attachments.pbi), 0 for none: attached in the same transaction. -; 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, BlobId.q = 0) - Protected Job.BakaShrot_PushJob - Protected NewList Jobs.i() - Protected StartTicks.q - - Job\TopicId = TopicId - Job\NodeId = NodeId - Job\JsonData = JsonData - Job\PushedAt = BakaShrot_NowUtcMs() - Job\BlobId = BlobId - 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 and pushed_at 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). -; Messages pushed before SkipBeforeMs (ms since 1970 UTC, 0 for none) are -; past this server's max age for the topic already: not stored, but the -; pair's head still goes up to them, so the peer doesn't send them again. -; *Skipped\i, if given, gets how many. -; A message's attachment gets its row, its data comes later (Attachments.pbi), -; unless it's bigger than MaxAttachmentSize: not kept here then. -; 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, SkipBeforeMs.q = 0, *Skipped.Integer = 0, MaxAttachmentSize.q = #BakaShrot_MaxAttachmentSize) - Protected Stored.i, Inserted.i, Key.s, JsonData.s, Skipped.i, LastMessageId.q - - 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() - LastMessageId = Messages()\MessageId - If SkipBeforeMs > 0 And Messages()\PushedAt < SkipBeforeMs - Skipped + 1 - Continue - EndIf - JsonData = Messages()\JsonData - Inserted = BakaShrot_Writer_InsertRow(BakaShrot_Storage_Writer\InsertOrIgnore, TopicId, NodeId, Messages()\MessageId, JsonData, Messages()\PushedAt) - If Inserted < 0 - Stored = #False - Break - EndIf - If Inserted = 1 And Messages()\AttachmentSize > 0 And Not BakaShrot_Writer_AddReplicatedAttachment(TopicId, NodeId, @Messages(), MaxAttachmentSize) - 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 - - ; The skipped ones count as received: the head covers the whole batch, - ; and the next push goes after it. - If Stored And Skipped > 0 - If BakaShrot_Writer_RaiseHead(TopicId, NodeId, LastMessageId) - If FindMapElement(BakaShrot_Storage_Writer\NextIds(), Key) - If LastMessageId + 1 > BakaShrot_Storage_Writer\NextIds() - BakaShrot_Storage_Writer\NextIds() = LastMessageId + 1 - EndIf - EndIf - Else - Stored = #False - EndIf - EndIf - - 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) - If *Skipped - *Skipped\i = Skipped - EndIf - ProcedureReturn Stored -EndProcedure - - -; Deletes up to Limit messages of TopicId pushed before BeforeMs (ms since -; 1970 UTC), in one statement under the write mutex: call it again while it -; deletes Limit, pushes get their turn in between. node_heads is left as is -; (see SetupStorageDatabase()). -; Returns how many were deleted, -1 with the reason in *Error\s. -Procedure.i DeleteStorageMessagesBefore(TopicId.i, BeforeMs.q, Limit.i, *Error.String) - Protected Deleted.i = -1 - - LockMutex(BakaShrot_Storage_WriteMutex) - If Not BakaShrot_Storage_Writer\DbId - UnlockMutex(BakaShrot_Storage_WriteMutex) - *Error\s = "the storage writer isn't open" - ProcedureReturn -1 - EndIf - - CompilerIf #BakaShrot_Storage_RawSqlite - Protected Statement.i = BakaShrot_Storage_Writer\Delete - BakaShrot_Sqlite\BindInt64(Statement, 1, TopicId) - BakaShrot_Sqlite\BindInt64(Statement, 2, BeforeMs) - BakaShrot_Sqlite\BindInt64(Statement, 3, Limit) - If BakaShrot_Sqlite\Step_(Statement) = #BakaShrot_Sqlite_Done - Deleted = BakaShrot_Sqlite\Changes(BakaShrot_Storage_Writer\Handle) - Else - *Error\s = BakaShrot_Writer_Error() - EndIf - BakaShrot_Sqlite\Reset(Statement) - CompilerElse - Protected DbId.i = BakaShrot_Storage_Writer\DbId - SetDatabaseLong(DbId, 0, TopicId) - SetDatabaseQuad(DbId, 1, BeforeMs) - SetDatabaseLong(DbId, 2, Limit) - If DatabaseUpdate(DbId, PeekS(BakaShrot_Storage_Writer\Delete)) - Deleted = AffectedDatabaseRows(DbId) - Else - *Error\s = DatabaseError() - EndIf - CompilerEndIf - - UnlockMutex(BakaShrot_Storage_WriteMutex) - ProcedureReturn Deleted -EndProcedure - - -; Adds a row to the "topics" or "nodes" table (Table), for Id, named Name -; (its id in digits if it has none), Origin "peer" or "id", see -; Server/Storage/Names.pbi. A row already there for that id is kept. -; Returns #False with the reason in *Error\s. -Procedure.i RegisterStorageName(Table.s, Id.i, Name.s, Origin.s, *Error.String) - Protected DbId.i, Stored.i - - LockMutex(BakaShrot_Storage_WriteMutex) - DbId = BakaShrot_Storage_Writer\DbId - If Not DbId - UnlockMutex(BakaShrot_Storage_WriteMutex) - *Error\s = "the storage writer isn't open" - ProcedureReturn #False - EndIf - - SetDatabaseLong(DbId, 0, Id) - SetDatabaseString(DbId, 1, Name) - SetDatabaseString(DbId, 2, Origin) - Stored = DatabaseUpdate(DbId, "INSERT OR IGNORE INTO " + Table + " VALUES (?, ?, ?)") - If Not Stored - *Error\s = DatabaseError() - EndIf - - UnlockMutex(BakaShrot_Storage_WriteMutex) - ProcedureReturn Stored -EndProcedure diff --git a/Server/Storage/db_schema_v0.dbml b/Server/Storage/db_schema_v0.dbml deleted file mode 100644 index a878064..0000000 --- a/Server/Storage/db_schema_v0.dbml +++ /dev/null @@ -1,32 +0,0 @@ - -table archives { - # UTC Unix Timestamp after which this archived message should be deleted. - delete_by ??? [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] -} - -# 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] -} - -index { - data, on combined group_id/node_id - data, on message_id - attachements, on combined group_id/node_id - attachements, on message_id -} - -# Note, ignore it -# msg_type TEXT GENERATED ALWAYS AS (data ->> '$.messageData.MsgType') VIRTUAL diff --git a/Server/Storage/db_schema_v1.dbml b/Server/Storage/db_schema_v1.dbml deleted file mode 100644 index f22ad1e..0000000 --- a/Server/Storage/db_schema_v1.dbml +++ /dev/null @@ -1,34 +0,0 @@ -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] - - indexes { - (group_id, node_id) - message_id - } -} - -// Create it, but we'll implement this later. -table attachements { - group_id integer [not null] - node_id integer [not null] - message_id integer [not null] - attachement_data blob [not null] - - indexes { - (group_id, node_id) - message_id - } -} - -// Note, ignore it -// msg_type TEXT GENERATED ALWAYS AS (data ->> '$.messageData.MsgType') VIRTUAL diff --git a/Server/Storage/db_schema_v2.dbml b/Server/Storage/db_schema_v2.dbml deleted file mode 100644 index 7ffbebf..0000000 --- a/Server/Storage/db_schema_v2.dbml +++ /dev/null @@ -1,45 +0,0 @@ -// Changes from v1, on "data" only: -// - UNIQUE (group_id, node_id, message_id), so a message id can't be stored twice. -// Its index also serves (group_id, node_id) lookups, replacing v1's index on them. -// - is_json, set by SQLite on insert, for JSON queries on message_data. -// -// Needs SQLite 3.38+ with its JSON functions (json_valid, ->>), see Storage.pbi. - -table archives { - // UTC Unix Timestamp after which this archived message should be deleted. - delete_by integer [not null] - - message_data text [not null] -} - -table data { - group_id integer [not null] - node_id integer [not null] - message_id integer [not null] - message_data text [not null] - - // 1 if message_data is well-formed JSON, 0 otherwise. - // Can't be written, SQLite computes it on insert and stores it. - is_json integer [not null, note: 'GENERATED ALWAYS AS (json_valid(message_data)) STORED'] - - indexes { - (group_id, node_id, message_id) [unique] - message_id - } -} - -// Create it, but we'll implement this later. -table attachements { - group_id integer [not null] - node_id integer [not null] - message_id integer [not null] - attachement_data blob [not null] - - indexes { - (group_id, node_id) - message_id - } -} - -// Note, ignore it -// msg_type TEXT GENERATED ALWAYS AS (data ->> '$.messageData.MsgType') VIRTUAL diff --git a/Server/Storage/db_schema_v3.dbml b/Server/Storage/db_schema_v3.dbml deleted file mode 100644 index ff48129..0000000 --- a/Server/Storage/db_schema_v3.dbml +++ /dev/null @@ -1,62 +0,0 @@ -// Changes from v2: -// - node_heads, the highest message id of every group/node id, kept by the -// trg_data_node_heads trigger on every insert into data. The sync state -// (GetSyncState()) reads it instead of a GROUP BY over every message. -// Filled from data when it's created on an existing database. -// Nothing deletes from data yet, whatever does must update it too. -// -// Needs SQLite 3.38+ with its JSON functions (json_valid, ->>), see Storage.pbi. -// The database is in WAL mode, see Storage.pbi and Writer.pbi. - -table archives { - // UTC Unix Timestamp after which this archived message should be deleted. - delete_by integer [not null] - - message_data text [not null] -} - -table data { - group_id integer [not null] - node_id integer [not null] - message_id integer [not null] - message_data text [not null] - - // 1 if message_data is well-formed JSON, 0 otherwise. - // Can't be written, SQLite computes it on insert and stores it. - is_json integer [not null, note: 'GENERATED ALWAYS AS (json_valid(message_data)) STORED'] - - indexes { - (group_id, node_id, message_id) [unique] - message_id - } -} - -// One row per group/node id that has messages. -// AFTER INSERT ON data: INSERT ... ON CONFLICT DO UPDATE SET -// max_message_id = MAX(max_message_id, excluded.max_message_id) -// Only fires for rows actually inserted (not the ones INSERT OR IGNORE drops). -table node_heads [note: 'WITHOUT ROWID'] { - group_id integer [not null] - node_id integer [not null] - max_message_id integer [not null] - - indexes { - (group_id, node_id) [pk] - } -} - -// Create it, but we'll implement this later. -table attachements { - group_id integer [not null] - node_id integer [not null] - message_id integer [not null] - attachement_data blob [not null] - - indexes { - (group_id, node_id) - message_id - } -} - -// Note, ignore it -// msg_type TEXT GENERATED ALWAYS AS (data ->> '$.messageData.MsgType') VIRTUAL diff --git a/Server/Storage/db_schema_v4.dbml b/Server/Storage/db_schema_v4.dbml deleted file mode 100644 index 30bbd39..0000000 --- a/Server/Storage/db_schema_v4.dbml +++ /dev/null @@ -1,61 +0,0 @@ -// Changes from v3: -// - group_id is now topic_id, in every table. MigrateStorageTopicIds() -// (Storage.pbi) renames the columns of an older database on start, and -// the trigger and the attachements index are made again with the new -// names (idx_attachements_group_node -> idx_attachements_topic_node). -// -// Needs SQLite 3.38+ with its JSON functions (json_valid, ->>), see Storage.pbi. -// The database is in WAL mode, see Storage.pbi and Writer.pbi. - -table archives { - // UTC Unix Timestamp after which this archived message should be deleted. - delete_by integer [not null] - - message_data text [not null] -} - -table data { - topic_id integer [not null] - node_id integer [not null] - message_id integer [not null] - message_data text [not null] - - // 1 if message_data is well-formed JSON, 0 otherwise. - // Can't be written, SQLite computes it on insert and stores it. - is_json integer [not null, note: 'GENERATED ALWAYS AS (json_valid(message_data)) STORED'] - - indexes { - (topic_id, node_id, message_id) [unique] - message_id - } -} - -// One row per topic/node id that has messages. -// AFTER INSERT ON data: INSERT ... ON CONFLICT DO UPDATE SET -// max_message_id = MAX(max_message_id, excluded.max_message_id) -// Only fires for rows actually inserted (not the ones INSERT OR IGNORE drops). -table node_heads [note: 'WITHOUT ROWID'] { - topic_id integer [not null] - node_id integer [not null] - max_message_id integer [not null] - - indexes { - (topic_id, node_id) [pk] - } -} - -// Create it, but we'll implement this later. -table attachements { - topic_id integer [not null] - node_id integer [not null] - message_id integer [not null] - attachement_data blob [not null] - - indexes { - (topic_id, node_id) - message_id - } -} - -// Note, ignore it -// msg_type TEXT GENERATED ALWAYS AS (data ->> '$.messageData.MsgType') VIRTUAL diff --git a/Server/Storage/db_schema_v5.dbml b/Server/Storage/db_schema_v5.dbml deleted file mode 100644 index 458eb5c..0000000 --- a/Server/Storage/db_schema_v5.dbml +++ /dev/null @@ -1,88 +0,0 @@ -// Changes from v4: -// - topics and nodes: every topic and node id in data, with its name (its -// id in digits if it has none) and where that comes from. Kept by -// Server/Storage/Names.pbi from the config. Only names on both servers -// replicate. Names are shared between servers, ids aren't. -// - messages: a view of data with the names, for queries by name. -// - No foreign keys from data to them (Notes.md): an unknown id would fail -// a whole replicated batch. -// -// Needs SQLite 3.38+ with its JSON functions (json_valid, ->>), see Storage.pbi. -// The database is in WAL mode, see Storage.pbi and Writer.pbi. - -table archives { - // UTC Unix Timestamp after which this archived message should be deleted. - delete_by integer [not null] - - message_data text [not null] -} - -table data { - topic_id integer [not null] - node_id integer [not null] - message_id integer [not null] - message_data text [not null] - - // 1 if message_data is well-formed JSON, 0 otherwise. - // Can't be written, SQLite computes it on insert and stores it. - is_json integer [not null, note: 'GENERATED ALWAYS AS (json_valid(message_data)) STORED'] - - indexes { - (topic_id, node_id, message_id) [unique] - message_id - } -} - -// One row per topic/node id that has messages. -// AFTER INSERT ON data: INSERT ... ON CONFLICT DO UPDATE SET -// max_message_id = MAX(max_message_id, excluded.max_message_id) -// Only fires for rows actually inserted (not the ones INSERT OR IGNORE drops). -table node_heads [note: 'WITHOUT ROWID'] { - topic_id integer [not null] - node_id integer [not null] - max_message_id integer [not null] - - indexes { - (topic_id, node_id) [pk] - } -} - -// Create it, but we'll implement this later. -table attachements { - topic_id integer [not null] - node_id integer [not null] - message_id integer [not null] - attachement_data blob [not null] - - indexes { - (topic_id, node_id) - message_id - } -} - -// origin: "config" (named in [BakaShrot.Topics]), "id" (unnamed, name is -// the id in digits). -table topics { - topic_id integer [pk] - name text [not null, unique, note: 'COLLATE NOCASE'] - origin text [not null] -} - -// origin: "config" (named in [BakaShrot.Nodes]), "id" (unnamed), "peer" -// (only in databases from the short-lived version that added peer nodes). -table nodes { - node_id integer [pk] - name text [not null, unique, note: 'COLLATE NOCASE'] - origin text [not null] -} - -// View messages: -// SELECT t.name AS topic, n.name AS node, d.message_id, d.message_data, -// d.is_json, d.topic_id, d.node_id -// FROM data d JOIN topics t ON t.topic_id = d.topic_id -// JOIN nodes n ON n.node_id = d.node_id -// WHERE topic = ... AND node = ... goes through the name indexes, then -// data's (topic_id, node_id, message_id) one. - -// Note, ignore it -// msg_type TEXT GENERATED ALWAYS AS (data ->> '$.messageData.MsgType') VIRTUAL diff --git a/Server/Storage/db_schema_v6.dbml b/Server/Storage/db_schema_v6.dbml deleted file mode 100644 index 0497d83..0000000 --- a/Server/Storage/db_schema_v6.dbml +++ /dev/null @@ -1,89 +0,0 @@ -// Changes from v5: -// - data.pushed_at: when the message was pushed to its origin, ms since -// 1970-01-01 UTC, kept as is when replicated. A v5 database gets it with -// the time of the upgrade (MigrateStoragePushedAt() in Storage.pbi). -// - Index (topic_id, pushed_at): what the retention deletes by -// (Retention.pbi, [BakaShrot.Retention] in the config). -// - messages: the view also has pushed_at, and pushed_utc as text. -// - node_heads outlives deleted messages: a pair's highest id ever. Also -// raised for replicated messages skipped as already past their max age. -// - archives is gone: never used, dropped from older databases. -// -// 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 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'] - - // When it was pushed to its origin, ms since 1970-01-01 UTC. - pushed_at integer [not null, default: 0] - - indexes { - (topic_id, node_id, message_id) [unique] - message_id - (topic_id, pushed_at) - } -} - -// One row per topic/node id that has ever had messages: deleting messages -// (the retention) leaves it as is, so ids never go back. -// 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, d.pushed_at, -// strftime('%Y-%m-%dT%H:%M:%fZ', d.pushed_at / 1000.0, 'unixepoch') AS pushed_utc -// FROM data d JOIN topics t ON t.topic_id = d.topic_id -// JOIN nodes n ON n.node_id = d.node_id -// WHERE topic = ... AND node = ... goes through the name indexes, then -// data's (topic_id, node_id, message_id) one. - -// Note, ignore it -// msg_type TEXT GENERATED ALWAYS AS (data ->> '$.messageData.MsgType') VIRTUAL diff --git a/Server/Storage/db_schema_v7.dbml b/Server/Storage/db_schema_v7.dbml deleted file mode 100644 index dfbef56..0000000 --- a/Server/Storage/db_schema_v7.dbml +++ /dev/null @@ -1,126 +0,0 @@ -// Changes from v6 (Design/Attachments.md): -// - attachments, blobs, blob_chunks: a message's attachment (one at most), -// its data, in 1 MB parts. Replace the placeholder "attachements" table, -// dropped. -// - Triggers: deleting a message deletes its attachment row, which marks -// its blob to delete (Retention.pbi deletes the parts). -// -// 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 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'] - - // When it was pushed to its origin, ms since 1970-01-01 UTC. - pushed_at integer [not null, default: 0] - - indexes { - (topic_id, node_id, message_id) [unique] - message_id - (topic_id, pushed_at) - } -} - -// One row per topic/node id that has ever had messages: deleting messages -// (the retention) leaves it as is, so ids never go back. -// 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] - } -} - -// A message's attachment (Design/Attachments.md). Its size and SHA-256 come -// with it (pushed, or replicated), its data in blob_id once any is here. -// state: 0 missing (replicated, none here yet), 1 receiving, 2 ready, -// 3 not kept (bigger than this server's MaxAttachmentSize). -// AFTER DELETE ON data deletes it, AFTER DELETE ON attachments marks its -// blob to delete (state 3). -table attachments [note: 'WITHOUT ROWID'] { - topic_id integer [not null] - node_id integer [not null] - message_id integer [not null] - size integer [not null] - sha256 blob [not null] - blob_id integer - state integer [not null] - - indexes { - (topic_id, node_id, message_id) [pk] - state - } -} - -// The data of one attachment, being received (an upload, or replicated) or -// stored. topic_id, node_id: an upload's owner, or the message's pair. -// received: bytes stored so far. created_at: ms since 1970 UTC, an upload -// not pushed with its message within UploadTimeout is deleted. -// state: 0 receiving, 1 complete (an upload waiting for its message), -// 2 attached, 3 to delete. -table blobs { - blob_id integer [pk] - topic_id integer [not null] - node_id integer [not null] - size integer [not null] - sha256 blob [not null] - received integer [not null, default: 0] - state integer [not null] - created_at integer [not null] - - indexes { - state - } -} - -// Its parts, #BakaShrot_AttachmentChunkSize (1 MB) each, the last one -// what's left. -table blob_chunks { - blob_id integer [not null] - chunk_index integer [not null] - chunk_data blob [not null] - - indexes { - (blob_id, chunk_index) [pk] - } -} - -// 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, d.pushed_at, -// strftime('%Y-%m-%dT%H:%M:%fZ', d.pushed_at / 1000.0, 'unixepoch') AS pushed_utc -// FROM data d JOIN topics t ON t.topic_id = d.topic_id -// JOIN nodes n ON n.node_id = d.node_id -// WHERE topic = ... AND node = ... goes through the name indexes, then -// data's (topic_id, node_id, message_id) one. - -// Note, ignore it -// msg_type TEXT GENERATED ALWAYS AS (data ->> '$.messageData.MsgType') VIRTUAL diff --git a/Server/Storage/db_schema_v8.dbml b/Server/Storage/db_schema_v8.dbml deleted file mode 100644 index 589357a..0000000 --- a/Server/Storage/db_schema_v8.dbml +++ /dev/null @@ -1,148 +0,0 @@ -// Changes from v7: -// - browse: one row (id 1), the topic and optionally the node to browse, -// referencing topics and nodes by name so database tools (SQLiteStudio) -// show a dropdown of them. Never written by the server, its foreign keys -// never turned on by it. -// - browse_messages: the view of what browse selects, newest first. -// - The origins of topics and nodes: "config" also covers the nodes the -// config's sections define, "peer" the names peers sent (AcceptTopics / -// AcceptNodes wildcards). -// -// 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 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'] - - // When it was pushed to its origin, ms since 1970-01-01 UTC. - pushed_at integer [not null, default: 0] - - indexes { - (topic_id, node_id, message_id) [unique] - message_id - (topic_id, pushed_at) - } -} - -// One row per topic/node id that has ever had messages: deleting messages -// (the retention) leaves it as is, so ids never go back. -// 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] - } -} - -// A message's attachment (Design/Attachments.md). Its size and SHA-256 come -// with it (pushed, or replicated), its data in blob_id once any is here. -// state: 0 missing (replicated, none here yet), 1 receiving, 2 ready, -// 3 not kept (bigger than this server's MaxAttachmentSize). -// AFTER DELETE ON data deletes it, AFTER DELETE ON attachments marks its -// blob to delete (state 3). -table attachments [note: 'WITHOUT ROWID'] { - topic_id integer [not null] - node_id integer [not null] - message_id integer [not null] - size integer [not null] - sha256 blob [not null] - blob_id integer - state integer [not null] - - indexes { - (topic_id, node_id, message_id) [pk] - state - } -} - -// The data of one attachment, being received (an upload, or replicated) or -// stored. topic_id, node_id: an upload's owner, or the message's pair. -// received: bytes stored so far. created_at: ms since 1970 UTC, an upload -// not pushed with its message within UploadTimeout is deleted. -// state: 0 receiving, 1 complete (an upload waiting for its message), -// 2 attached, 3 to delete. -table blobs { - blob_id integer [pk] - topic_id integer [not null] - node_id integer [not null] - size integer [not null] - sha256 blob [not null] - received integer [not null, default: 0] - state integer [not null] - created_at integer [not null] - - indexes { - state - } -} - -// Its parts, #BakaShrot_AttachmentChunkSize (1 MB) each, the last one -// what's left. -table blob_chunks { - blob_id integer [not null] - chunk_index integer [not null] - chunk_data blob [not null] - - indexes { - (blob_id, chunk_index) [pk] - } -} - -// origin: "config" (named in [BakaShrot.Topics]), "peer" (taken from a -// peer by a wildcard), "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], or a node the config's -// [BakaShrot], peer or client sections define), "peer" (taken from a peer: -// AcceptNodes is * by default), "id" (unnamed). -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, d.pushed_at, -// strftime('%Y-%m-%dT%H:%M:%fZ', d.pushed_at / 1000.0, 'unixepoch') AS pushed_utc -// FROM data d JOIN topics t ON t.topic_id = d.topic_id -// JOIN nodes n ON n.node_id = d.node_id -// WHERE topic = ... AND node = ... goes through the name indexes, then -// data's (topic_id, node_id, message_id) one. - -// What to browse with a database tool: set topic (and node, NULL for every -// one) in its one row, open browse_messages. The references are for the -// tools' dropdowns only: the server doesn't turn foreign keys on. -table browse { - id integer [pk, note: 'CHECK (id = 1)'] - topic text [ref: > topics.name, note: 'COLLATE NOCASE'] - node text [ref: > nodes.name, note: 'COLLATE NOCASE'] -} - -// View browse_messages: -// SELECT m.node, m.message_id, m.pushed_utc, m.message_data, m.is_json, -// a.size AS attachment_size, m.topic -// FROM browse b JOIN messages m ON m.topic = b.topic -// LEFT JOIN attachments a ON a.topic_id = m.topic_id AND a.node_id = m.node_id -// AND a.message_id = m.message_id -// WHERE b.id = 1 AND (b.node IS NULL OR m.node = b.node) -// ORDER BY m.pushed_at DESC, m.node, m.message_id DESC - -// Note, ignore it -// msg_type TEXT GENERATED ALWAYS AS (data ->> '$.messageData.MsgType') VIRTUAL diff --git a/Tests/AttachmentEdgeClient.pb b/Tests/AttachmentEdgeClient.pb deleted file mode 100644 index fac7e99..0000000 --- a/Tests/AttachmentEdgeClient.pb +++ /dev/null @@ -1,389 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: AttachmentEdgeClient.pb -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; A raw protocol client for the attachment cases the DLL never produces, run -; by Tests/AttachmentEdges-Test.ps1 against a running server. -; -; Usage: -; AttachmentEdgeClient edge -; Wrong SHA-256, parts out of order / of the wrong size / repeated, -; someone else's upload, the wrong topic, an upload attached twice, too -; big, a part out of range. Then starts two uploads it leaves behind -; (one half sent, one complete but never pushed) and prints -; "LEFT ". -; AttachmentEdgeClient late -; Once they expired: both refused. -; The inis are client.ini's: PrivateKey, PublicKey, ServerPublicKey, Topic, -; Node, ServerHost, ServerPort. Kitchen may push to logs and other, garage -; to logs; the server's MaxAttachmentSize must be under 1G. -; Compile as a thread-safe console program into Build\. Exits with 0 if -; every check passed, 1 otherwise. -; ============================================================================ - -EnableExplicit - -XIncludeFile "../Commons/Networking/Outbound.pbi" - -Structure EdgeClient - Outbound.BakaShrot_Outbound - Identity.BakaShrot_OutboundIdentity - PrivateKey.a[#BakaShrot_Ed25519_PrivateKeySize] - ServerPublicKey.a[#BakaShrot_Ed25519_PublicKeySize] -EndStructure - -Global Fails.i = 0 - -Procedure Check(What.s, Ok.i, Detail.s = "") - If Ok - PrintN("PASS " + What) - Else - PrintN("FAIL " + What) - Fails + 1 - EndIf - PrintN(" -> " + Detail) -EndProcedure - -Procedure.i ConnectIni(*Client.EdgeClient, IniPath.s) - Protected Host.s, Port.i, Ok.i - - If Not OpenPreferences(IniPath) - ProcedureReturn #False - EndIf - PreferenceGroup("BakaShrot") - Ok = DecodeKeyFromString(ReadPreferenceString("PrivateKey", ""), @*Client\PrivateKey[0], #BakaShrot_Ed25519_PrivateKeySize) - Ok = Bool(Ok And DecodeKeyFromString(ReadPreferenceString("ServerPublicKey", ""), @*Client\ServerPublicKey[0], #BakaShrot_Ed25519_PublicKeySize)) - *Client\Identity\PublicKey = ReadPreferenceString("PublicKey", "") - *Client\Identity\Node = ReadPreferenceString("Node", "") - *Client\Identity\PrivateKey = @*Client\PrivateKey[0] - Host = ReadPreferenceString("ServerHost", "127.0.0.1") - Port = ReadPreferenceLong("ServerPort", 0) - ClosePreferences() - If Not Ok - ProcedureReturn #False - EndIf - ProcedureReturn BakaShrot_Outbound_Connect(@*Client\Outbound, Host, Port, @*Client\Identity, @*Client\ServerPublicKey[0]) -EndProcedure - -; Sends *Packet (freed), returns the answer with its type, 0 if the link failed. -Procedure.i Exchange(*Client.EdgeClient, *Packet, Size.i, *Type.Integer, *AnswerSize.Integer) - Protected *Answer - *Type\i = 0 - If Not *Packet - ProcedureReturn 0 - EndIf - If Not BakaShrot_Outbound_Send(@*Client\Outbound, *Packet, Size) - FreeMemory(*Packet) - ProcedureReturn 0 - EndIf - FreeMemory(*Packet) - *Answer = BakaShrot_Outbound_WaitPacket(@*Client\Outbound, *AnswerSize, 20000) - If *Answer - *Type\i = BakaShrot_GetPacketType(*Answer, *AnswerSize\i) - EndIf - ProcedureReturn *Answer -EndProcedure - -Procedure.s Refusal(*Answer, Size.i) - Protected *View.MsgPackData, *Refused.BakaShrot_RequestRefused, Reason.s - *View = MsgPackWrapMsgBuffer(*Answer, Size) - If *View - *Refused = BakaShrot_RequestRefusedPacket_Decode(*View) - MsgPackFree(*View, #False) - If *Refused - Reason = *Refused\Reason - FreeStructure(*Refused) - EndIf - EndIf - ProcedureReturn Reason -EndProcedure - -; Starts an upload. Returns its id, 0 if refused (reason in *Reason\s). -Procedure.q StartUpload(*Client.EdgeClient, Topic.s, Size.q, *Sha256, *Reason.String) - Protected Start.BakaShrot_UploadStart, *Started.BakaShrot_UploadStarted - Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer, Type.Integer, *View.MsgPackData, Id.q - - *Reason\s = "" - Start\Topic = Topic - Start\Size = Size - CopyMemory(*Sha256, @Start\Sha256[0], #BakaShrot_Sha256Size) - *Packet = BakaShrot_UploadStartPacket_Encode(@Start, @PacketSize) - *Answer = Exchange(*Client, *Packet, PacketSize\i, @Type, @AnswerSize) - If Not *Answer - *Reason\s = "the link failed" - ProcedureReturn 0 - EndIf - If Type\i = #BakaShrot_PacketType_RequestRefused - *Reason\s = Refusal(*Answer, AnswerSize\i) - ElseIf Type\i = #BakaShrot_PacketType_UploadStarted - *View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i) - *Started = BakaShrot_UploadStartedPacket_Decode(*View) - MsgPackFree(*View, #False) - If *Started - Id = *Started\UploadId - FreeStructure(*Started) - EndIf - EndIf - FreeMemory(*Answer) - ProcedureReturn Id -EndProcedure - -; Sends a part. Returns 1 if stored (*Complete\i set), 0 if refused (reason), -1 if the link failed. -Procedure.i SendChunk(*Client.EdgeClient, UploadId.q, Index.i, *Data, Size.i, *Complete.Integer, *Reason.String) - Protected Chunk.BakaShrot_UploadChunk, *Stored.BakaShrot_ChunkStored - Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer, Type.Integer, *View.MsgPackData, Result.i = -1 - - *Reason\s = "" - Chunk\UploadId = UploadId - Chunk\ChunkIndex = Index - Chunk\Data = *Data - Chunk\DataSize = Size - *Packet = BakaShrot_UploadChunkPacket_Encode(@Chunk, @PacketSize) - *Answer = Exchange(*Client, *Packet, PacketSize\i, @Type, @AnswerSize) - If Not *Answer - ProcedureReturn -1 - EndIf - If Type\i = #BakaShrot_PacketType_RequestRefused - *Reason\s = Refusal(*Answer, AnswerSize\i) - Result = 0 - ElseIf Type\i = #BakaShrot_PacketType_ChunkStored - *View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i) - *Stored = BakaShrot_ChunkStoredPacket_Decode(*View) - MsgPackFree(*View, #False) - If *Stored - *Complete\i = *Stored\Complete - FreeStructure(*Stored) - Result = 1 - EndIf - EndIf - FreeMemory(*Answer) - ProcedureReturn Result -EndProcedure - -; Pushes a message with UploadId. Returns its id, 0 if refused (reason). -Procedure.q Push(*Client.EdgeClient, Topic.s, Json.s, UploadId.q, *Reason.String) - Protected Push.BakaShrot_PushMessage, *Pushed.BakaShrot_MessagePushed - Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer, Type.Integer, *View.MsgPackData, Id.q - - *Reason\s = "" - Push\Topic = Topic - Push\JsonData = Json - Push\UploadId = UploadId - *Packet = BakaShrot_PushMessagePacket_Encode(@Push, @PacketSize) - *Answer = Exchange(*Client, *Packet, PacketSize\i, @Type, @AnswerSize) - If Not *Answer - *Reason\s = "the link failed" - ProcedureReturn 0 - EndIf - If Type\i = #BakaShrot_PacketType_RequestRefused - *Reason\s = Refusal(*Answer, AnswerSize\i) - ElseIf Type\i = #BakaShrot_PacketType_MessagePushed - *View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i) - *Pushed = BakaShrot_MessagePushedPacket_Decode(*View) - MsgPackFree(*View, #False) - If *Pushed - Id = *Pushed\MessageId - FreeStructure(*Pushed) - EndIf - EndIf - FreeMemory(*Answer) - ProcedureReturn Id -EndProcedure - -; Asks for a part. Returns it (free with _Free), 0 if refused (reason). -Procedure.i GetChunk(*Client.EdgeClient, Topic.s, Node.s, MessageId.q, Index.i, *Reason.String) - Protected Request.BakaShrot_GetAttachment, *Chunk.BakaShrot_AttachmentChunk - Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer, Type.Integer, *View.MsgPackData - - *Reason\s = "" - Request\Topic = Topic - Request\Node = Node - Request\MessageId = MessageId - Request\ChunkIndex = Index - *Packet = BakaShrot_GetAttachmentPacket_Encode(@Request, @PacketSize) - *Answer = Exchange(*Client, *Packet, PacketSize\i, @Type, @AnswerSize) - If Not *Answer - *Reason\s = "the link failed" - ProcedureReturn 0 - EndIf - If Type\i = #BakaShrot_PacketType_RequestRefused - *Reason\s = Refusal(*Answer, AnswerSize\i) - ElseIf Type\i = #BakaShrot_PacketType_AttachmentChunk - *View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i) - *Chunk = BakaShrot_AttachmentChunkPacket_Decode(*View) - MsgPackFree(*View, #False) - EndIf - FreeMemory(*Answer) - ProcedureReturn *Chunk -EndProcedure - -; Size random bytes. -Procedure.i RandomBytes(Size.i) - Protected *Data = AllocateMemory(Size) - RandomData(*Data, Size) - ProcedureReturn *Data -EndProcedure - -Procedure Sha256Of(*Data, Size.q, *Out) - Protected Hash.BakaShrot_Sha256 - BakaShrot_Sha256_Start(@Hash) - BakaShrot_Sha256_Add(@Hash, *Data, Size) - BakaShrot_Sha256_Finish(@Hash, *Out) -EndProcedure - -; Uploads Size bytes of *Data properly. Returns the upload id, 0 on failure. -Procedure.q UploadAll(*Client.EdgeClient, Topic.s, *Data, Size.q) - Protected Dim Sha.a(31), Id.q, Index.i, Complete.Integer, Reason.String - Sha256Of(*Data, Size, @Sha(0)) - Id = StartUpload(*Client, Topic, Size, @Sha(0), @Reason) - If Not Id - ProcedureReturn 0 - EndIf - For Index = 0 To BakaShrot_AttachmentChunkCount(Size) - 1 - If SendChunk(*Client, Id, Index, *Data + Index * #BakaShrot_AttachmentChunkSize, BakaShrot_AttachmentChunkBytes(Size, Index), @Complete, @Reason) <> 1 - ProcedureReturn 0 - EndIf - Next - If Not Complete\i - ProcedureReturn 0 - EndIf - ProcedureReturn Id -EndProcedure - - -Define Kitchen.EdgeClient, Garage.EdgeClient, Reason.String, Complete.Integer -Define Dim Sha.a(31), Dim WrongSha.a(31) -Define *Data, *Other, Id.q, Id2.q, MessageId.q, Result.i, *Chunk.BakaShrot_AttachmentChunk, Size.q -Define PartialId.q, CompleteId.q - -OpenConsole() -If CountProgramParameters() < 3 - PrintN("Usage: AttachmentEdgeClient edge | late ") - End 1 -EndIf -If Not ConnectIni(@Kitchen, ProgramParameter(1)) - PrintN("FAIL can't connect with " + ProgramParameter(1)) - End 1 -EndIf - -If LCase(ProgramParameter(0)) = "late" - PartialId = Val(ProgramParameter(2)) - CompleteId = Val(ProgramParameter(3)) - *Data = RandomBytes(#BakaShrot_AttachmentChunkSize) - Result = SendChunk(@Kitchen, PartialId, 1, *Data, 1000, @Complete, @Reason) - Check("An expired upload: its next part refused", Bool(Result = 0 And FindString(Reason\s, "No such upload in progress")), Reason\s) - MessageId = Push(@Kitchen, "logs", "{" + Chr(34) + "late" + Chr(34) + ":1}", CompleteId, @Reason) - Check("An expired complete upload: pushing with it refused", Bool(MessageId = 0 And (FindString(Reason\s, "No such upload") Or FindString(Reason\s, "isn't complete"))), Reason\s) - Check("Still connected after the refusals", BakaShrot_Outbound_IsConnected(@Kitchen\Outbound)) - BakaShrot_Outbound_Close(@Kitchen\Outbound, #BakaShrot_ConnectionStatus_Disconnected) - PrintN("") - If Fails : PrintN(Str(Fails) + " FAILED") : End 1 : EndIf - PrintN("All passed") - End 0 -EndIf - -If Not ConnectIni(@Garage, ProgramParameter(2)) - PrintN("FAIL can't connect with " + ProgramParameter(2)) - End 1 -EndIf - -; --- A wrong SHA-256 -------------------------------------------------------------- -Size = #BakaShrot_AttachmentChunkSize + 500000 -*Data = RandomBytes(Size) -*Other = RandomBytes(Size) -Sha256Of(*Other, Size, @WrongSha(0)) -Id = StartUpload(@Kitchen, "logs", Size, @WrongSha(0), @Reason) -Check("Upload with a wrong SHA-256: started", Bool(Id > 0), Reason\s) -Result = SendChunk(@Kitchen, Id, 0, *Data, #BakaShrot_AttachmentChunkSize, @Complete, @Reason) -Check(" part 0 stored, not complete", Bool(Result = 1 And Complete\i = 0), Reason\s) -Result = SendChunk(@Kitchen, Id, 1, *Data + #BakaShrot_AttachmentChunkSize, 500000, @Complete, @Reason) -Check(" the last part: refused, doesn't match", Bool(Result = 0 And FindString(Reason\s, "doesn't match its SHA-256")), Reason\s) -MessageId = Push(@Kitchen, "logs", "{" + Chr(34) + "bad" + Chr(34) + ":1}", Id, @Reason) -Check(" pushing with it: refused", Bool(MessageId = 0 And FindString(Reason\s, "isn't complete")), Reason\s) -Result = SendChunk(@Kitchen, Id, 1, *Data + #BakaShrot_AttachmentChunkSize, 500000, @Complete, @Reason) -Check(" sending the last part again: refused, it's dropped", Bool(Result = 0 And FindString(Reason\s, "No such upload in progress")), Reason\s) - -; --- Parts out of order, wrong size, repeated --------------------------------------- -Size = 2 * #BakaShrot_AttachmentChunkSize + 1234 -FreeMemory(*Data) : *Data = RandomBytes(Size) -Sha256Of(*Data, Size, @Sha(0)) -Id = StartUpload(@Kitchen, "logs", Size, @Sha(0), @Reason) -Check("Upload of 3 parts: started", Bool(Id > 0), Reason\s) -Result = SendChunk(@Kitchen, Id, 1, *Data + #BakaShrot_AttachmentChunkSize, #BakaShrot_AttachmentChunkSize, @Complete, @Reason) -Check(" part 1 first: refused", Bool(Result = 0 And FindString(Reason\s, "Expected part 0 of 3")), Reason\s) -Result = SendChunk(@Kitchen, Id, 0, *Data, 1000, @Complete, @Reason) -Check(" part 0 too short: refused", Bool(Result = 0 And FindString(Reason\s, "1048576 bytes")), Reason\s) -Result = SendChunk(@Kitchen, Id, 0, *Data, #BakaShrot_AttachmentChunkSize, @Complete, @Reason) -Check(" part 0 right: stored, the refusals didn't drop the upload", Bool(Result = 1 And Complete\i = 0), Reason\s) -Result = SendChunk(@Kitchen, Id, 0, *Data, #BakaShrot_AttachmentChunkSize, @Complete, @Reason) -Check(" part 0 again: refused", Bool(Result = 0 And FindString(Reason\s, "Expected part 1")), Reason\s) -Result = SendChunk(@Garage, Id, 1, *Data + #BakaShrot_AttachmentChunkSize, #BakaShrot_AttachmentChunkSize, @Complete, @Reason) -Check(" part 1 from another client: refused", Bool(Result = 0 And FindString(Reason\s, "No such upload in progress")), Reason\s) -Result = SendChunk(@Kitchen, Id, 1, *Data + #BakaShrot_AttachmentChunkSize, #BakaShrot_AttachmentChunkSize, @Complete, @Reason) -Check(" part 1: stored", Bool(Result = 1 And Complete\i = 0), Reason\s) -Result = SendChunk(@Kitchen, Id, 2, *Data + 2 * #BakaShrot_AttachmentChunkSize, 1234, @Complete, @Reason) -Check(" part 2, the last: complete", Bool(Result = 1 And Complete\i = 1), Reason\s) -Result = SendChunk(@Kitchen, Id, 3, *Data, 10, @Complete, @Reason) -Check(" a part past the end: refused", Bool(Result = 0), Reason\s) - -; --- Whose, which topic, how many times ------------------------------------------------- -MessageId = Push(@Garage, "logs", "{" + Chr(34) + "theirs" + Chr(34) + ":1}", Id, @Reason) -Check("Another client pushing with it: refused", Bool(MessageId = 0 And FindString(Reason\s, "No such upload")), Reason\s) -MessageId = Push(@Kitchen, "other", "{" + Chr(34) + "topic" + Chr(34) + ":1}", Id, @Reason) -Check("Pushing it to another topic: refused", Bool(MessageId = 0 And FindString(Reason\s, "is for topic 'logs'")), Reason\s) -MessageId = Push(@Kitchen, "logs", "{" + Chr(34) + "edge" + Chr(34) + ":1}", Id, @Reason) -Check("Pushing it: stored", Bool(MessageId > 0), "message #" + Str(MessageId) + " " + Reason\s) -Id2 = Push(@Kitchen, "logs", "{" + Chr(34) + "edge" + Chr(34) + ":2}", Id, @Reason) -Check("Pushing it again: refused, attached already", Bool(Id2 = 0 And FindString(Reason\s, "attached already")), Reason\s) -Id2 = Push(@Kitchen, "logs", "{" + Chr(34) + "edge" + Chr(34) + ":3}", 999999, @Reason) -Check("An upload id that doesn't exist: refused", Bool(Id2 = 0 And FindString(Reason\s, "No such upload")), Reason\s) - -; --- Reading it back, part by part --------------------------------------------------------- -*Chunk = GetChunk(@Kitchen, "logs", "kitchen", MessageId, 2, @Reason) -Check("GetAttachment part 2 first: the right bytes", Bool(*Chunk And *Chunk\DataSize = 1234 And *Chunk\Size = Size And CompareMemory(*Chunk\Data, *Data + 2 * #BakaShrot_AttachmentChunkSize, 1234) And CompareMemory(@*Chunk\Sha256[0], @Sha(0), 32)), Reason\s) -BakaShrot_AttachmentChunkPacket_Free(*Chunk) -*Chunk = GetChunk(@Kitchen, "logs", "kitchen", MessageId, 0, @Reason) -Check(" part 0: the right bytes", Bool(*Chunk And *Chunk\DataSize = #BakaShrot_AttachmentChunkSize And CompareMemory(*Chunk\Data, *Data, #BakaShrot_AttachmentChunkSize)), Reason\s) -BakaShrot_AttachmentChunkPacket_Free(*Chunk) -*Chunk = GetChunk(@Kitchen, "logs", "kitchen", MessageId, 3, @Reason) -Check(" part 3, past the end: refused", Bool(Not *Chunk And FindString(Reason\s, "has 3 parts")), Reason\s) -*Chunk = GetChunk(@Garage, "secret", "kitchen", MessageId, 0, @Reason) -Check(" from a topic garage may not read: refused", Bool(Not *Chunk And FindString(Reason\s, "Not allowed to read topic")), Reason\s) - -; --- Limits ------------------------------------------------------------------------------------ -Id = StartUpload(@Kitchen, "logs", 1024 * 1024 * 1024, @Sha(0), @Reason) -Check("Upload of 1 GB (over MaxAttachmentSize): refused", Bool(Id = 0 And FindString(Reason\s, "too big")), Reason\s) -Id = StartUpload(@Garage, "other", 1000, @Sha(0), @Reason) -Check("Upload to a topic garage may not push to: refused", Bool(Id = 0 And FindString(Reason\s, "Not allowed to push")), Reason\s) -Check("Both still connected after every refusal", Bool(BakaShrot_Outbound_IsConnected(@Kitchen\Outbound) And BakaShrot_Outbound_IsConnected(@Garage\Outbound))) - -; --- Left behind, for the expiry --------------------------------------------------------------------- -Size = 2 * #BakaShrot_AttachmentChunkSize -FreeMemory(*Data) : *Data = RandomBytes(Size) -Sha256Of(*Data, Size, @Sha(0)) -PartialId = StartUpload(@Kitchen, "logs", Size, @Sha(0), @Reason) -Result = SendChunk(@Kitchen, PartialId, 0, *Data, #BakaShrot_AttachmentChunkSize, @Complete, @Reason) -CompleteId = UploadAll(@Kitchen, "logs", *Data, 5000) -Check("Two uploads left behind: half sent, and complete but never pushed", Bool(PartialId > 0 And Result = 1 And CompleteId > 0), Str(PartialId) + ", " + Str(CompleteId)) - -BakaShrot_Outbound_Close(@Kitchen\Outbound, #BakaShrot_ConnectionStatus_Disconnected) -BakaShrot_Outbound_Close(@Garage\Outbound, #BakaShrot_ConnectionStatus_Disconnected) -PrintN("LEFT " + Str(PartialId) + " " + Str(CompleteId)) -PrintN("") -If Fails : PrintN(Str(Fails) + " FAILED") : End 1 : EndIf -PrintN("All passed") -End 0 diff --git a/Tests/AttachmentEdges-Test.ps1 b/Tests/AttachmentEdges-Test.ps1 deleted file mode 100644 index d372532..0000000 --- a/Tests/AttachmentEdges-Test.ps1 +++ /dev/null @@ -1,292 +0,0 @@ -# The attachment cases the regular clients never produce (Design/Attachments.md): -# 1. Through a raw client (Tests/AttachmentEdgeClient.pb): a wrong SHA-256, -# parts out of order / of the wrong size / repeated, someone else's -# upload, the wrong topic, an upload attached twice, too big, a part -# out of range. -# 2. Uploads left behind: kept within UploadTimeout, deleted past it, then -# refused. -# 3. Replication resuming: the receiving server killed in the middle of a -# 400 MB attachment, restarted, the sender goes on from where it stopped. -# 4. A corrupted attachment (bytes flipped in the sender's database): the -# client refuses it, the peer drops it and doesn't keep it. -# Two servers, A (port 12413) and B (12414). Needs Build\ (Build.ps1), -# Build\Bench\BenchServer.exe, Build\AttachmentEdgeClient.exe (compile -# Tests\AttachmentEdgeClient.pb, thread-safe console), and Python 3 for 4. -# Usage: powershell -ExecutionPolicy Bypass -File Tests\AttachmentEdges-Test.ps1 [-Python ] -param( - [string]$Build = (Join-Path $PSScriptRoot "..\Build"), - [string]$Python = "python" -) -$ErrorActionPreference = "Stop" -$Build = (Resolve-Path $Build).Path -$Dir = Join-Path $Build "_attachedges" -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 "BakaShrotGenerateKeyPairs.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 " | "); Lines = @($O) } -} -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) { - Check $What (($Result.Code -eq $Code) -and ($Result.Out -match $Pattern)) ("[{0}] {1}" -f $Result.Code, $Result.Out) -} -function Start-Srv($Name) { - $Stop = Join-Path $Dir "$Name.stop" - Remove-Item $Stop -ErrorAction SilentlyContinue - # Each run its own log: a restart doesn't overwrite the last one's. - $script:Runs[$Name]++ - $Log = Join-Path $Dir "$Name.$($script:Runs[$Name]).log" - $P = Start-Process -FilePath $Server -ArgumentList "`"$(Join-Path $Dir "$Name.ini")`"", "`"$Stop`"" -WorkingDirectory $Dir ` - -RedirectStandardOutput $Log -WindowStyle Hidden -PassThru - $null = $P.Handle - @{ P = $P; Stop = $Stop; Name = $Name; Log = $Log } -} -$Runs = @{ a = 0; b = 0 } -function Stop-Srv($S) { - if (-not $S -or $S.P.HasExited) { return } - Set-Content $S.Stop "x" - if (-not $S.P.WaitForExit(30000)) { 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 $S.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 "BakaShrotQuery.exe" @("@$F", $Ini) -} -function Wait-Query($Sql, $Ini, $Pattern, $Seconds = 20) { - $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 -} -function Push($Data, $Ini, [string]$Attach = "") { - $F = Join-Path $Dir "push.txt" - [IO.File]::WriteAllText($F, $Data, (New-Object System.Text.UTF8Encoding $false)) - $A = @() - if ($Attach) { $A += @("-a", $Attach) } - Tool "BakaShrotPushMessage.exe" ($A + @("@$F", $Ini)) -} -function New-File($Name, [int64]$Size, [int]$Seed) { - $P = Join-Path $Dir $Name - $R = New-Object System.Random $Seed - $Buf = New-Object byte[] ([math]::Min($Size, 16MB)) - $F = [IO.File]::OpenWrite($P) - $Left = $Size - while ($Left -gt 0) { $R.NextBytes($Buf); $N = [math]::Min($Left, $Buf.Length); $F.Write($Buf, 0, $N); $Left -= $N } - $F.Close() - $P -} -function Hash($Path) { if (Test-Path $Path) { (Get-FileHash $Path -Algorithm SHA256).Hash } else { "no file" } } -function Num($Out) { if ($Out -match '\[\["(\d+)"\]\]') { [int64]$Matches[1] } else { -1 } } - -$A = New-KeyPair; $B = New-KeyPair; $K = New-KeyPair; $G = New-KeyPair - -foreach ($Name in "a", "b") { - $Me = @{ a = $A; b = $B }[$Name]; $Peer = @{ a = $B; b = $A }[$Name] - $PeerName = @{ a = "b"; b = "a" }[$Name] - $Port = @{ a = 12413; b = 12414 }[$Name]; $PeerPort = @{ a = 12414; b = 12413 }[$Name] - $Base = @{ a = 1; b = 100 }[$Name] - Set-Content (Join-Path $Dir "$Name.ini") -Encoding Ascii -Value @" -[BakaShrot] -PrivateKey = $($Me.Priv) -Node = server$Name - -[BakaShrot.Topics] -logs = $Base -other = $($Base + 1) -secret = $($Base + 2) - -[BakaShrot.Nodes] -servera = $($Base + 10) -serverb = $($Base + 11) -kitchen = $($Base + 2) -garage = $($Base + 3) - -[BakaShrot.Server] -Host = 127.0.0.1 -Port = $Port -ReplicatingTopics = logs -DatabasePath = $(Join-Path $Dir "$Name.sqlite") -PeerSyncInterval = 1 -PeerRetryDelay = 1 -RetentionInterval = 1 -MaxAttachmentSize = 512M -UploadTimeout = 10 - -[BakaShrot.Peer.$PeerName] -Host = 127.0.0.1 -Port = $PeerPort -Node = server$PeerName -PublicKey = $($Peer.Pub) - -[BakaShrot.Client.$PeerName] -PublicKeys = $($Peer.Pub) -Node = server$PeerName -DefaultTopic = logs - -[BakaShrot.Client.kitchen] -PublicKeys = $($K.Pub) -Node = kitchen -DefaultTopic = logs -PushTopics = logs;other;secret -ReadTopics = * -AllowQuery = 1 - -[BakaShrot.Client.garage] -PublicKeys = $($G.Pub) -Node = garage -DefaultTopic = logs -PushTopics = logs -ReadTopics = logs -"@ -} -$ServerKeys = @{ 12413 = $A.Pub; 12414 = $B.Pub } -function Client-Ini($Name, $Keys, $Node, $Port) { - $P = Join-Path $Dir "$Name.ini" - Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($Keys.Priv)`r`nPublicKey = $($Keys.Pub)`r`nNode = $Node`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($ServerKeys[$Port])" - $P -} -$KitchenA = Client-Ini "kitchen-a" $K "kitchen" 12413 -$GarageA = Client-Ini "garage-a" $G "garage" 12413 -$KitchenB = Client-Ini "kitchen-b" $K "kitchen" 12414 - -foreach ($Port in 12413, 12414) { if (Test-Port $Port) { throw "Port $Port is already in use" } } -$SA = Start-Srv "a"; $SB = $null -try { - Wait-Port 12413 $SA - - "--- 1. Through the raw client" - $R = Tool "AttachmentEdgeClient.exe" @("edge", $KitchenA, $GarageA) - $R.Lines | Where-Object { $_ -match "^(PASS|FAIL| ->)" } - $Script:Fails += @($R.Lines | Where-Object { $_ -match "^FAIL" }).Count - Check "the raw client ran to the end" ($R.Code -ne $null -and ($R.Out -match "LEFT (\d+) (\d+)")) $R.Lines[-1] - $Partial = $Matches[1]; $Complete = $Matches[2] - $LeftAt = Get-Date - - "--- 2. Uploads left behind (UploadTimeout = 10)" - $Sql = "SELECT blob_id, state, received FROM blobs WHERE blob_id IN ($Partial, $Complete) ORDER BY blob_id" - $R = Query $Sql $KitchenA - Check "within UploadTimeout: both kept, receiving (0) and complete (1)" ($R.Out -match "\[\[`"$Partial`",`"0`",`"1048576`"\],\[`"$Complete`",`"1`",`"5000`"\]\]") $R.Out - $R = Wait-Query "SELECT COUNT(*) FROM blobs WHERE blob_id IN ($Partial, $Complete)" $KitchenA '\[\["0"\]\]' 25 - $After = ((Get-Date) - $LeftAt).TotalSeconds - Check "past it: both deleted" ($R.Out -match '\[\["0"\]\]') ("{0:N1} s after they were left" -f $After) - Check " not before 10 s" ($After -ge 8) ("{0:N1} s" -f $After) - Expect " their parts too" (Query "SELECT COUNT(*) FROM blob_chunks WHERE blob_id IN ($Partial, $Complete)" $KitchenA) '\[\["0"\]\]' - Expect " and the one with the wrong SHA-256 (dropped at once)" (Query "SELECT COUNT(*) FROM blobs WHERE state <> 2" $KitchenA) '\[\["0"\]\]' - Expect " the attached one is kept" (Query "SELECT COUNT(*) FROM blobs WHERE state = 2" $KitchenA) '\[\["1"\]\]' - $R = Tool "AttachmentEdgeClient.exe" @("late", $KitchenA, $Partial, $Complete) - $R.Lines | Where-Object { $_ -match "^(PASS|FAIL| ->)" } - $Script:Fails += @($R.Lines | Where-Object { $_ -match "^FAIL" }).Count - - "--- 3. Replication resuming (B killed in the middle of 400 MB)" - $Big = New-File "big.bin" 400MB 9 - $R = Push '{"big":1}' $KitchenA $Big - Check "push 400 MB to A" ($R.Code -eq 0 -and $R.Out -match "message #(\d+), with an attachment") $R.Out - $BigId = $Matches[1] - $SB = Start-Srv "b" - Wait-Port 12414 $SB - $Received = "SELECT COALESCE(MAX(b.received), 0) FROM attachments a JOIN topics t ON t.topic_id = a.topic_id LEFT JOIN blobs b ON b.blob_id = a.blob_id WHERE t.name = 'logs' AND a.message_id = $BigId" - $KilledAt = -1 - $D = (Get-Date).AddSeconds(60) - while ((Get-Date) -lt $D) { - $N = Num (Query $Received $KitchenB).Out - if ($N -ge 40MB) { Stop-Process -Id $SB.P.Id -Force; $SB.P.WaitForExit(10000) | Out-Null; $KilledAt = $N; break } - Start-Sleep -Milliseconds 50 - } - Check "B killed in the middle" ($KilledAt -gt 0 -and $KilledAt -lt 400MB) ("{0:N0} MB of 400 received" -f ($KilledAt / 1MB)) - $SB = Start-Srv "b" - Wait-Port 12414 $SB - $AfterRestart = Num (Query $Received $KitchenB).Out - Check "after the restart, what it had is still there" ($AfterRestart -ge $KilledAt) ("{0:N0} MB" -f ($AfterRestart / 1MB)) - $Copy = Join-Path $Dir "big-from-b.bin" - $D = (Get-Date).AddSeconds(90) - do { - $R = Tool "BakaShrotGetAttachment.exe" @("logs", "kitchen", $BigId, $Copy, $KitchenB) - if ($R.Code -eq 0) { break } - Start-Sleep -Milliseconds 500 - } while ((Get-Date) -lt $D) - Check "B ends up with all of it, identical" ($R.Code -eq 0 -and (Hash $Copy) -eq (Hash $Big)) $R.Out - $LogA = (Get-ChildItem $Dir -Filter "a.*.log" | ForEach-Object { Get-Content $_.FullName -Raw }) -join "`n" - $Resumed = [regex]::Matches($LogA, "Sent the attachment of logs:kitchen#$BigId to 'b' in \d+ ms, from part (\d+)") - $From = if ($Resumed.Count) { [int]$Resumed[$Resumed.Count - 1].Groups[1].Value } else { -1 } - Check "A went on from where B stopped, not from 0" ($From -gt 0 -and $From * 1MB -le $AfterRestart) ("from part $From, B had {0:N0} MB" -f ($AfterRestart / 1MB)) - Remove-Item $Copy, $Big -ErrorAction SilentlyContinue - - "--- 4. A corrupted attachment" - $HasPython = $false - try { & $Python -c "import sqlite3" 2>&1 | Out-Null; $HasPython = ($LASTEXITCODE -eq 0) } catch { } - if (-not $HasPython) { - "SKIP no Python ($Python)" - } else { - Stop-Srv $SB; $SB = $null - $Small = New-File "small.bin" (3MB + 99) 10 - $R = Push '{"corrupt":1}' $KitchenA $Small - Check "push 3 MB to A, B stopped" ($R.Code -eq 0 -and $R.Out -match "message #(\d+), with an attachment") $R.Out - $BadId = $Matches[1] - Stop-Srv $SA - $Flip = @" -import sqlite3, sys -db = sqlite3.connect(sys.argv[1]) -row = db.execute("SELECT c.rowid, c.chunk_data FROM blob_chunks c JOIN attachments a ON a.blob_id = c.blob_id WHERE a.message_id = ? AND a.topic_id = 1 AND c.chunk_index = 1", (int(sys.argv[2]),)).fetchone() -data = bytearray(row[1]); data[1000] ^= 0xFF -db.execute("UPDATE blob_chunks SET chunk_data = ? WHERE rowid = ?", (bytes(data), row[0])) -db.commit(); print("flipped") -"@ - Set-Content (Join-Path $Dir "flip.py") -Encoding Ascii -Value $Flip - $Out = & $Python -B (Join-Path $Dir "flip.py") (Join-Path $Dir "a.sqlite") $BadId 2>&1 - Check "a byte flipped in A's database, part 1" ("$Out" -eq "flipped") "$Out" - $SA = Start-Srv "a" - Wait-Port 12413 $SA - $Copy = Join-Path $Dir "bad-from-a.bin" - Expect "reading it from A: the client refuses it" (Tool "BakaShrotGetAttachment.exe" @("logs", "kitchen", $BadId, $Copy, $KitchenA)) "doesn't match its SHA-256" 1 - Check " and leaves no file" (-not (Test-Path $Copy)) "checked" - $SB = Start-Srv "b" - Wait-Port 12414 $SB - Start-Sleep -Seconds 6 - $LogB = Get-Content $SB.Log -Raw - $Drops = [regex]::Matches($LogB, "attachment of logs:kitchen#$BadId from peer 'a' doesn't match its SHA-256, dropped").Count - Check "B drops it: doesn't match" ($Drops -ge 1) "$Drops times in 6 s" - Expect "B doesn't serve it" (Tool "BakaShrotGetAttachment.exe" @("logs", "kitchen", $BadId, $Copy, $KitchenB)) "isn't here yet" 1 - # A sends it again at every check-in, so B can be receiving (1) it - # again when asked: back to missing once that copy is dropped too. - $R = Wait-Query "SELECT a.state, COALESCE(a.blob_id, 0) FROM attachments a JOIN topics t ON t.topic_id = a.topic_id WHERE t.name = 'logs' AND a.message_id = $BadId" $KitchenB '\[\["0","0"\]\]' 5 - Check "B's attachment is back to missing (0), no blob" ($R.Out -match '\[\["0","0"\]\]') $R.Out - Expect "B: no blob left behind, once cleaned" (Wait-Query "SELECT COUNT(*) FROM blobs WHERE state <> 2" $KitchenB '\[\["0"\]\]' 5) '\[\["0"\]\]' - "INFO A sends it again at every check-in: $Drops times in 6 s (PeerSyncInterval 1)" - } -} -finally { - Stop-Srv $SA; Stop-Srv $SB -} - -"--- Logs" -# Refusals are what this test asks for, their codes' names (InvalidRequest) -# aren't bad packets. -$All = (Get-ChildItem $Dir -Filter "*.log" | ForEach-Object { Get-Content $_.FullName }) | Where-Object { $_ -notmatch "Refused a request" -and $_ -match "invalid|unexpected|doesn't decrypt" } -Check "no invalid or unexpected packets in any log" ($All.Count -eq 0) ($All -join " / ") - -"" -if ($Fails) { "$Fails FAILED"; exit 1 } else { "All passed" } diff --git a/Tests/Attachments-Test.ps1 b/Tests/Attachments-Test.ps1 deleted file mode 100644 index 9cbd8bb..0000000 --- a/Tests/Attachments-Test.ps1 +++ /dev/null @@ -1,306 +0,0 @@ -# End-to-end test of attachments (Design/Attachments.md), through the tools -# (BakaShrotPushMessage -a, BakaShrotGetAttachment, BakaShrotGetLatestMessage): -# - pushed with a message, read back identical (100 KB, 5 MB + a bit, -# exactly 2 MB: one part, several, a whole number of them); -# - a message without one: refused when asked for it; -# - replicated after their messages, identical on the other server; -# - bigger than the other server's MaxAttachmentSize: its message comes, -# the attachment is refused there as not kept; -# - too big to push: refused, and the message isn't stored; -# - deleted with their message by the retention, parts included. -# Two linked servers, A (port 12410, MaxAttachmentSize 64M) and B (12411, 3M). -# Needs Build\ (Build.ps1) and Build\Bench\BenchServer.exe. -# Usage: powershell -ExecutionPolicy Bypass -File Tests\Attachments-Test.ps1 -param([string]$Build = (Join-Path $PSScriptRoot "..\Build")) -$ErrorActionPreference = "Stop" -$Build = (Resolve-Path $Build).Path -$Dir = Join-Path $Build "_attachtest" -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 "BakaShrotGenerateKeyPairs.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) { - Check $What (($Result.Code -eq $Code) -and ($Result.Out -match $Pattern)) ("[{0}] {1}" -f $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) { - if ($S.P.HasExited) { return } - 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 "BakaShrotQuery.exe" @("@$F", $Ini) -} -function Wait-Query($Sql, $Ini, $Pattern, $Seconds = 20) { - $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 -} -function Push($Data, $Ini, [string]$Topic = "", [string]$Attach = "") { - $F = Join-Path $Dir "push.txt" - [IO.File]::WriteAllText($F, $Data, (New-Object System.Text.UTF8Encoding $false)) - $A = @() - if ($Topic) { $A += @("-t", $Topic) } - if ($Attach) { $A += @("-a", $Attach) } - Tool "BakaShrotPushMessage.exe" ($A + @("@$F", $Ini)) -} -# A file of Size random bytes. -function New-File($Name, [int]$Size, [int]$Seed) { - $P = Join-Path $Dir $Name - $B = New-Object byte[] $Size - (New-Object System.Random $Seed).NextBytes($B) - [IO.File]::WriteAllBytes($P, $B) - $P -} -function Hash($Path) { if (Test-Path $Path) { (Get-FileHash $Path -Algorithm SHA256).Hash } else { "no file" } } -# Saves an attachment and compares it with the original. -function Expect-Same([string]$What, $Topic, $Node, $Id, $Original, $Ini) { - $Out = Join-Path $Dir ("got-" + [guid]::NewGuid().ToString("N") + ".bin") - $R = Tool "BakaShrotGetAttachment.exe" @($Topic, $Node, "$Id", $Out, $Ini) - $Same = ($R.Code -eq 0) -and ((Hash $Out) -eq (Hash $Original)) - Check $What $Same ("[{0}] {1}" -f $R.Code, $R.Out) -} -# Retries BakaShrotGetAttachment until it works: replicated ones come after their message. -function Wait-Same([string]$What, $Topic, $Node, $Id, $Original, $Ini, $Seconds = 20) { - $Out = Join-Path $Dir ("got-" + [guid]::NewGuid().ToString("N") + ".bin") - $D = (Get-Date).AddSeconds($Seconds) - do { - $R = Tool "BakaShrotGetAttachment.exe" @($Topic, $Node, "$Id", $Out, $Ini) - if ($R.Code -eq 0) { break } - Start-Sleep -Milliseconds 250 - } while ((Get-Date) -lt $D) - Check $What (($R.Code -eq 0) -and ((Hash $Out) -eq (Hash $Original))) ("[{0}] {1}" -f $R.Code, $R.Out) -} - -$A = New-KeyPair; $B = New-KeyPair; $K = New-KeyPair - -Set-Content (Join-Path $Dir "a.ini") -Encoding Ascii -Value @" -[BakaShrot] -PrivateKey = $($A.Priv) -Node = serverA - -[BakaShrot.Topics] -logs = 1 -short = 2 -photos = 3 - -[BakaShrot.Nodes] -serverA = 10 -serverB = 11 -kitchen = 2 -garage = 3 - -[BakaShrot.Retention] -short = 4s - -[BakaShrot.Server] -Host = 127.0.0.1 -Port = 12410 -ReplicatingTopics = logs;short;photos -DatabasePath = $(Join-Path $Dir "a.sqlite") -PeerSyncInterval = 1 -PeerRetryDelay = 1 -RetentionInterval = 1 -MaxAttachmentSize = 64M - -[BakaShrot.Peer.b] -Host = 127.0.0.1 -Port = 12411 -Node = serverB -PublicKey = $($B.Pub) - -[BakaShrot.Client.b] -PublicKeys = $($B.Pub) -Node = serverB -DefaultTopic = logs - -[BakaShrot.Client.kitchen] -PublicKeys = $($K.Pub) -Node = kitchen -DefaultTopic = logs -PushTopics = logs;short -ReadTopics = * -AllowQuery = 1 -"@ - -Set-Content (Join-Path $Dir "b.ini") -Encoding Ascii -Value @" -[BakaShrot] -PrivateKey = $($B.Priv) -Node = serverB - -[BakaShrot.Topics] -logs = 300 -short = 301 -photos = 302 - -[BakaShrot.Nodes] -serverA = 1 -serverB = 2 -kitchen = 30 -garage = 31 - -[BakaShrot.Server] -Host = 127.0.0.1 -Port = 12411 -ReplicatingTopics = logs;short;photos -DatabasePath = $(Join-Path $Dir "b.sqlite") -PeerSyncInterval = 1 -PeerRetryDelay = 1 -RetentionInterval = 1 -MaxAttachmentSize = 3M - -[BakaShrot.Peer.a] -Host = 127.0.0.1 -Port = 12410 -Node = serverA -PublicKey = $($A.Pub) - -[BakaShrot.Client.a] -PublicKeys = $($A.Pub) -Node = serverA -DefaultTopic = logs - -[BakaShrot.Client.garage] -PublicKeys = $($K.Pub) -Node = garage -DefaultTopic = photos -PushTopics = photos -ReadTopics = * -AllowQuery = 1 -"@ - -$ServerKeys = @{ 12410 = $A.Pub; 12411 = $B.Pub } -function Client-Ini($Name, $Topic, $Node, $Port) { - $P = Join-Path $Dir "$Name.ini" - Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($K.Priv)`r`nPublicKey = $($K.Pub)`r`nNode = $Node`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($ServerKeys[$Port])" - $P -} -$OnA = Client-Ini "kitchen-a" "logs" "kitchen" 12410 -$OnB = Client-Ini "garage-b" "photos" "garage" 12411 - -$Small = New-File "small.bin" (100 * 1024) 1 -$Mid = New-File "mid.bin" (5 * 1024 * 1024 + 123) 2 -$Exact = New-File "exact.bin" (2 * 1024 * 1024) 3 -$Tiny = New-File "tiny.bin" 1 4 - -foreach ($Port in 12410, 12411) { if (Test-Port $Port) { throw "Port $Port is already in use" } } -$SA = Start-Srv "a"; $SB = Start-Srv "b" -try { - Wait-Port 12410 $SA; Wait-Port 12411 $SB - Start-Sleep -Seconds 1 - - "--- Pushed with their message, read back" - Expect "push #1 with 100 KB" (Push '{"n":1}' $OnA "" $Small) "message #1, with an attachment of 102400 bytes" - $Started = Get-Date - Expect "push #2 with 5 MB + 123 bytes (6 parts)" (Push '{"n":2}' $OnA "" $Mid) "message #2, with an attachment of 5243003 bytes" - $UploadMs = ((Get-Date) - $Started).TotalMilliseconds - Expect "push #3 with exactly 2 MB (2 parts)" (Push '{"n":3}' $OnA "" $Exact) "message #3, with an attachment of 2097152 bytes" - Expect "push #4 with 1 byte" (Push '{"n":4}' $OnA "" $Tiny) "message #4" - Expect "push #5 without" (Push '{"n":5}' $OnA) "message #5$" - Expect-Same "#1 read back identical" "logs" "kitchen" 1 $Small $OnA - $Started = Get-Date - Expect-Same "#2 read back identical" "logs" "kitchen" 2 $Mid $OnA - $DownloadMs = ((Get-Date) - $Started).TotalMilliseconds - Check "5 MB up and down, tool start included" $true ("{0:N0} ms up, {1:N0} ms down" -f $UploadMs, $DownloadMs) - Expect-Same "#3 read back identical" "logs" "kitchen" 3 $Exact $OnA - Expect-Same "#4 read back identical" "logs" "kitchen" 4 $Tiny $OnA - Expect "#5 has none: refused" (Tool "BakaShrotGetAttachment.exe" @("logs", "kitchen", "5", (Join-Path $Dir "none.bin"), $OnA)) "No attachment for logs:kitchen#5" 1 - Check "a refused one leaves no file" (-not (Test-Path (Join-Path $Dir "none.bin"))) "checked" - Expect "a message that doesn't exist: refused" (Tool "BakaShrotGetAttachment.exe" @("logs", "kitchen", "99", (Join-Path $Dir "none.bin"), $OnA)) "No attachment" 1 - Expect "BakaShrotGetLatestMessage: #5, no attachment line" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "kitchen", $OnA)) "#5 \(ids 1:2\), pushed [^|]+\| \{`"n`":5\}$" - $R = Query "SELECT message_id, size, state FROM attachments WHERE topic_id = 1 AND node_id = 2 ORDER BY message_id" $OnA - Check "A's attachments: 4, all ready (2)" ($R.Out -match '\[\["1","102400","2"\],\["2","5243003","2"\],\["3","2097152","2"\],\["4","1","2"\]\]') $R.Out - Expect "A stores 6 + 2 + 1 + 1 parts" (Query "SELECT COUNT(*) FROM blob_chunks" $OnA) '\[\["10"\]\]' - - "--- Replicated after their messages (B takes up to 3M)" - $R = Wait-Query "SELECT COUNT(*) FROM messages WHERE topic = 'logs' AND node = 'kitchen'" $OnB '\[\["5"\]\]' - Check "B got the 5 messages" ($R.Out -match '\[\["5"\]\]') $R.Out - Wait-Same "B: #1 identical" "logs" "kitchen" 1 $Small $OnB - Wait-Same "B: #3 identical (2 MB)" "logs" "kitchen" 3 $Exact $OnB - Wait-Same "B: #4 identical (1 byte)" "logs" "kitchen" 4 $Tiny $OnB - Expect "B: #2 isn't kept (5 MB > 3M)" (Tool "BakaShrotGetAttachment.exe" @("logs", "kitchen", "2", (Join-Path $Dir "none.bin"), $OnB)) "isn't kept here" 1 - $R = Query "SELECT a.message_id, a.state FROM attachments a JOIN topics t ON t.topic_id = a.topic_id WHERE t.name = 'logs' ORDER BY a.message_id" $OnB - Check "B's attachments: ready, not kept (3), ready, ready" ($R.Out -match '\[\["1","2"\],\["2","3"\],\["3","2"\],\["4","2"\]\]') $R.Out - Expect "B: BakaShrotGetLatestMessage logs:kitchen, #5 has none" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "kitchen", $OnB)) "#5 \(ids 300:30\), pushed [^|]+\| \{`"n`":5\}" - - "--- Pushed on B, too big there, then replicated to A" - Expect "B refuses 5 MB (more than 3M)" (Push '{"photo":0}' $OnB "" $Mid) "too big: 5243003 bytes, at most 3145728" 1 - Expect "the message wasn't stored: the next is #1" (Push '{"photo":1}' $OnB "" $Small) "message #1, with an attachment" - Wait-Same "A got B's photos:garage#1 identical" "photos" "garage" 1 $Small $OnA - Expect "A: the latest of photos:garage" (Tool "BakaShrotGetLatestMessage.exe" @("photos", "garage", $OnA)) "Attachment: 102400 bytes \| \{`"photo`":1\}" - - "--- Deleted with their message (A: short = 4s)" - $Before = (Query "SELECT COUNT(*) FROM blob_chunks" $OnA).Out - Expect "push short #1 with 2 MB" (Push '{"s":1}' $OnA "short" $Exact) "message #1, with an attachment" - Expect "A has 2 more parts" (Query "SELECT COUNT(*) FROM blob_chunks" $OnA) '\[\["13"\]\]' - $R = Wait-Query "SELECT COUNT(*) FROM messages WHERE topic = 'short'" $OnA '\[\["0"\]\]' 15 - Check "the message is deleted past 4 s" ($R.Out -match '\[\["0"\]\]') $R.Out - $R = Wait-Query "SELECT COUNT(*) FROM blob_chunks" $OnA '\[\["11"\]\]' 10 - Check "and its 2 parts" ($R.Out -match '\[\["11"\]\]') "before $Before, now $($R.Out)" - Expect "and its attachments row" (Query "SELECT COUNT(*) FROM attachments WHERE topic_id = 2" $OnA) '\[\["0"\]\]' - Expect "and its blob" (Query "SELECT COUNT(*) FROM blobs WHERE state = 3" $OnA) '\[\["0"\]\]' - Wait-Same "B kept short#1 (no max age there)" "short" "kitchen" 1 $Exact $OnB -} -finally { - Stop-Srv $SA; Stop-Srv $SB -} - -"--- Logs" -# A and B start together: until its first link, the other one may not be -# listening yet. Refused at once on Linux, while Windows retries the connect -# for about a second, by which time it usually is. Those attempts are left out. -function Skip-EarlyLinkFailures([string[]]$Lines) { - $Linked = $false - foreach ($Line in $Lines) { - if ($Line -match "^\[Peer\] Linked to") { $Linked = $true } - if ($Linked -or $Line -notmatch "^\[Peer\] (Failed to link|Retrying)") { $Line } - } -} -$LogA = @(Skip-EarlyLinkFailures (Get-Content (Join-Path $Dir "a.log"))) -join "`n" -$LogB = @(Skip-EarlyLinkFailures (Get-Content (Join-Path $Dir "b.log"))) -join "`n" -Check "A sent B the attachments it takes" ($LogA -match "Sent the attachment of logs:kitchen#1 to 'b'" -and $LogA -match "Sent the attachment of logs:kitchen#3 to 'b'") "checked" -Check "A never sent #2 (not kept by B)" (-not ($LogA -match "Sent the attachment of logs:kitchen#2")) "checked" -Check "B sent A its photo" ($LogB -match "Sent the attachment of photos:garage#1 to 'a'") "checked" -Check "A logged deleting the parts" ($LogA -match "deleted 2 attachment parts") "checked" -$Other = ($LogA + "`n" + $LogB) -split "`r?`n" | Where-Object { $_ -match "Failed|invalid|unexpected|doesn't decrypt|SHA-256" -and $_ -notmatch "Refused a request" } -Check "no failure in A's or B's log" ($Other.Count -eq 0) ($Other -join " / ") - -"" -if ($Fails) { "$Fails FAILED"; exit 1 } else { "All passed" } diff --git a/Tests/Bench/Bench-Replication.ps1 b/Tests/Bench/Bench-Replication.ps1 deleted file mode 100644 index f314314..0000000 --- a/Tests/Bench/Bench-Replication.ps1 +++ /dev/null @@ -1,666 +0,0 @@ -# ============================================================================ -# BakaShrot replication benchmark -# -# Runs several servers linked as peers on localhost (by default 4 in a Y: one -# hub linked to 3 leaves), each with its own nodes pushing to it, and -# measures, stage by stage: -# - the push path: achieved vs offered rate, latency, failures -# - replication: lag on every server while pushing, whether it keeps up -# (trough slope, see Bench_TroughSlope() in BenchClient.pb), and how long -# it takes to drain once the pushes stop -# - every server's CPU and RAM, and its database's size -# - a query suite (queries.txt) after every stage, as the data grows -# -# Three parts: -# 1. Ramp: from an empty database, stages of -Ramp ("NodesxRate", Rate per -# node in msg/s, 0 = as fast as the server answers), to find where the -# push path and the replication saturate. -# 2. Scale: seeds every database up to each of -SeedTotals rows (identical -# on every server, see BenchSeed.pb), then runs -SteadyStage and the -# query suite at that size: how check-ins and queries hold up with -# lots of data. -# 3. Mixed: -MixedStage with queries_load.txt running in a loop against -# the hub meanwhile: reads under write load, and writes under reads. -# -# Results go into Build\Bench\runs\\: configs, per-stage samples -# (CSV, one row per sample), summaries (JSON), and report.md / results.json -# for the whole run. -# The databases and server logs go into -DataDir\\ instead, out of -# the repo: every push rewrites them, and file watchers on the repo (git -# caches, editors) otherwise burn a core or two reacting to it, skewing the -# CPU numbers. The databases are deleted at the end, unless -KeepData. -# -# Usage: -# powershell -ExecutionPolicy Bypass -File Tests\Bench\Bench-Replication.ps1 -# ... -Ramp "5x20,10x50" -SeedTotals @() -PushSeconds 10 quick run -# ... -Topology Mesh -PeerSyncInterval 1 variations -# ... -Synchronous NORMAL the servers' Synchronous (FULL by default) -# ... -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, - # The servers' [BakaShrot.Server] Synchronous: FULL like their default, - # NORMAL to compare with the runs from before 2026-11-09. - [ValidateSet("FULL", "NORMAL")] - [string]$Synchronous = "FULL", - [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\BakaShrotGenerateKeyPairs\BakaShrotGenerateKeyPairs.pb", "BakaShrotGenerateKeyPairs.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 "BakaShrotGenerateKeyPairs.exe") - if ($LASTEXITCODE -ne 0) { throw "BakaShrotGenerateKeyPairs 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 - # The bench's one key writes as every node: a client section per node. - $ClientSections = (@($Server.FirstNode..$LastNode) + @($Server.MonitorNode, $Server.QueryNode) | ForEach-Object { @" -[BakaShrot.Client.bench$_] -PublicKeys = $($ClientKeys.PublicKey) -Node = $_ -DefaultTopic = $TopicId -AllowRead = 1 -AllowWrite = 1 -AllowQuery = 1 - -"@ }) -join "`r`n" - - # 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) -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 -Synchronous = $Synchronous - -$ClientSections -"@ - foreach ($PeerIndex in $Server.Peers) { - $Peer = $Servers[$PeerIndex] - $Text += @" -[BakaShrot.Peer.$($Peer.Name)] -Host = 127.0.0.1 -Port = $($Peer.Port) -Node = $($Peer.NodeId) -PublicKey = $($Peer.PublicKey) -$(if ($Names -eq "Wildcard") { "AcceptNodes = n*" }) - -[BakaShrot.Client.$($Peer.Name)] -PublicKeys = $($Peer.PublicKey) -Node = $($Peer.NodeId) -AllowRead = 0 -AllowWrite = 0 -AllowQuery = 0 - -"@ - } - Set-Content -Path $Server.ConfigPath -Value $Text -Encoding Ascii -} - - -# --- Servers ---------------------------------------------------------------- - -$script:StartCount = 0 - -function Test-Port($Port) { - $Client = New-Object System.Net.Sockets.TcpClient - try { - $Async = $Client.BeginConnect("127.0.0.1", $Port, $null, $null) - if ($Async.AsyncWaitHandle.WaitOne(200) -and $Client.Connected) { return $true } - return $false - } catch { - return $false - } finally { - $Client.Close() - } -} - -function Start-Servers($Servers) { - $script:StartCount++ - foreach ($Server in $Servers) { - Remove-Item $Server.StopFile -ErrorAction SilentlyContinue - $Log = Join-Path $LogDir "$($Server.Name)-$($script:StartCount).log" - $Server.Process = Start-Process -FilePath (Join-Path $OutDir "BenchServer.exe") ` - -ArgumentList "`"$($Server.ConfigPath)`"", "`"$($Server.StopFile)`"" ` - -WorkingDirectory $OutDir -NoNewWindow -PassThru ` - -RedirectStandardOutput $Log -RedirectStandardError "$Log.err" - } - foreach ($Server in $Servers) { - $Deadline = (Get-Date).AddSeconds(15) - while (-not (Test-Port $Server.Port)) { - if ($Server.Process.HasExited) { throw "$($Server.Name) exited, see its log in $LogDir" } - if ((Get-Date) -gt $Deadline) { throw "$($Server.Name) isn't listening on $($Server.Port)" } - Start-Sleep -Milliseconds 100 - } - } - # Let the peers link (they retry every 2 s) and run their first check-in. - Start-Sleep -Seconds 4 - Write-Host "Servers up: $(($Servers | ForEach-Object { "$($_.Name)=pid $($_.Process.Id)" }) -join ', ')" -} - -function Stop-Servers($Servers) { - foreach ($Server in $Servers) { - if ($Server.Process -and -not $Server.Process.HasExited) { - Set-Content -Path $Server.StopFile -Value "stop" - } - } - foreach ($Server in $Servers) { - if ($Server.Process) { - if (-not $Server.Process.WaitForExit(30000)) { - Write-Warning "$($Server.Name) didn't stop, killing it" - $Server.Process.Kill() - } - $Server.Process = $null - } - } -} - - -# --- Stages ----------------------------------------------------------------- - -function ConvertTo-Stage($Spec) { - $Fields = $Spec.Trim().ToLower().Split("x") - return [pscustomobject]@{ Nodes = [int]$Fields[0]; Rate = [double]$Fields[1] } -} - -function Write-Plan($Path, $Servers, $ClientKeys, $Stage, $Name, $QueryFile, $QueryLoad) { - $Text = @" -[Bench] -PrivateKey = $($ClientKeys.PrivateKey) -PublicKey = $($ClientKeys.PublicKey) -TopicId = $TopicId -ServerCount = $($Servers.Count) -PushSeconds = $PushSeconds -Rate = $($Stage.Rate) -MessageSize = $MessageSize -SampleMs = 1000 -DrainSampleMs = 250 -DrainTimeout = $DrainTimeout -PeerSyncInterval = $PeerSyncInterval -SamplesCsv = $(Join-Path $RunDir "$Name.samples.csv") -SummaryOut = $(Join-Path $RunDir "$Name.summary.json") -QueryFile = $QueryFile -QueryRepeats = $QueryRepeats -QueryOut = $(Join-Path $RunDir "$Name.queries.json") - -"@ - foreach ($Server in $Servers) { - $ProcId = 0 - if ($Server.Process) { $ProcId = $Server.Process.Id } - # The query suite runs on the hub and the first leaf, the query load - # only on the hub. - $Text += @" -[Server$($Server.Index + 1)] -Name = $($Server.Name) -Host = 127.0.0.1 -Port = $($Server.Port) -PublicKey = $($Server.PublicKey) -Pid = $ProcId -DatabasePath = $($Server.DatabasePath) -FirstNode = $($Server.FirstNode) -MaxNodes = $MaxNodesPerServer -NodeCount = $($Stage.Nodes) -MonitorNode = $($Server.MonitorNode) -QueryNode = $($Server.QueryNode) -QueryLoad = $([int]($QueryLoad -and $Server.Index -eq 0)) -Query = $([int]($Server.Index -le 1)) - -"@ - } - Set-Content -Path $Path -Value $Text -Encoding Ascii -} - -function Invoke-BenchClient($Mode, $Plan) { - & (Join-Path $OutDir "BenchClient.exe") $Mode $Plan | ForEach-Object { Write-Host " $_" } - if ($LASTEXITCODE -ne 0) { throw "BenchClient $Mode failed" } -} - -$script:Results = @() -$script:QueryResults = @() - -function Invoke-Stage($Part, $Name, $Stage, $Servers, $ClientKeys, [switch]$QueryLoad) { - $Plan = Join-Path $RunDir "$Name.plan.ini" - $LoadFile = "" - if ($QueryLoad) { $LoadFile = Join-Path $BenchDir "queries_load.txt" } - Write-Plan $Plan $Servers $ClientKeys $Stage $Name $LoadFile $QueryLoad - - $RateText = if ($Stage.Rate -gt 0) { "$($Stage.Rate) msg/s" } else { "max" } - Write-Host "" - Write-Host "=== $Name : $($Stage.Nodes) nodes/server x $RateText, $PushSeconds s ===" -ForegroundColor Cyan - # Other processes busy meanwhile (antivirus scanning the databases...), - # tick-based, only good enough to spot the big ones. - $Before = @{} - Get-Process | ForEach-Object { $Before[$_.Id] = $_.CPU } - $StartTime = Get-Date - Invoke-BenchClient "run" $Plan - $Seconds = ((Get-Date) - $StartTime).TotalSeconds - $Others = Get-Process | Where-Object { $_.Name -notin @("BenchServer", "BenchClient", "Idle") -and $null -ne $_.CPU } | ForEach-Object { - $Previous = 0 - if ($Before.ContainsKey($_.Id)) { $Previous = $Before[$_.Id] } - [pscustomobject]@{ Name = $_.Name; Percent = 100 * ($_.CPU - $Previous) / $Seconds } - } | Sort-Object Percent -Descending | Select-Object -First 3 - $Summary = Get-Content (Join-Path $RunDir "$Name.summary.json") -Raw | ConvertFrom-Json - $Summary | Add-Member -NotePropertyName OtherProcesses -NotePropertyValue (($Others | Where-Object Percent -ge 5 | ForEach-Object { "$($_.Name) $(Format-Num $_.Percent)" }) -join ", ") - $Summary | Add-Member -NotePropertyName Stage -NotePropertyValue $Name - $Summary | Add-Member -NotePropertyName Part -NotePropertyValue $Part - $Summary | Add-Member -NotePropertyName NodesPerServer -NotePropertyValue $Stage.Nodes - $script:Results += $Summary - - # The query suite, on the idle servers. - Write-Plan $Plan $Servers $ClientKeys $Stage $Name (Join-Path $BenchDir "queries.txt") $false - Invoke-BenchClient "query" $Plan - $Rows = ($Summary.Servers | Measure-Object -Property Rows -Maximum).Maximum - foreach ($Query in (Get-Content (Join-Path $RunDir "$Name.queries.json") -Raw | ConvertFrom-Json)) { - $Query | Add-Member -NotePropertyName Stage -NotePropertyValue $Name - $Query | Add-Member -NotePropertyName DataRows -NotePropertyValue $Rows - $script:QueryResults += $Query - } - return $Summary -} - -function Invoke-Seed($Servers, $TargetRows, $CurrentRows) { - $Nodes = $Servers.Count * $MaxNodesPerServer - $PerNode = [math]::Ceiling(($TargetRows - $CurrentRows) / $Nodes) - if ($PerNode -le 0) { return } - $Spec = ($Servers | ForEach-Object { "$($_.FirstNode)-$($_.FirstNode + $MaxNodesPerServer - 1)" }) -join "," - Write-Host "" - Write-Host "=== Seeding to ~$TargetRows rows per server ($PerNode more per node, in every database) ===" -ForegroundColor Cyan - Stop-Servers $Servers - $Dbs = $Servers | ForEach-Object { $_.DatabasePath } - & (Join-Path $OutDir "BenchSeed.exe") $TopicId $Spec $PerNode $MessageSize @Dbs | ForEach-Object { Write-Host " $_" } - if ($LASTEXITCODE -ne 0) { throw "BenchSeed failed" } - Start-Servers $Servers -} - - -# --- Report ----------------------------------------------------------------- - -function Format-Num($Value, $Decimals = 0) { - return ([double]$Value).ToString("N$Decimals", [Globalization.CultureInfo]::InvariantCulture) -} - -function Get-Verdict($Summary) { - $Notes = @() - if ($Summary.Rate -gt 0 -and $Summary.PushRate -lt 0.9 * $Summary.OfferedRate) { $Notes += "push saturated" } - if ($Summary.Failed -gt 0) { $Notes += "$($Summary.Failed) failed pushes" } - # The trough slope is too noisy for a verdict (check-ins drift against the - # windows), the lag in seconds of pushes isn't: keeping up means about - # two check-ins' worth at most, through the hub. - $MaxLagSeconds = ($Summary.Servers | Measure-Object -Property LagMaxSeconds -Maximum).Maximum - if ($MaxLagSeconds -gt 2 * $PeerSyncInterval + 2) { $Notes += "replication lagging" } - if (-not $Summary.Drained) { $Notes += "NOT drained" } - elseif ($Summary.DrainSeconds -gt 2 * $PeerSyncInterval + 5) { $Notes += "slow drain" } - if ($Notes.Count -eq 0) { return "ok" } - return $Notes -join ", " -} - -function Get-LogIssues($Servers) { - $Issues = @() - foreach ($Server in $Servers) { - $Logs = Get-ChildItem $LogDir -Filter "$($Server.Name)-*.log" - $Counts = [ordered]@{} - foreach ($Pattern in @("Refused", "Failed", "locked", "timed out", "Dropping", "Lost the link", "too big")) { - $Counts[$Pattern] = @($Logs | Select-String -SimpleMatch $Pattern).Count - } - $Sent = @($Logs | Select-String -Pattern "\[Peer\] Sent (\d+) messages .* in (\d+) ms") - $Messages = 0; $Ms = 0 - foreach ($Match in $Sent) { - $Messages += [int]$Match.Matches[0].Groups[1].Value - $Ms += [int]$Match.Matches[0].Groups[2].Value - } - $Issues += [pscustomobject]@{ - Server = $Server.Name; Counts = $Counts - ReplicatedOut = $Messages; ReplicateMs = $Ms; CatchUps = $Sent.Count - } - } - return $Issues -} - -function Write-Report($Servers) { - $Lines = @() - $Lines += "# BakaShrot replication benchmark, $(Get-Date -Format 'yyyy-MM-dd HH:mm')" - $Lines += "" - $Cpu = (Get-CimInstance Win32_Processor | Select-Object -First 1).Name.Trim() - $Ram = [math]::Round((Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory / 1GB) - $Lines += "- Machine: $Cpu, $Ram GB RAM, everything on localhost" - $Lines += "- Topology: $Topology, $ServerCount servers ($(($Servers | ForEach-Object { "$($_.Name) <-> " + (($_.Peers | ForEach-Object { $Servers[$_].Name }) -join '/') }) -join '; '))" - $Lines += "- Names: $Names ($(if ($Names -eq 'Wildcard') { 'each server names its own nodes, peers take them by AcceptNodes = n*' } else { 'every node named on every server' }))" - $Lines += "- Messages: ~$MessageSize bytes of JSON, PeerSyncInterval $PeerSyncInterval s, PeerBatchSize $PeerBatchSize, $PushSeconds s per stage" - $Lines += "- Built with: $($script:CompilerName), SQLite $((Get-Item (Join-Path $OutDir 'sqlite3.dll')).VersionInfo.ProductVersion)" - $Lines += "- CPU in % of one core (100 = one core busy), System = whole machine in %, Bench = the load generator itself (% of one core)" - $Lines += "" - - $Lines += "## Stages" - $Lines += "" - $Lines += "- Max lag: most messages a server was missing while pushing. Trough: the lowest lag of the last check-in window, slope: how fast those troughs rise (~0 = keeps up)." - $Lines += "" - $Lines += "| Stage | Nodes | Offered msg/s | Pushed msg/s | Push p50 / p99 / max ms | Failed | Max lag msgs (s of pushes) | Last trough | Trough slope msg/s | Drain s | Verdict |" - $Lines += "|---|---|---|---|---|---|---|---|---|---|---|" - foreach ($R in $script:Results) { - $Offered = if ($R.Rate -gt 0) { Format-Num $R.OfferedRate } else { "max" } - $Lag = ($R.Servers | Measure-Object -Property LagMaxPush -Maximum).Maximum - $LagSeconds = ($R.Servers | Measure-Object -Property LagMaxSeconds -Maximum).Maximum - $Trough = ($R.Servers | Measure-Object -Property LagTroughLast -Maximum).Maximum - $Slope = ($R.Servers | Measure-Object -Property LagSlope -Maximum).Maximum - $Drain = if ($R.Drained) { Format-Num $R.DrainSeconds 1 } else { "> $DrainTimeout" } - $Lines += "| $($R.Stage) | $($R.NodesPerServer) x $ServerCount | $Offered | $(Format-Num $R.PushRate) | $(Format-Num $R.PushP50Ms 1) / $(Format-Num $R.PushP99Ms 1) / $(Format-Num $R.PushMaxMs 0) | $($R.Failed) | $(Format-Num $Lag) ($(Format-Num $LagSeconds 1)) | $(Format-Num $Trough) | $(Format-Num $Slope 1) | $Drain | $(Get-Verdict $R) |" - } - $Lines += "" - - $Lines += "## Resources while pushing" - $Lines += "" - $Header = "| Stage | System CPU avg / max | Bench CPU |" - $Sep = "|---|---|---|" - foreach ($Server in $Servers) { $Header += " $($Server.Name) CPU avg / max | $($Server.Name) RAM WS / private MB |"; $Sep += "---|---|" } - $Header += " Other busy processes (% core) |"; $Sep += "---|" - $Lines += $Header - $Lines += $Sep - foreach ($R in $script:Results) { - $Row = "| $($R.Stage) | $(Format-Num $R.SystemCpuAvg) % / $(Format-Num $R.SystemCpuMax) % | $(Format-Num $R.BenchCpuAvg) |" - foreach ($S in $R.Servers) { $Row += " $(Format-Num $S.CpuAvgPush) / $(Format-Num $S.CpuMaxPush) | $(Format-Num $S.WorkingSetMaxMb 1) / $(Format-Num $S.PrivateMaxMb 1) |" } - $Row += " $($R.OtherProcesses) |" - $Lines += $Row - } - $Lines += "" - - $Lines += "## Per server, end of stage" - $Lines += "" - $Header = "| Stage |" - $Sep = "|---|" - foreach ($Server in $Servers) { $Header += " $($Server.Name) rows | DB MB | max lag | monitor query avg / max ms |"; $Sep += "---|---|---|---|" } - $Lines += $Header - $Lines += $Sep - foreach ($R in $script:Results) { - $Row = "| $($R.Stage) |" - foreach ($S in $R.Servers) { $Row += " $(Format-Num $S.Rows) | $(Format-Num $S.DbMb 1) | $(Format-Num $S.LagMaxPush) | $(Format-Num $S.MonitorAvgMs 1) / $(Format-Num $S.MonitorMaxMs 1) |" } - $Lines += $Row - } - $Lines += "" - - $Lines += "## Queries, idle, median ms (on $($Servers[0].Name))" - $Lines += "" - $Stages = $script:QueryResults | Where-Object Server -eq $Servers[0].Name | Select-Object -ExpandProperty Stage -Unique - $Names = $script:QueryResults | Select-Object -ExpandProperty Name -Unique - $Header = "| Query |" - $Sep = "|---|" - foreach ($Stage in $Stages) { - $Rows = ($script:QueryResults | Where-Object { $_.Stage -eq $Stage } | Select-Object -First 1).DataRows - $Header += " $Stage ($(Format-Num $Rows) rows) |"; $Sep += "---|" - } - $Lines += $Header - $Lines += $Sep - foreach ($Name in $Names) { - $Row = "| $Name |" - foreach ($Stage in $Stages) { - $Q = $script:QueryResults | Where-Object { $_.Stage -eq $Stage -and $_.Name -eq $Name -and $_.Server -eq $Servers[0].Name } | Select-Object -First 1 - if (-not $Q) { $Row += " |" } - elseif ($Q.Count -eq 0) { $Row += " FAIL: $($Q.LastError) |" } - else { $Row += " $(Format-Num $Q.P50Ms 1) |" } - } - $Lines += $Row - } - $Lines += "" - - $Mixed = $script:Results | Where-Object { $_.QueriesUnderLoad.Count -gt 0 } - foreach ($R in $Mixed) { - $Lines += "## Queries under load ($($R.Stage), on $($Servers[0].Name), while pushing $(Format-Num $R.PushRate) msg/s)" - $Lines += "" - $Lines += "| Query | Runs | p50 ms | p90 ms | max ms | Failures |" - $Lines += "|---|---|---|---|---|---|" - foreach ($Q in $R.QueriesUnderLoad) { - $Lines += "| $($Q.Name) | $($Q.Count) | $(Format-Num $Q.P50Ms 1) | $(Format-Num $Q.P90Ms 1) | $(Format-Num $Q.MaxMs 1) | $($Q.Failures) $($Q.LastError) |" - } - $Lines += "" - } - - $Lines += "## Server logs" - $Lines += "" - $Lines += "| Server | Catch-ups sent | Messages replicated out | ms spent sending | Refused | Failed | locked | timed out | Dropping | Lost the link | too big |" - $Lines += "|---|---|---|---|---|---|---|---|---|---|---|" - foreach ($I in (Get-LogIssues $Servers)) { - $Lines += "| $($I.Server) | $($I.CatchUps) | $(Format-Num $I.ReplicatedOut) | $(Format-Num $I.ReplicateMs) | $(($I.Counts.Values) -join ' | ') |" - } - $Lines += "" - - $Report = Join-Path $RunDir "report.md" - Set-Content -Path $Report -Value ($Lines -join "`r`n") -Encoding UTF8 - @{ Results = $script:Results; Queries = $script:QueryResults } | ConvertTo-Json -Depth 8 | Set-Content (Join-Path $RunDir "results.json") -Encoding UTF8 - return $Report -} - - -# --- Main ------------------------------------------------------------------- - -if (-not $SkipBuild) { Invoke-Build } -Copy-Dlls -New-Item -ItemType Directory -Force $RunDir, $LogDir | Out-Null -Write-Host "Run folder: $RunDir" - -$ClientKeys = New-KeyPair -$Servers = @(New-Servers) -foreach ($Server in $Servers) { Write-ServerConfig $Server $Servers $ClientKeys } - -try { - Start-Servers $Servers - $Last = $null - - if ($PartList -contains "Ramp") { - $i = 0 - foreach ($Spec in $Ramp.Split(",")) { - $i++ - $Stage = ConvertTo-Stage $Spec - $Last = Invoke-Stage "Ramp" ("ramp{0:D2}-{1}" -f $i, $Spec.Trim()) $Stage $Servers $ClientKeys - } - } - - if ($PartList -contains "Scale") { - foreach ($Target in $SeedTotals) { - $Current = 0 - if ($Last) { $Current = ($Last.Servers | Measure-Object -Property Rows -Minimum).Minimum } - Invoke-Seed $Servers $Target $Current - $Last = Invoke-Stage "Scale" ("scale-{0}k" -f [math]::Round($Target / 1000)) (ConvertTo-Stage $SteadyStage) $Servers $ClientKeys - } - } - - if ($PartList -contains "Mixed") { - $Last = Invoke-Stage "Mixed" "mixed" (ConvertTo-Stage $MixedStage) $Servers $ClientKeys -QueryLoad - } -} -finally { - Stop-Servers $Servers - if ($script:Results.Count -gt 0) { - $Report = Write-Report $Servers - Write-Host "" - Write-Host "Report: $Report" - } - Write-Host "Server logs: $LogDir" - if (-not $KeepData) { - Get-ChildItem $RunData -Filter "*.sqlite*" | Remove-Item -Force - } else { - Write-Host "Databases kept in $RunData" - } -} diff --git a/Tests/Bench/BenchClient.pb b/Tests/Bench/BenchClient.pb deleted file mode 100644 index c7115bb..0000000 --- a/Tests/Bench/BenchClient.pb +++ /dev/null @@ -1,1372 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: BenchClient.pb -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; BakaShrot Bench Client -; -; Usage: BenchClient -; -; run One benchmark stage: -; 1. One thread per pushing node, each with its own connection to -; its server, all connected before the clock starts. -; 2. They push for [Bench] PushSeconds, at [Bench] Rate messages -; per second each (0: as fast as the server answers). -; 3. Meanwhile, every [Bench] SampleMs, samples every server: -; how many messages of every node it has (replication lag), -; its CPU and RAM, its database's size. -; 4. Then keeps sampling, every [Bench] DrainSampleMs, until every -; server has every message (drained) or [Bench] DrainTimeout. -; Optionally, a thread runs [Bench] QueryFile in a loop against the -; servers with QueryLoad = 1 while pushing, to see how queries hold -; up under load. -; Writes every sample to [Bench] SamplesCsv, and the stage's summary -; to [Bench] SummaryOut (JSON). -; query Runs every query of [Bench] QueryFile against every server with -; Query = 1, [Bench] QueryRepeats times each (plus a warm-up), and -; writes their timings to [Bench] QueryOut (JSON). -; -; Plan.ini (written by Tests/Bench/Bench-Replication.ps1): -; [Bench] -; PrivateKey, PublicKey The client key every server registers. -; TopicId Topic every node pushes into. -; ServerCount Number of [Server] sections, 1-based. -; PushSeconds, Rate, MessageSize, SampleMs, DrainSampleMs, DrainTimeout -; SamplesCsv, SummaryOut, QueryFile, QueryRepeats, QueryOut -; [Server] -; Name, Host, Port, Pid, DatabasePath -; PublicKey The server's, it must prove it holds the private one. -; FirstNode, MaxNodes Its nodes are FirstNode to FirstNode+MaxNodes-1, -; all of them are monitored. -; NodeCount How many of them push in this stage, from FirstNode. -; MonitorNode, QueryNode Nodes used by the sampler and the queries. -; QueryLoad, Query 0/1, see above. -; -; Query file: one query per line, "Name | SQL", # starts a comment. -; {TOPIC} and {NODE} are replaced by the topic id and the server's FirstNode. -; "@latest" as the SQL does a GetLatestMessage of {NODE} instead. -; -; CPU is in % of one core (200 = two cores busy), the system's in % of the -; whole machine. RAM is the working set and the private bytes, in MB. -; Windows only (process sampling), compile as a thread-safe console program. -; ============================================================================ - -EnableExplicit - -CompilerIf Not #PB_Compiler_Thread - CompilerError "BenchClient needs the thread-safe option." -CompilerEndIf - -XIncludeFile "../../Commons/Networking/Outbound.pbi" - - -#Bench_RequestTimeout = 60000 -#Bench_MaxNodes = 512 - - -; --- Windows process sampling ------------------------------------------------ - -Structure BenchMemoryCounters - cb.l - PageFaultCount.l - PeakWorkingSetSize.i - WorkingSetSize.i - QuotaPeakPagedPoolUsage.i - QuotaPagedPoolUsage.i - QuotaPeakNonPagedPoolUsage.i - QuotaNonPagedPoolUsage.i - PagefileUsage.i - PeakPagefileUsage.i -EndStructure - -; CPU use is measured in cycles, not with GetProcessTimes(): that one is -; charged per clock tick, and threads that wake up from a Delay(), work a bit -; and sleep again before the next tick (all of BakaShrot's polling) are -; mostly never charged at all. -Prototype.i Proto_QueryProcessCycleTime(Process.i, *Cycles) -Prototype.i Proto_QueryThreadCycleTime(Thread.i, *Cycles) -Prototype.i Proto_QueryIdleProcessorCycleTime(*BufferLength, *Buffer) -Prototype.i Proto_GetProcessMemoryInfo(Process.i, *Counters, Cb.l) - -Global Bench_QueryProcessCycleTime.Proto_QueryProcessCycleTime -Global Bench_QueryThreadCycleTime.Proto_QueryThreadCycleTime -Global Bench_QueryIdleProcessorCycleTime.Proto_QueryIdleProcessorCycleTime -Global Bench_GetProcessMemoryInfo.Proto_GetProcessMemoryInfo -Global Bench_CyclesPerMs.d -Global Bench_CpuCount.i -Global Bench_QpcFrequency.q - - -; --- State ------------------------------------------------------------------- - -Structure BenchLagSample - T.d - Lag.q -EndStructure - -Structure BenchServer - Name.s - Host.s - Port.i - Pid.i - DatabasePath.s - FirstNode.i - MaxNodes.i - NodeCount.i - MonitorNode.i - QueryNode.i - QueryLoad.i - Query.i - ; The server's Ed25519 public key, it must prove it holds the private one. - PublicKey.a[#BakaShrot_Ed25519_PublicKeySize] - - Monitor.BakaShrot_Outbound - Process.i - LastCpu.q - - ; Latest sample - Present.q - Lag.q - CpuPercent.d - WorkingSetMb.d - PrivateMb.d - DbMb.d - MonitorMs.d - - ; Stage stats - CpuSumPush.d - CpuMaxPush.d - CpuCountPush.i - CpuSumDrain.d - CpuMaxDrain.d - CpuCountDrain.i - WorkingSetMaxMb.d - PrivateMaxMb.d - PresentAtPushStart.q - LagMaxPush.q - LagAtPushEnd.q - MonitorSumMs.d - MonitorMaxMs.d - MonitorCount.i - MonitorFailures.i - ; Every lag sample while pushing, see Bench_TroughSlope(). - List PushLag.BenchLagSample() -EndStructure - -Structure BenchPusher - ServerIndex.i - NodeId.i - ThreadId.i - Ready.i - ConnectFailed.i - Sent.q - Failed.q - Reconnects.i - LastError.s - List LatencyMs.f() -EndStructure - -Structure BenchQueryStats - Name.s - Sql.s - List LatencyMs.f() - Failures.i - LastError.s -EndStructure - -Global Bench_PlanPath.s -Global Bench_TopicId.i -Global Bench_PublicKey.s -Global Dim Bench_PrivateKey.a(#BakaShrot_Ed25519_PrivateKeySize - 1) -Global Bench_PushSeconds.i, Bench_Rate.d, Bench_MessageSize.i -Global Bench_SampleMs.i, Bench_DrainSampleMs.i, Bench_DrainTimeout.i -Global Bench_SamplesCsv.s, Bench_SummaryOut.s, Bench_QueryFile.s, Bench_QueryOut.s -Global Bench_QueryRepeats.i - -Global Bench_ServerCount.i -Global Dim Bench_Servers.BenchServer(0) - -; Every monitored node, and how many messages of it each server has. -Global Bench_NodeCount.i -Global Dim Bench_Nodes.i(0) -Global Dim Bench_Present.q(0, 0) -Global Bench_MonitorSql.s - -Global Bench_PusherCount.i -Global Dim Bench_Pushers.BenchPusher(0) - -Global Bench_PushStarted.i, Bench_StopPush.i -Global Bench_StartMs.d - -; Query load during the push -Global NewList Bench_LoadStats.BenchQueryStats() - -; Sampling -Global Bench_LastSampleMs.d -Global Bench_LastIdleCycles.q -Global Bench_LastSelfCpu.q -Global Bench_SyncInterval.i -Global Bench_SystemCpu.d, Bench_SelfCpu.d -Global Bench_SystemCpuSum.d, Bench_SystemCpuMax.d, Bench_SystemCpuCount.i -Global Bench_SelfCpuSum.d, Bench_SelfCpuCount.i -Global Bench_LastPushed.q -Global Bench_CsvFile.i - - -Procedure.d Bench_NowMs() - Protected Count.q - QueryPerformanceCounter_(@Count) - ProcedureReturn Count * 1000.0 / Bench_QpcFrequency -EndProcedure - - -Procedure Bench_Fail(Message.s) - PrintN("[Bench] " + Message) - End 1 -EndProcedure - - -; --- Plan -------------------------------------------------------------------- - -Procedure Bench_LoadPlan(PlanPath.s) - Protected i.i, n.i, Node.i - - If Not OpenPreferences(PlanPath) - Bench_Fail("Failed to open the plan '" + PlanPath + "'") - EndIf - - PreferenceGroup("Bench") - Bench_PublicKey = ReadPreferenceString("PublicKey", "") - Bench_TopicId = ReadPreferenceLong("TopicId", 1) - Bench_ServerCount = ReadPreferenceLong("ServerCount", 0) - Bench_PushSeconds = ReadPreferenceLong("PushSeconds", 10) - Bench_Rate = ReadPreferenceDouble("Rate", 10) - Bench_MessageSize = ReadPreferenceLong("MessageSize", 200) - Bench_SampleMs = ReadPreferenceLong("SampleMs", 1000) - Bench_DrainSampleMs = ReadPreferenceLong("DrainSampleMs", 250) - Bench_DrainTimeout = ReadPreferenceLong("DrainTimeout", 120) - Bench_SyncInterval = ReadPreferenceLong("PeerSyncInterval", 5) - Bench_SamplesCsv = ReadPreferenceString("SamplesCsv", "samples.csv") - Bench_SummaryOut = ReadPreferenceString("SummaryOut", "summary.json") - Bench_QueryFile = ReadPreferenceString("QueryFile", "") - Bench_QueryRepeats = ReadPreferenceLong("QueryRepeats", 5) - Bench_QueryOut = ReadPreferenceString("QueryOut", "queries.json") - If Not DecodeKeyFromString(ReadPreferenceString("PrivateKey", ""), @Bench_PrivateKey(0), #BakaShrot_Ed25519_PrivateKeySize) - Bench_Fail("Invalid [Bench] PrivateKey") - EndIf - If Bench_ServerCount < 1 - Bench_Fail("No servers in the plan") - EndIf - - Dim Bench_Servers.BenchServer(Bench_ServerCount - 1) - Bench_NodeCount = 0 - For i = 0 To Bench_ServerCount - 1 - PreferenceGroup("Server" + Str(i + 1)) - With Bench_Servers(i) - \Name = ReadPreferenceString("Name", "server" + Str(i + 1)) - \Host = ReadPreferenceString("Host", "127.0.0.1") - \Port = ReadPreferenceLong("Port", 0) - \Pid = ReadPreferenceLong("Pid", 0) - \DatabasePath = ReadPreferenceString("DatabasePath", "") - \FirstNode = ReadPreferenceLong("FirstNode", 0) - \MaxNodes = ReadPreferenceLong("MaxNodes", 0) - \NodeCount = ReadPreferenceLong("NodeCount", 0) - \MonitorNode = ReadPreferenceLong("MonitorNode", 0) - \QueryNode = ReadPreferenceLong("QueryNode", 0) - \QueryLoad = ReadPreferenceLong("QueryLoad", 0) - \Query = ReadPreferenceLong("Query", 0) - If Not DecodeKeyFromString(ReadPreferenceString("PublicKey", ""), @\PublicKey[0], #BakaShrot_Ed25519_PublicKeySize) - Bench_Fail("Server" + Str(i + 1) + " has no valid PublicKey in the plan") - EndIf - If \NodeCount > \MaxNodes - \MaxNodes = \NodeCount - EndIf - Bench_NodeCount + \MaxNodes - EndWith - Next - ClosePreferences() - - If Bench_NodeCount > #Bench_MaxNodes - Bench_Fail("Too many nodes") - EndIf - - ; Every monitored node, and one query asking a server for all of them. - ; One indexed MAX() per node: cheap, even with millions of rows. By name - ; ("bench", "n" + id, see Bench-Replication.ps1) through the "messages" - ; view: each server can have its own ids for them (-Names Wildcard). - Dim Bench_Nodes.i(Bench_NodeCount - 1) - Dim Bench_Present.q(Bench_ServerCount - 1, Bench_NodeCount - 1) - n = 0 - Bench_MonitorSql = "SELECT " - For i = 0 To Bench_ServerCount - 1 - For Node = Bench_Servers(i)\FirstNode To Bench_Servers(i)\FirstNode + Bench_Servers(i)\MaxNodes - 1 - Bench_Nodes(n) = Node - If n > 0 - Bench_MonitorSql + ", " - EndIf - Bench_MonitorSql + "(SELECT COALESCE(MAX(message_id), 0) FROM messages WHERE topic = 'bench' AND node = 'n" + Str(Node) + "')" - n + 1 - Next - Next -EndProcedure - - -; --- Requests ---------------------------------------------------------------- - -Procedure.i Bench_Connect(*Outbound.BakaShrot_Outbound, *Server.BenchServer, NodeId.i) - Protected Identity.BakaShrot_OutboundIdentity - - Identity\Node = Str(NodeId) - Identity\PublicKey = Bench_PublicKey - Identity\PrivateKey = @Bench_PrivateKey(0) - ProcedureReturn BakaShrot_Outbound_Connect(*Outbound, *Server\Host, *Server\Port, @Identity, @*Server\PublicKey[0]) -EndProcedure - - -; Sends *Request, returns the answer (free it) or 0 if the connection failed. -Procedure.i Bench_Request(*Outbound.BakaShrot_Outbound, *Request, RequestSize.i, *AnswerSize.Integer) - If Not BakaShrot_Outbound_Send(*Outbound, *Request, RequestSize) - ProcedureReturn 0 - EndIf - ProcedureReturn BakaShrot_Outbound_WaitPacket(*Outbound, *AnswerSize, #Bench_RequestTimeout) -EndProcedure - - -Procedure.s Bench_RefusalReason(*Answer, AnswerSize.i) - Protected *View.MsgPackData, *Refused.BakaShrot_RequestRefused, Reason.s - - Reason = "unexpected answer" - If BakaShrot_GetPacketType(*Answer, AnswerSize) = #BakaShrot_PacketType_RequestRefused - *Refused = 0 - *View = MsgPackWrapMsgBuffer(*Answer, AnswerSize) - If *View - *Refused = BakaShrot_RequestRefusedPacket_Decode(*View) - MsgPackFree(*View, #False) - EndIf - If *Refused - Reason = "refused: " + *Refused\Reason - FreeStructure(*Refused) - EndIf - EndIf - ProcedureReturn Reason -EndProcedure - - -; Runs a query (or "@latest", a GetLatestMessage of NodeId). -; Returns #True with the time it took in *Ms\d, the answer's size in -; *Bytes\i and the JSON result in *Result\s, or #False with *Error\s set. -; Reconnects as ConnectNode if the connection was lost. -Procedure.i Bench_RunQuery(*Outbound.BakaShrot_Outbound, *Server.BenchServer, ConnectNode.i, Sql.s, NodeId.i, *Ms.Double, *Bytes.Integer, *Result.String, *Error.String) - Protected Request.BakaShrot_QueryRequest, Latest.BakaShrot_GetLatestMessage - Protected *QueryResult.BakaShrot_QueryResult, *LatestMessage.BakaShrot_LatestMessage - Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer, *View.MsgPackData - Protected StartMs.d, Expected.i, Ok.i - - If Not *Outbound\ConnectionId - If Not Bench_Connect(*Outbound, *Server, ConnectNode) - *Error\s = "can't connect" - ProcedureReturn #False - EndIf - EndIf - - If Sql = "@latest" - Latest\Topic = Str(Bench_TopicId) - Latest\Node = Str(NodeId) - *Packet = BakaShrot_GetLatestMessagePacket_Encode(@Latest, @PacketSize) - Expected = #BakaShrot_PacketType_LatestMessage - Else - Request\Sql = Sql - *Packet = BakaShrot_QueryRequestPacket_Encode(@Request, @PacketSize) - Expected = #BakaShrot_PacketType_QueryResult - EndIf - If Not *Packet - *Error\s = "can't encode" - ProcedureReturn #False - EndIf - - StartMs = Bench_NowMs() - *Answer = Bench_Request(*Outbound, *Packet, PacketSize\i, @AnswerSize) - *Ms\d = Bench_NowMs() - StartMs - FreeMemory(*Packet) - - If Not *Answer - BakaShrot_Outbound_Close(*Outbound, #BakaShrot_ConnectionStatus_Aborted) - *Error\s = "connection lost" - ProcedureReturn #False - EndIf - - *Bytes\i = AnswerSize\i - If BakaShrot_GetPacketType(*Answer, AnswerSize\i) <> Expected - *Error\s = Bench_RefusalReason(*Answer, AnswerSize\i) - FreeMemory(*Answer) - ProcedureReturn #False - EndIf - - Ok = #False - *View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i) - If *View - If Expected = #BakaShrot_PacketType_QueryResult - *QueryResult = BakaShrot_QueryResultPacket_Decode(*View) - If *QueryResult - *Result\s = *QueryResult\JsonResult - FreeStructure(*QueryResult) - Ok = #True - EndIf - Else - *LatestMessage = BakaShrot_LatestMessagePacket_Decode(*View) - If *LatestMessage - *Result\s = ~"{\"columns\": [\"message_id\"], \"rows\": [[\"" + Str(*LatestMessage\MessageId) + ~"\"]]}" - FreeStructure(*LatestMessage) - Ok = #True - EndIf - EndIf - MsgPackFree(*View, #False) - EndIf - FreeMemory(*Answer) - - If Not Ok - *Error\s = "can't decode the answer" - EndIf - ProcedureReturn Ok -EndProcedure - - -; Number of rows in a query's JSON result, -1 if it can't be parsed. -Procedure.i Bench_CountRows(Result.s) - Protected JsonId.i, *Rows, Count.i = -1 - - JsonId = ParseJSON(#PB_Any, Result) - If JsonId - *Rows = GetJSONMember(JSONValue(JsonId), "rows") - If *Rows - Count = JSONArraySize(*Rows) - EndIf - FreeJSON(JsonId) - EndIf - ProcedureReturn Count -EndProcedure - - -; Loads the query file into Queries(). -Procedure Bench_LoadQueries(Path.s, List Queries.BenchQueryStats()) - Protected FileId.i, Line.s, Separator.i - - ClearList(Queries()) - If Path = "" - ProcedureReturn - EndIf - FileId = ReadFile(#PB_Any, Path) - If Not FileId - Bench_Fail("Failed to open the query file '" + Path + "'") - EndIf - While Not Eof(FileId) - Line = Trim(ReadString(FileId, #PB_UTF8)) - If Line = "" Or Left(Line, 1) = "#" - Continue - EndIf - Separator = FindString(Line, "|") - If Separator < 2 - Continue - EndIf - AddElement(Queries()) - Queries()\Name = Trim(Left(Line, Separator - 1)) - Queries()\Sql = Trim(Mid(Line, Separator + 1)) - Wend - CloseFile(FileId) -EndProcedure - - -Procedure.s Bench_ExpandSql(Sql.s, *Server.BenchServer) - Sql = ReplaceString(Sql, "{TOPIC}", Str(Bench_TopicId)) - Sql = ReplaceString(Sql, "{NODE}", Str(*Server\FirstNode)) - ProcedureReturn Sql -EndProcedure - - -; --- Pushers ----------------------------------------------------------------- - -Procedure Bench_PusherThread(*Pusher.BenchPusher) - Protected *Server.BenchServer = @Bench_Servers(*Pusher\ServerIndex) - Protected Outbound.BakaShrot_Outbound - Protected Push.BakaShrot_PushMessage - Protected *Request, RequestSize.Integer, *Answer, AnswerSize.Integer - Protected Attempt.i, Seq.q, Kind.s, Pad.s, Json.s, Spread.i, Value.i - Protected IntervalMs.d, NextDueMs.d, NowMs.d, StartMs.d, LatencyMs.d - - For Attempt = 1 To 5 - If Bench_Connect(@Outbound, *Server, *Pusher\NodeId) - Break - EndIf - Delay(200 * Attempt) - Next - If Not Outbound\ConnectionId - *Pusher\ConnectFailed = #True - *Pusher\LastError = "can't connect" - *Pusher\Ready = #True - ProcedureReturn - EndIf - *Pusher\Ready = #True - - ; About MessageSize bytes of JSON, ~90 without the padding. - If Bench_MessageSize > 90 - Pad = LSet("", Bench_MessageSize - 90, "x") - EndIf - - While Not Bench_PushStarted And Not Bench_StopPush - Delay(1) - Wend - - If Bench_Rate > 0 - IntervalMs = 1000.0 / Bench_Rate - ; Spread the nodes' pushes over the interval. - Spread = *Pusher\NodeId % 97 - NextDueMs = Bench_NowMs() + IntervalMs * Spread / 97.0 - EndIf - - While Not Bench_StopPush - If Bench_Rate > 0 - NowMs = Bench_NowMs() - If NowMs < NextDueMs - Delay(1) - Continue - EndIf - NextDueMs + IntervalMs - ; More than a second behind: the server can't keep up, don't - ; build up a backlog to burst later. - If NowMs - NextDueMs > 1000 - NextDueMs = NowMs - EndIf - EndIf - - Seq + 1 - If Seq % 50 = 0 - Kind = "alert" - Else - Select Seq % 4 - Case 0 : Kind = "temp" - Case 1 : Kind = "humidity" - Case 2 : Kind = "pressure" - Default : Kind = "status" - EndSelect - EndIf - Value = (Seq * 7919 + *Pusher\NodeId) % 10000 - Json = ~"{\"kind\":\"" + Kind + ~"\",\"node\":" + Str(*Pusher\NodeId) + ~",\"seq\":" + Str(Seq) + - ~",\"value\":" + StrD(Value / 100.0, 2) + - ~",\"ts\":" + Str(Date()) + ~",\"pad\":\"" + Pad + ~"\"}" - - Push\JsonData = Json - *Request = BakaShrot_PushMessagePacket_Encode(@Push, @RequestSize) - If Not *Request - *Pusher\Failed + 1 - *Pusher\LastError = "can't encode" - Continue - EndIf - - StartMs = Bench_NowMs() - *Answer = Bench_Request(@Outbound, *Request, RequestSize\i, @AnswerSize) - LatencyMs = Bench_NowMs() - StartMs - FreeMemory(*Request) - - If Not *Answer - *Pusher\Failed + 1 - *Pusher\LastError = "connection lost" - BakaShrot_Outbound_Close(@Outbound, #BakaShrot_ConnectionStatus_Aborted) - *Pusher\Reconnects + 1 - If Not Bench_Connect(@Outbound, *Server, *Pusher\NodeId) - Delay(500) - If Not Bench_Connect(@Outbound, *Server, *Pusher\NodeId) - *Pusher\LastError = "connection lost, can't reconnect" - Break - EndIf - EndIf - Continue - EndIf - - If BakaShrot_GetPacketType(*Answer, AnswerSize\i) = #BakaShrot_PacketType_MessagePushed - AddElement(*Pusher\LatencyMs()) - *Pusher\LatencyMs() = LatencyMs - *Pusher\Sent + 1 - Else - *Pusher\Failed + 1 - *Pusher\LastError = Bench_RefusalReason(*Answer, AnswerSize\i) - EndIf - FreeMemory(*Answer) - Wend - - BakaShrot_Outbound_Close(@Outbound, #BakaShrot_ConnectionStatus_Disconnected) -EndProcedure - - -; Runs the query file in a loop against the QueryLoad servers until the push -; ends. -Procedure Bench_QueryLoadThread(Unused.i) - Protected NewList Queries.BenchQueryStats() - Protected Dim Outbounds.BakaShrot_Outbound(Bench_ServerCount - 1) - Protected i.i, Ms.Double, Bytes.Integer, Result.String, Error.String, Sql.s - - While Not Bench_PushStarted And Not Bench_StopPush - Delay(1) - Wend - - While Not Bench_StopPush - ForEach Bench_LoadStats() - For i = 0 To Bench_ServerCount - 1 - If Not Bench_Servers(i)\QueryLoad - Continue - EndIf - If Bench_StopPush - Break 2 - EndIf - Sql = Bench_ExpandSql(Bench_LoadStats()\Sql, @Bench_Servers(i)) - If Bench_RunQuery(@Outbounds(i), @Bench_Servers(i), Bench_Servers(i)\QueryNode, Sql, Bench_Servers(i)\FirstNode, @Ms, @Bytes, @Result, @Error) - AddElement(Bench_LoadStats()\LatencyMs()) - Bench_LoadStats()\LatencyMs() = Ms\d - Else - Bench_LoadStats()\Failures + 1 - Bench_LoadStats()\LastError = Error\s - EndIf - Next - Next - Delay(100) - Wend - - For i = 0 To Bench_ServerCount - 1 - BakaShrot_Outbound_Close(@Outbounds(i), #BakaShrot_ConnectionStatus_Disconnected) - Next -EndProcedure - - -; --- Sampling ---------------------------------------------------------------- - -Procedure.q Bench_ProcessCycles(Process.i) - Protected Cycles.q - If Not Bench_QueryProcessCycleTime(Process, @Cycles) - ProcedureReturn 0 - EndIf - ProcedureReturn Cycles -EndProcedure - - -; Idle cycles of every processor, summed. -Procedure.q Bench_IdleCycles() - Protected Dim Buffer.q(255), Size.l, i.i, Total.q - - Size = 256 * SizeOf(Quad) - If Bench_QueryIdleProcessorCycleTime(@Size, @Buffer(0)) - Bench_CpuCount = Size / SizeOf(Quad) - For i = 0 To Bench_CpuCount - 1 - Total + Buffer(i) - Next - EndIf - ProcedureReturn Total -EndProcedure - - -; How many cycles a busy processor counts per ms: spins a few times for -; 200 ms, keeps the best (the least preempted). -Procedure Bench_CalibrateCycles() - Protected Attempt.i, StartMs.d, NowMs.d, Start.q, Finish.q, Rate.d - - For Attempt = 1 To 3 - Bench_QueryThreadCycleTime(GetCurrentThread_(), @Start) - StartMs = Bench_NowMs() - Repeat - NowMs = Bench_NowMs() - Until NowMs - StartMs >= 200 - Bench_QueryThreadCycleTime(GetCurrentThread_(), @Finish) - Rate = (Finish - Start) / (NowMs - StartMs) - If Rate > Bench_CyclesPerMs - Bench_CyclesPerMs = Rate - EndIf - Next -EndProcedure - - -Procedure Bench_InitSampling() - Protected Kernel32.i, i.i - - Kernel32 = OpenLibrary(#PB_Any, "kernel32.dll") - If Not Kernel32 - Bench_Fail("Can't open kernel32.dll") - EndIf - Bench_QueryProcessCycleTime = GetFunction(Kernel32, "QueryProcessCycleTime") - Bench_QueryThreadCycleTime = GetFunction(Kernel32, "QueryThreadCycleTime") - Bench_QueryIdleProcessorCycleTime = GetFunction(Kernel32, "QueryIdleProcessorCycleTime") - Bench_GetProcessMemoryInfo = GetFunction(Kernel32, "K32GetProcessMemoryInfo") - If Not Bench_QueryProcessCycleTime Or Not Bench_QueryThreadCycleTime Or Not Bench_QueryIdleProcessorCycleTime Or Not Bench_GetProcessMemoryInfo - Bench_Fail("Missing kernel32 functions") - EndIf - - Bench_CalibrateCycles() - Bench_LastIdleCycles = Bench_IdleCycles() - Bench_LastSelfCpu = Bench_ProcessCycles(GetCurrentProcess_()) - - For i = 0 To Bench_ServerCount - 1 - With Bench_Servers(i) - If \Pid - ; PROCESS_QUERY_INFORMATION | PROCESS_VM_READ - \Process = OpenProcess_($0400 | $0010, 0, \Pid) - If \Process - \LastCpu = Bench_ProcessCycles(\Process) - Else - PrintN("[Bench] Can't open the process of '" + \Name + "' (pid " + Str(\Pid) + "), no CPU/RAM for it") - EndIf - EndIf - EndWith - Next - Bench_LastSampleMs = Bench_NowMs() -EndProcedure - - -Procedure Bench_WriteCsvHeader() - Protected Line.s, i.i, Prefix.s - - Bench_CsvFile = CreateFile(#PB_Any, Bench_SamplesCsv) - If Not Bench_CsvFile - Bench_Fail("Can't create '" + Bench_SamplesCsv + "'") - EndIf - Line = "t_s,phase,pushed,push_rate,system_cpu,bench_cpu" - For i = 0 To Bench_ServerCount - 1 - Prefix = Bench_Servers(i)\Name + "_" - Line + "," + Prefix + "present," + Prefix + "lag," + Prefix + "cpu," + Prefix + "ws_mb," + Prefix + "private_mb," + Prefix + "db_mb," + Prefix + "monitor_ms" - Next - WriteStringN(Bench_CsvFile, Line) -EndProcedure - - -Procedure.q Bench_TotalPushed() - Protected i.i, Total.q - For i = 0 To Bench_PusherCount - 1 - Total + Bench_Pushers(i)\Sent - Next - ProcedureReturn Total -EndProcedure - - -; Phase: "push", "push-end" or "drain". Returns the total lag of every server. -Procedure.q Bench_Sample(Phase.s) - Protected NowMs.d, ElapsedS.d, IntervalMs.d, i.i, n.i - Protected Idle.q, Cpu.q, BusyCycles.d - Protected Counters.BenchMemoryCounters - Protected Ms.Double, Bytes.Integer, Result.String, Error.String - Protected JsonId.i, *Row, *Value, Expected.q, TotalLag.q, Pushed.q, PushRate.d, Line.s - - NowMs = Bench_NowMs() - IntervalMs = NowMs - Bench_LastSampleMs - If IntervalMs < 1 - IntervalMs = 1 - EndIf - Bench_LastSampleMs = NowMs - ElapsedS = (NowMs - Bench_StartMs) / 1000.0 - - ; Machine and self CPU - ; Cycles a fully busy processor would have counted meanwhile. - BusyCycles = Bench_CyclesPerMs * IntervalMs - Idle = Bench_IdleCycles() - If Bench_CpuCount > 0 - Bench_SystemCpu = 100.0 * (1.0 - (Idle - Bench_LastIdleCycles) / (BusyCycles * Bench_CpuCount)) - If Bench_SystemCpu < 0 - Bench_SystemCpu = 0 - EndIf - EndIf - Bench_LastIdleCycles = Idle - Cpu = Bench_ProcessCycles(GetCurrentProcess_()) - Bench_SelfCpu = 100.0 * (Cpu - Bench_LastSelfCpu) / BusyCycles - Bench_LastSelfCpu = Cpu - - For i = 0 To Bench_ServerCount - 1 - With Bench_Servers(i) - If \Process - Cpu = Bench_ProcessCycles(\Process) - \CpuPercent = 100.0 * (Cpu - \LastCpu) / BusyCycles - \LastCpu = Cpu - Counters\cb = SizeOf(BenchMemoryCounters) - If Bench_GetProcessMemoryInfo(\Process, @Counters, SizeOf(BenchMemoryCounters)) - \WorkingSetMb = Counters\WorkingSetSize / 1048576.0 - \PrivateMb = Counters\PagefileUsage / 1048576.0 - EndIf - EndIf - If \DatabasePath <> "" - \DbMb = FileSize(\DatabasePath) / 1048576.0 - EndIf - - ; How many messages of every node it has. - If Bench_RunQuery(@\Monitor, @Bench_Servers(i), \MonitorNode, Bench_MonitorSql, 0, @Ms, @Bytes, @Result, @Error) - \MonitorMs = Ms\d - \MonitorSumMs + Ms\d - \MonitorCount + 1 - If Ms\d > \MonitorMaxMs - \MonitorMaxMs = Ms\d - EndIf - JsonId = ParseJSON(#PB_Any, Result\s) - If JsonId - *Row = GetJSONElement(GetJSONMember(JSONValue(JsonId), "rows"), 0) - If *Row - For n = 0 To Bench_NodeCount - 1 - *Value = GetJSONElement(*Row, n) - If *Value And JSONType(*Value) = #PB_JSON_String - Bench_Present(i, n) = Val(GetJSONString(*Value)) - EndIf - Next - EndIf - FreeJSON(JsonId) - EndIf - Else - \MonitorMs = -1 - \MonitorFailures + 1 - PrintN("[Bench] Monitor query on '" + \Name + "' failed: " + Error\s) - EndIf - EndWith - Next - - ; A node's messages are only pushed to its own server, so whoever has the - ; most has all of them so far. - For i = 0 To Bench_ServerCount - 1 - Bench_Servers(i)\Present = 0 - Bench_Servers(i)\Lag = 0 - Next - For n = 0 To Bench_NodeCount - 1 - Expected = 0 - For i = 0 To Bench_ServerCount - 1 - If Bench_Present(i, n) > Expected - Expected = Bench_Present(i, n) - EndIf - Next - For i = 0 To Bench_ServerCount - 1 - Bench_Servers(i)\Present + Bench_Present(i, n) - Bench_Servers(i)\Lag + Expected - Bench_Present(i, n) - Next - Next - - Pushed = Bench_TotalPushed() - PushRate = (Pushed - Bench_LastPushed) * 1000.0 / IntervalMs - Bench_LastPushed = Pushed - - ; Stats - If Phase = "push" - Bench_SystemCpuSum + Bench_SystemCpu - Bench_SystemCpuCount + 1 - If Bench_SystemCpu > Bench_SystemCpuMax - Bench_SystemCpuMax = Bench_SystemCpu - EndIf - Bench_SelfCpuSum + Bench_SelfCpu - Bench_SelfCpuCount + 1 - EndIf - For i = 0 To Bench_ServerCount - 1 - With Bench_Servers(i) - TotalLag + \Lag - If \WorkingSetMb > \WorkingSetMaxMb - \WorkingSetMaxMb = \WorkingSetMb - EndIf - If \PrivateMb > \PrivateMaxMb - \PrivateMaxMb = \PrivateMb - EndIf - If Phase = "push" - \CpuSumPush + \CpuPercent - \CpuCountPush + 1 - If \CpuPercent > \CpuMaxPush - \CpuMaxPush = \CpuPercent - EndIf - If \Lag > \LagMaxPush - \LagMaxPush = \Lag - EndIf - AddElement(\PushLag()) - \PushLag()\T = ElapsedS - \PushLag()\Lag = \Lag - ElseIf Phase = "push-end" - \LagAtPushEnd = \Lag - If \Lag > \LagMaxPush - \LagMaxPush = \Lag - EndIf - Else - \CpuSumDrain + \CpuPercent - \CpuCountDrain + 1 - If \CpuPercent > \CpuMaxDrain - \CpuMaxDrain = \CpuPercent - EndIf - EndIf - EndWith - Next - - Line = StrD(ElapsedS, 3) + "," + Phase + "," + Str(Pushed) + "," + StrD(PushRate, 1) + "," + StrD(Bench_SystemCpu, 1) + "," + StrD(Bench_SelfCpu, 1) - For i = 0 To Bench_ServerCount - 1 - With Bench_Servers(i) - Line + "," + Str(\Present) + "," + Str(\Lag) + "," + StrD(\CpuPercent, 1) + "," + StrD(\WorkingSetMb, 1) + "," + StrD(\PrivateMb, 1) + "," + StrD(\DbMb, 2) + "," + StrD(\MonitorMs, 1) - EndWith - Next - WriteStringN(Bench_CsvFile, Line) - - ProcedureReturn TotalLag -EndProcedure - - -; --- Stats helpers ----------------------------------------------------------- - -; Fills Sorted() from Values() and sorts it. -Procedure Bench_Sorted(List Values.f(), Array Sorted.f(1)) - Protected n.i - - If ListSize(Values()) = 0 - Dim Sorted.f(0) - ProcedureReturn - EndIf - Dim Sorted.f(ListSize(Values()) - 1) - ForEach Values() - Sorted(n) = Values() - n + 1 - Next - SortArray(Sorted(), #PB_Sort_Ascending) -EndProcedure - -Procedure.d Bench_Percentile(Array Sorted.f(1), Count.i, P.d) - If Count = 0 - ProcedureReturn 0 - EndIf - ProcedureReturn Sorted(Int((Count - 1) * P)) -EndProcedure - -Procedure.d Bench_Average(Array Sorted.f(1), Count.i) - Protected i.i, Sum.d - If Count = 0 - ProcedureReturn 0 - EndIf - For i = 0 To Count - 1 - Sum + Sorted(i) - Next - ProcedureReturn Sum / Count -EndProcedure - -Procedure Bench_AddLatencyStats(*Object, Prefix.s, List Values.f()) - Protected Dim Sorted.f(0), Count.i = ListSize(Values()) - - Bench_Sorted(Values(), Sorted()) - SetJSONInteger(AddJSONMember(*Object, Prefix + "Count"), Count) - SetJSONDouble(AddJSONMember(*Object, Prefix + "AvgMs"), Bench_Average(Sorted(), Count)) - SetJSONDouble(AddJSONMember(*Object, Prefix + "P50Ms"), Bench_Percentile(Sorted(), Count, 0.50)) - SetJSONDouble(AddJSONMember(*Object, Prefix + "P90Ms"), Bench_Percentile(Sorted(), Count, 0.90)) - SetJSONDouble(AddJSONMember(*Object, Prefix + "P99Ms"), Bench_Percentile(Sorted(), Count, 0.99)) - If Count > 0 - SetJSONDouble(AddJSONMember(*Object, Prefix + "MaxMs"), Sorted(Count - 1)) - SetJSONDouble(AddJSONMember(*Object, Prefix + "MinMs"), Sorted(0)) - Else - SetJSONDouble(AddJSONMember(*Object, Prefix + "MaxMs"), 0) - SetJSONDouble(AddJSONMember(*Object, Prefix + "MinMs"), 0) - EndIf -EndProcedure - - -; Replication catches up in bursts, once per check-in (every PeerSyncInterval -; plus the catch-up's own time), and a message pushed to a leaf needs two -; check-ins to reach the other leaves through the hub, so the lag is a -; sawtooth. Whether it keeps up shows in its troughs: the lowest lag of every -; window of two check-ins. Returns how fast they rise, in messages per second -; (~0 keeps up, > 0 falls further behind every check-in), and the last full -; window's trough in *LastTrough\q. Needs a push of 3+ windows to mean much. -Procedure.d Bench_TroughSlope(List Samples.BenchLagSample(), *LastTrough.Quad) - Protected Window.d, Index.i, LastIndex.i, n.d, SumT.d, SumL.d, SumTT.d, SumTL.d, Denominator.d - Protected NewMap Troughs.q(), NewMap Centers.d() - - *LastTrough\q = 0 - Window = 2 * Bench_SyncInterval - If Window <= 0 - Window = 10 - EndIf - - LastIndex = -1 - ForEach Samples() - Index = Int(Samples()\T / Window) - If Not FindMapElement(Troughs(), Str(Index)) Or Samples()\Lag < Troughs(Str(Index)) - Troughs(Str(Index)) = Samples()\Lag - EndIf - Centers(Str(Index)) = (Index + 0.5) * Window - If Index > LastIndex - LastIndex = Index - EndIf - Next - - ; The last window is usually cut short by the end of the push. - ForEach Troughs() - If Val(MapKey(Troughs())) = LastIndex And MapSize(Troughs()) > 1 - Continue - EndIf - n + 1 - SumT + Centers(MapKey(Troughs())) - SumL + Troughs() - SumTT + Centers(MapKey(Troughs())) * Centers(MapKey(Troughs())) - SumTL + Centers(MapKey(Troughs())) * Troughs() - If Val(MapKey(Troughs())) = LastIndex - 1 Or MapSize(Troughs()) = 1 - *LastTrough\q = Troughs() - EndIf - Next - - Denominator = n * SumTT - SumT * SumT - If n < 2 Or Denominator = 0 - ProcedureReturn 0 - EndIf - ProcedureReturn (n * SumTL - SumT * SumL) / Denominator -EndProcedure - - -; --- run --------------------------------------------------------------------- - -Procedure Bench_Run() - Protected i.i, n.i, Node.i, NextSampleMs.d, PushEndMs.d, DrainMs.d, TotalLag.q - Protected QueryThread.i, Connected.i, ConnectFailures.i, Pushed.q, Failed.q, Reconnects.i - Protected JsonId.i, *Root, *Servers, *Server, *Queries, *Query, *Errors - Protected NewList AllLatencies.f(), NewMap Errors.i() - Protected PushMs.d, PushRate.d, Trough.Quad - - ; Everyone's identity in place, nothing pushing yet. - Bench_InitSampling() - Bench_WriteCsvHeader() - - For i = 0 To Bench_ServerCount - 1 - If Not Bench_Connect(@Bench_Servers(i)\Monitor, @Bench_Servers(i), Bench_Servers(i)\MonitorNode) - Bench_Fail("Can't connect the monitor to '" + Bench_Servers(i)\Name + "'") - EndIf - Next - - Bench_PusherCount = 0 - For i = 0 To Bench_ServerCount - 1 - Bench_PusherCount + Bench_Servers(i)\NodeCount - Next - If Bench_PusherCount > 0 - Dim Bench_Pushers.BenchPusher(Bench_PusherCount - 1) - EndIf - n = 0 - For i = 0 To Bench_ServerCount - 1 - For Node = Bench_Servers(i)\FirstNode To Bench_Servers(i)\FirstNode + Bench_Servers(i)\NodeCount - 1 - Bench_Pushers(n)\ServerIndex = i - Bench_Pushers(n)\NodeId = Node - Bench_Pushers(n)\ThreadId = CreateThread(@Bench_PusherThread(), @Bench_Pushers(n)) - If Not Bench_Pushers(n)\ThreadId - Bench_Fail("Can't start a pusher thread") - EndIf - n + 1 - Next - Next - - Bench_LoadQueries(Bench_QueryFile, Bench_LoadStats()) - If ListSize(Bench_LoadStats()) > 0 - For i = 0 To Bench_ServerCount - 1 - If Bench_Servers(i)\QueryLoad - QueryThread = CreateThread(@Bench_QueryLoadThread(), 0) - Break - EndIf - Next - EndIf - - ; Wait for every pusher to be connected. - Repeat - Connected = 0 - For i = 0 To Bench_PusherCount - 1 - If Bench_Pushers(i)\Ready - Connected + 1 - EndIf - Next - If Connected = Bench_PusherCount - Break - EndIf - Delay(10) - ForEver - For i = 0 To Bench_PusherCount - 1 - If Bench_Pushers(i)\ConnectFailed - ConnectFailures + 1 - EndIf - Next - PrintN("[Bench] " + Str(Bench_PusherCount - ConnectFailures) + "/" + Str(Bench_PusherCount) + " pushers connected, pushing for " + Str(Bench_PushSeconds) + " s at " + StrD(Bench_Rate, 1) + " msg/s each") - - ; Baseline, then go. - Bench_StartMs = Bench_NowMs() - Bench_Sample("start") - For i = 0 To Bench_ServerCount - 1 - Bench_Servers(i)\PresentAtPushStart = Bench_Servers(i)\Present - Next - Bench_StartMs = Bench_NowMs() - Bench_LastPushed = 0 - Bench_PushStarted = #True - - NextSampleMs = Bench_StartMs + Bench_SampleMs - While Bench_NowMs() - Bench_StartMs < Bench_PushSeconds * 1000.0 - If Bench_NowMs() >= NextSampleMs - Bench_Sample("push") - NextSampleMs + Bench_SampleMs - EndIf - Delay(5) - Wend - Bench_StopPush = #True - PushEndMs = Bench_NowMs() - For i = 0 To Bench_PusherCount - 1 - If Bench_Pushers(i)\ThreadId - WaitThread(Bench_Pushers(i)\ThreadId) - EndIf - Next - If QueryThread - WaitThread(QueryThread) - EndIf - PushMs = Bench_NowMs() - Bench_StartMs - Pushed = Bench_TotalPushed() - PushRate = Pushed * 1000.0 / PushMs - PrintN("[Bench] Pushed " + Str(Pushed) + " in " + StrD(PushMs / 1000.0, 1) + " s (" + StrD(PushRate, 1) + " msg/s), draining") - - ; Drain - TotalLag = Bench_Sample("push-end") - DrainMs = -1 - If TotalLag = 0 - DrainMs = Bench_NowMs() - PushEndMs - Else - NextSampleMs = Bench_NowMs() + Bench_DrainSampleMs - While Bench_NowMs() - PushEndMs < Bench_DrainTimeout * 1000.0 - If Bench_NowMs() >= NextSampleMs - TotalLag = Bench_Sample("drain") - If TotalLag = 0 - DrainMs = Bench_NowMs() - PushEndMs - Break - EndIf - NextSampleMs + Bench_DrainSampleMs - EndIf - Delay(5) - Wend - EndIf - CloseFile(Bench_CsvFile) - - If DrainMs >= 0 - PrintN("[Bench] Drained in " + StrD(DrainMs / 1000.0, 2) + " s") - Else - PrintN("[Bench] NOT drained after " + Str(Bench_DrainTimeout) + " s, " + Str(TotalLag) + " messages still missing") - EndIf - - ; Summary - For i = 0 To Bench_PusherCount - 1 - Failed + Bench_Pushers(i)\Failed - Reconnects + Bench_Pushers(i)\Reconnects - ForEach Bench_Pushers(i)\LatencyMs() - AddElement(AllLatencies()) - AllLatencies() = Bench_Pushers(i)\LatencyMs() - Next - If Bench_Pushers(i)\LastError <> "" - Errors(Bench_Pushers(i)\LastError) + 1 - EndIf - Next - - JsonId = CreateJSON(#PB_Any) - *Root = SetJSONObject(JSONValue(JsonId)) - SetJSONDouble(AddJSONMember(*Root, "Rate"), Bench_Rate) - SetJSONInteger(AddJSONMember(*Root, "Pushers"), Bench_PusherCount) - SetJSONInteger(AddJSONMember(*Root, "ConnectFailures"), ConnectFailures) - SetJSONInteger(AddJSONMember(*Root, "MessageSize"), Bench_MessageSize) - SetJSONDouble(AddJSONMember(*Root, "PushSeconds"), PushMs / 1000.0) - SetJSONDouble(AddJSONMember(*Root, "OfferedRate"), Bench_Rate * Bench_PusherCount) - SetJSONInteger(AddJSONMember(*Root, "Pushed"), Pushed) - SetJSONInteger(AddJSONMember(*Root, "Failed"), Failed) - SetJSONInteger(AddJSONMember(*Root, "Reconnects"), Reconnects) - SetJSONDouble(AddJSONMember(*Root, "PushRate"), PushRate) - Bench_AddLatencyStats(*Root, "Push", AllLatencies()) - SetJSONDouble(AddJSONMember(*Root, "DrainSeconds"), DrainMs / 1000.0) - SetJSONBoolean(AddJSONMember(*Root, "Drained"), Bool(DrainMs >= 0)) - SetJSONInteger(AddJSONMember(*Root, "LagAtTimeout"), TotalLag) - SetJSONInteger(AddJSONMember(*Root, "CpuCount"), Bench_CpuCount) - SetJSONDouble(AddJSONMember(*Root, "CyclesPerMs"), Bench_CyclesPerMs) - If Bench_SystemCpuCount > 0 - SetJSONDouble(AddJSONMember(*Root, "SystemCpuAvg"), Bench_SystemCpuSum / Bench_SystemCpuCount) - SetJSONDouble(AddJSONMember(*Root, "BenchCpuAvg"), Bench_SelfCpuSum / Bench_SelfCpuCount) - Else - SetJSONDouble(AddJSONMember(*Root, "SystemCpuAvg"), 0) - SetJSONDouble(AddJSONMember(*Root, "BenchCpuAvg"), 0) - EndIf - SetJSONDouble(AddJSONMember(*Root, "SystemCpuMax"), Bench_SystemCpuMax) - - *Errors = SetJSONObject(AddJSONMember(*Root, "Errors")) - ForEach Errors() - SetJSONInteger(AddJSONMember(*Errors, MapKey(Errors())), Errors()) - Next - - *Servers = SetJSONArray(AddJSONMember(*Root, "Servers")) - For i = 0 To Bench_ServerCount - 1 - With Bench_Servers(i) - *Server = SetJSONObject(AddJSONElement(*Servers)) - SetJSONString(AddJSONMember(*Server, "Name"), \Name) - SetJSONInteger(AddJSONMember(*Server, "Nodes"), \NodeCount) - SetJSONInteger(AddJSONMember(*Server, "Rows"), \Present) - SetJSONDouble(AddJSONMember(*Server, "ReceiveRate"), (\Present - \PresentAtPushStart) * 1000.0 / PushMs) - If \CpuCountPush > 0 - SetJSONDouble(AddJSONMember(*Server, "CpuAvgPush"), \CpuSumPush / \CpuCountPush) - Else - SetJSONDouble(AddJSONMember(*Server, "CpuAvgPush"), 0) - EndIf - SetJSONDouble(AddJSONMember(*Server, "CpuMaxPush"), \CpuMaxPush) - If \CpuCountDrain > 0 - SetJSONDouble(AddJSONMember(*Server, "CpuAvgDrain"), \CpuSumDrain / \CpuCountDrain) - Else - SetJSONDouble(AddJSONMember(*Server, "CpuAvgDrain"), 0) - EndIf - SetJSONDouble(AddJSONMember(*Server, "WorkingSetMaxMb"), \WorkingSetMaxMb) - SetJSONDouble(AddJSONMember(*Server, "PrivateMaxMb"), \PrivateMaxMb) - SetJSONDouble(AddJSONMember(*Server, "DbMb"), \DbMb) - SetJSONInteger(AddJSONMember(*Server, "LagMaxPush"), \LagMaxPush) - ; How many seconds of pushes that was. - If PushRate > 0 - SetJSONDouble(AddJSONMember(*Server, "LagMaxSeconds"), \LagMaxPush / PushRate) - Else - SetJSONDouble(AddJSONMember(*Server, "LagMaxSeconds"), 0) - EndIf - SetJSONInteger(AddJSONMember(*Server, "LagAtPushEnd"), \LagAtPushEnd) - ; Messages per second it falls further behind, over the push's - ; second half. ~0 keeps up, > 0 doesn't. - SetJSONDouble(AddJSONMember(*Server, "LagSlope"), Bench_TroughSlope(\PushLag(), @Trough)) - SetJSONInteger(AddJSONMember(*Server, "LagTroughLast"), Trough\q) - If \MonitorCount > 0 - SetJSONDouble(AddJSONMember(*Server, "MonitorAvgMs"), \MonitorSumMs / \MonitorCount) - Else - SetJSONDouble(AddJSONMember(*Server, "MonitorAvgMs"), 0) - EndIf - SetJSONDouble(AddJSONMember(*Server, "MonitorMaxMs"), \MonitorMaxMs) - SetJSONInteger(AddJSONMember(*Server, "MonitorFailures"), \MonitorFailures) - EndWith - Next - - *Queries = SetJSONArray(AddJSONMember(*Root, "QueriesUnderLoad")) - ForEach Bench_LoadStats() - *Query = SetJSONObject(AddJSONElement(*Queries)) - SetJSONString(AddJSONMember(*Query, "Name"), Bench_LoadStats()\Name) - Bench_AddLatencyStats(*Query, "", Bench_LoadStats()\LatencyMs()) - SetJSONInteger(AddJSONMember(*Query, "Failures"), Bench_LoadStats()\Failures) - SetJSONString(AddJSONMember(*Query, "LastError"), Bench_LoadStats()\LastError) - Next - - If Not SaveJSON(JsonId, Bench_SummaryOut, #PB_JSON_PrettyPrint) - Bench_Fail("Can't write '" + Bench_SummaryOut + "'") - EndIf - FreeJSON(JsonId) - - For i = 0 To Bench_ServerCount - 1 - BakaShrot_Outbound_Close(@Bench_Servers(i)\Monitor, #BakaShrot_ConnectionStatus_Disconnected) - If Bench_Servers(i)\Process - CloseHandle_(Bench_Servers(i)\Process) - EndIf - Next -EndProcedure - - -; --- query ------------------------------------------------------------------- - -Procedure Bench_Query() - Protected NewList Queries.BenchQueryStats() - Protected i.i, r.i, Sql.s, Ms.Double, Bytes.Integer, Result.String, Error.String, Ok.i, Rows.i - Protected JsonId.i, *Root, *Entry, LastBytes.i - - Bench_LoadQueries(Bench_QueryFile, Queries()) - If ListSize(Queries()) = 0 - Bench_Fail("No queries in '" + Bench_QueryFile + "'") - EndIf - - JsonId = CreateJSON(#PB_Any) - *Root = SetJSONArray(JSONValue(JsonId)) - - For i = 0 To Bench_ServerCount - 1 - With Bench_Servers(i) - If Not \Query - Continue - EndIf - ForEach Queries() - ClearList(Queries()\LatencyMs()) - Queries()\Failures = 0 - Queries()\LastError = "" - Rows = -1 - LastBytes = 0 - Sql = Bench_ExpandSql(Queries()\Sql, @Bench_Servers(i)) - - ; Warm-up, also gives the row count. - Ok = Bench_RunQuery(@\Monitor, @Bench_Servers(i), \QueryNode, Sql, \FirstNode, @Ms, @Bytes, @Result, @Error) - If Ok - Rows = Bench_CountRows(Result\s) - LastBytes = Bytes\i - For r = 1 To Bench_QueryRepeats - If Bench_RunQuery(@\Monitor, @Bench_Servers(i), \QueryNode, Sql, \FirstNode, @Ms, @Bytes, @Result, @Error) - AddElement(Queries()\LatencyMs()) - Queries()\LatencyMs() = Ms\d - Else - Queries()\Failures + 1 - Queries()\LastError = Error\s - EndIf - Next - Else - Queries()\Failures + 1 - Queries()\LastError = Error\s - EndIf - - *Entry = SetJSONObject(AddJSONElement(*Root)) - SetJSONString(AddJSONMember(*Entry, "Server"), \Name) - SetJSONString(AddJSONMember(*Entry, "Name"), Queries()\Name) - Bench_AddLatencyStats(*Entry, "", Queries()\LatencyMs()) - SetJSONInteger(AddJSONMember(*Entry, "Rows"), Rows) - SetJSONInteger(AddJSONMember(*Entry, "Bytes"), LastBytes) - SetJSONInteger(AddJSONMember(*Entry, "Failures"), Queries()\Failures) - SetJSONString(AddJSONMember(*Entry, "LastError"), Queries()\LastError) - If ListSize(Queries()\LatencyMs()) > 0 - LastElement(Queries()\LatencyMs()) - PrintN("[Bench] " + \Name + " " + Queries()\Name + ": " + StrD(Queries()\LatencyMs(), 1) + " ms (last), " + Str(Rows) + " rows") - Else - PrintN("[Bench] " + \Name + " " + Queries()\Name + ": FAILED " + Queries()\LastError) - EndIf - Next - BakaShrot_Outbound_Close(@\Monitor, #BakaShrot_ConnectionStatus_Disconnected) - EndWith - Next - - If Not SaveJSON(JsonId, Bench_QueryOut, #PB_JSON_PrettyPrint) - Bench_Fail("Can't write '" + Bench_QueryOut + "'") - EndIf - FreeJSON(JsonId) -EndProcedure - - -; --- Main -------------------------------------------------------------------- - -Define Mode.s - -OpenConsole() - -If CountProgramParameters() < 2 - PrintN("Usage: BenchClient ") - End 1 -EndIf -Mode = LCase(ProgramParameter(0)) - -QueryPerformanceFrequency_(@Bench_QpcFrequency) -; Delay(1) closer to 1 ms, for the pacing. -timeBeginPeriod_(1) - -CompilerIf #PB_Compiler_Version < 600 - InitNetwork() -CompilerEndIf -If Not InitCryptography() - Bench_Fail("Can't initialize libsodium") -EndIf - -Bench_LoadPlan(ProgramParameter(1)) - -Select Mode - Case "run" - Bench_Run() - Case "query" - Bench_Query() - Default - Bench_Fail("Unknown mode '" + Mode + "'") -EndSelect - -timeEndPeriod_(1) -End 0 diff --git a/Tests/Bench/BenchSeed.pb b/Tests/Bench/BenchSeed.pb deleted file mode 100644 index 9264fd7..0000000 --- a/Tests/Bench/BenchSeed.pb +++ /dev/null @@ -1,198 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: BenchSeed.pb -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; BakaShrot Bench Seed -; -; Usage: BenchSeed [Db...] -; Nodes Node ids, "101-110,201-210". -; -; Adds RowsPerNode messages to every node, identical in every database, so -; servers that were in sync stay in sync without replicating anything: a -; quick way to get millions of rows for the query and check-in benchmarks. -; Each node continues from the highest message id any database has for it, -; and INSERT OR IGNORE keeps what's already there. -; Nodes go by name ("n" + id, like Bench-Replication.ps1 names them): each -; database stores a node under its own id for that name, and gets the name -; (origin "peer", as if a peer had sent it) if it doesn't have it yet, so -; servers that take nodes by wildcard (-Names Wildcard) see them as known. -; The servers must be stopped. Same JSON as BenchClient's pushes. -; -; Used by Tests/Bench/Bench-Replication.ps1, compile as a console program. -; ============================================================================ - -EnableExplicit - -XIncludeFile "../../Server/Storage/Storage.pbi" - - -#Seed_BatchSize = 50000 - - -; The id DbId has for node "n", given that name if it has none yet. -; Returns -1 on failure. -Procedure.i Seed_LocalNode(DbId.i, Node.i) - Protected Name.s = "n" + Str(Node), Id.i = -1 - - SetDatabaseString(DbId, 0, Name) - If DatabaseQuery(DbId, "SELECT node_id FROM nodes WHERE name = ?") - If NextDatabaseRow(DbId) - Id = GetDatabaseLong(DbId, 0) - EndIf - FinishDatabaseQuery(DbId) - EndIf - If Id >= 0 - ProcedureReturn Id - EndIf - - ; Its own id, unless something else is named there. - SetDatabaseLong(DbId, 0, Node) - SetDatabaseString(DbId, 1, Name) - If Not DatabaseUpdate(DbId, "INSERT INTO nodes (node_id, name, origin) VALUES (?, ?, 'peer') " + - "ON CONFLICT (node_id) DO UPDATE SET name = excluded.name, origin = 'peer' WHERE origin = 'id'") - ProcedureReturn -1 - EndIf - SetDatabaseString(DbId, 0, Name) - If DatabaseQuery(DbId, "SELECT node_id FROM nodes WHERE name = ?") - If NextDatabaseRow(DbId) - Id = GetDatabaseLong(DbId, 0) - EndIf - FinishDatabaseQuery(DbId) - EndIf - ProcedureReturn Id -EndProcedure - - -Procedure.s Seed_Json(NodeId.i, Seq.q, Pad.s) - Protected Kind.s, Value.i - - If Seq % 50 = 0 - Kind = "alert" - Else - Select Seq % 4 - Case 0 : Kind = "temp" - Case 1 : Kind = "humidity" - Case 2 : Kind = "pressure" - Default : Kind = "status" - EndSelect - EndIf - Value = (Seq * 7919 + NodeId) % 10000 - ProcedureReturn ~"{\"kind\":\"" + Kind + ~"\",\"node\":" + Str(NodeId) + ~",\"seq\":" + Str(Seq) + - ~",\"value\":" + StrD(Value / 100.0, 2) + ~",\"ts\":" + Str(1700000000 + Seq) + - ~",\"pad\":\"" + Pad + ~"\"}" -EndProcedure - - -Define TopicId.i, NodesSpec.s, RowsPerNode.i, MessageSize.i, Pad.s -Define NewList Nodes.i(), NewList Dbs.i() -Define i.i, Part.s, First.i, Last.i, Node.i, StartId.q, Id.q, MaxId.q, Count.q, StartMs.i, Total.q, d.i -Define Dim LocalIds.i(0) - -OpenConsole() - -If CountProgramParameters() < 5 - PrintN("Usage: BenchSeed [Db...]") - End 1 -EndIf - -TopicId = Val(ProgramParameter(0)) -NodesSpec = ProgramParameter(1) -RowsPerNode = Val(ProgramParameter(2)) -MessageSize = Val(ProgramParameter(3)) -If MessageSize > 90 - Pad = LSet("", MessageSize - 90, "x") -EndIf - -For i = 1 To CountString(NodesSpec, ",") + 1 - Part = Trim(StringField(NodesSpec, i, ",")) - If Part = "" - Continue - EndIf - If FindString(Part, "-") - First = Val(StringField(Part, 1, "-")) - Last = Val(StringField(Part, 2, "-")) - Else - First = Val(Part) - Last = First - EndIf - For Node = First To Last - AddElement(Nodes()) - Nodes() = Node - Next -Next - -For i = 4 To CountProgramParameters() - 1 - AddElement(Dbs()) - Dbs() = OpenStorageDatabase(ProgramParameter(i)) - If Not Dbs() Or Not SetupStorageDatabase(Dbs()) - PrintN("Can't open '" + ProgramParameter(i) + "': " + DatabaseError()) - End 1 - EndIf -Next - -StartMs = ElapsedMilliseconds() -ReDim LocalIds(ListSize(Dbs()) - 1) -ForEach Nodes() - ; Where every database is at for this node, continue after the furthest. - StartId = 0 - d = 0 - ForEach Dbs() - LocalIds(d) = Seed_LocalNode(Dbs(), Nodes()) - If LocalIds(d) < 0 - PrintN("Can't name node " + Str(Nodes()) + ": " + DatabaseError()) - End 1 - EndIf - MaxId = GetLatestMessageId(Dbs(), TopicId, LocalIds(d)) - If MaxId > StartId - StartId = MaxId - EndIf - d + 1 - Next - - d = -1 - ForEach Dbs() - d + 1 - Id = StartId - While Id < StartId + RowsPerNode - If Not DatabaseUpdate(Dbs(), "BEGIN IMMEDIATE") - PrintN("BEGIN failed: " + DatabaseError()) - End 1 - EndIf - Count = 0 - While Count < #Seed_BatchSize And Id < StartId + RowsPerNode - Id + 1 - Count + 1 - If Not InsertReplicatedMessage(Dbs(), TopicId, LocalIds(d), Id, Seed_Json(Nodes(), Id, Pad), BakaShrot_NowUtcMs()) - PrintN("Insert failed: " + DatabaseError()) - End 1 - EndIf - Wend - If Not DatabaseUpdate(Dbs(), "COMMIT") - PrintN("COMMIT failed: " + DatabaseError()) - End 1 - EndIf - Total + Count - Wend - Next -Next - -ForEach Dbs() - CloseDatabase(Dbs()) -Next - -PrintN("Seeded " + Str(Total) + " rows (" + Str(RowsPerNode) + " per node, " + Str(ListSize(Nodes())) + " nodes, " + Str(ListSize(Dbs())) + " databases) in " + StrD((ElapsedMilliseconds() - StartMs) / 1000.0, 1) + " s") -End 0 diff --git a/Tests/Bench/BenchServer.pb b/Tests/Bench/BenchServer.pb deleted file mode 100644 index f6b17c8..0000000 --- a/Tests/Bench/BenchServer.pb +++ /dev/null @@ -1,75 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: BenchServer.pb -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; BakaShrot Bench Server -; -; Usage: BenchServer -; -; The real server (Server/Root.pbi), without the console commands: it runs -; until StopFile exists, then stops its workers cleanly and exits. -; BakaShrot_Server.exe can't run headless, with no console input its -; Input() returns Chr(4) and it stops right away, see Notes.md. -; -; Used by Tests/Bench/Bench-Replication.ps1, compile as a thread-safe console -; program. -; ============================================================================ - -EnableExplicit - -XIncludeFile "../../Server/Root.pbi" - - -Define Root.BakaShrot_Root -Define StopFile.s - -OpenConsole("BakaShrot Bench Server") - -If CountProgramParameters() < 2 - PrintN("Usage: BenchServer ") - End 1 -EndIf - -Root\ConfigPath = ProgramParameter(0) -StopFile = ProgramParameter(1) - -If Not BakaShrot_Root_LoadConfig(@Root) - End 1 -EndIf - -If Not BakaShrot_Root_OpenDatabase(@Root) - FreeConfig(Root\Config) - End 1 -EndIf - -If Not BakaShrot_Root_StartWorkers(@Root) - BakaShrot_Root_CloseDatabase(@Root) - FreeConfig(Root\Config) - End 1 -EndIf - -PrintN("Running until '" + StopFile + "' exists.") - -While FileSize(StopFile) < 0 - Delay(200) -Wend - -PrintN("Stopping...") -BakaShrot_Root_StopWorkers(@Root) -BakaShrot_Root_CloseDatabase(@Root) -FreeConfig(Root\Config) -End 0 diff --git a/Tests/Bench/Compare-Runs.ps1 b/Tests/Bench/Compare-Runs.ps1 deleted file mode 100644 index 54672b2..0000000 --- a/Tests/Bench/Compare-Runs.ps1 +++ /dev/null @@ -1,106 +0,0 @@ -# ============================================================================ -# Compares runs of Bench-Replication.ps1 side by side, as a markdown table. -# -# Usage: -# powershell -ExecutionPolicy Bypass -File Tests\Bench\Compare-Runs.ps1 ` -# -Runs "Build\Bench\runs\20261107-123413,Build\Bench\runs\20261107-125334" ` -# -Labels "Before,WAL + wake-ups" [-Out comparison.md] -# -# Picks the key numbers of each run's results.json: the push ceilings, the -# latencies, replication lag and drain, CPU and RAM, the queries at the -# biggest data size, and the mixed stage. Stages missing from a run show "-". -# ============================================================================ - -param( - [Parameter(Mandatory = $true)] [string[]]$Runs, - [string[]]$Labels = @(), - [string]$Out = "" -) - -$ErrorActionPreference = "Stop" - -# "powershell -File" passes "a,b" as one string. -$Runs = @($Runs | ForEach-Object { $_ -split "," } | ForEach-Object { $_.Trim() } | Where-Object { $_ }) -$Labels = @($Labels | ForEach-Object { $_ -split "," } | ForEach-Object { $_.Trim() } | Where-Object { $_ }) - -$Culture = [Globalization.CultureInfo]::InvariantCulture - -function Format-Num($Value, $Decimals = 0) { - if ($null -eq $Value) { return "-" } - return ([double]$Value).ToString("N$Decimals", $Culture) -} - -$Data = @() -for ($i = 0; $i -lt $Runs.Count; $i++) { - $Json = Get-Content (Join-Path $Runs[$i] "results.json") -Raw | ConvertFrom-Json - $Label = if ($i -lt $Labels.Count) { $Labels[$i] } else { Split-Path $Runs[$i] -Leaf } - $Data += [pscustomobject]@{ Label = $Label; Results = @($Json.Results); Queries = @($Json.Queries) } -} - -# A stage by the end of its name ("5x0" matches "ramp05-5x0"). -function Get-Stage($Run, $Suffix) { - return $Run.Results | Where-Object { $_.Stage -like "*$Suffix" } | Select-Object -First 1 -} - -function Get-Max($Stage, $Property) { - if (-not $Stage) { return $null } - return ($Stage.Servers | Measure-Object -Property $Property -Maximum).Maximum -} - -function Get-Avg($Stage, $Property) { - if (-not $Stage) { return $null } - return ($Stage.Servers | Measure-Object -Property $Property -Average).Average -} - -# Median of a query on the first server, in the last stage that ran it. -function Get-Query($Run, $Name) { - $Q = $Run.Queries | Where-Object { $_.Name -eq $Name -and $_.Server -eq $Run.Results[0].Servers[0].Name } | Select-Object -Last 1 - if (-not $Q -or $Q.Count -eq 0) { return $null } - return $Q.P50Ms -} - -function Get-LoadQuery($Run, $Name) { - $Mixed = Get-Stage $Run "mixed" - if (-not $Mixed) { return $null } - $Q = $Mixed.QueriesUnderLoad | Where-Object Name -eq $Name | Select-Object -First 1 - if (-not $Q) { return $null } - return $Q.P50Ms -} - -$Rows = @( - @("**Push ceiling**, msg/s, 5 nodes/server", { param($R) Format-Num (Get-Stage $R "5x0").PushRate }), - @("**Push ceiling**, msg/s, 10 nodes/server", { param($R) Format-Num (Get-Stage $R "10x0").PushRate }), - @("Pushed of 2,000 offered (10 x 50)", { param($R) Format-Num (Get-Stage $R "10x50").PushRate }), - @("Pushed of 4,000 offered (10 x 100)", { param($R) Format-Num (Get-Stage $R "10x100").PushRate }), - @("Push p50 / p99 ms, 10 x 50", { param($R) $S = Get-Stage $R "10x50"; if ($S) { "$(Format-Num $S.PushP50Ms 1) / $(Format-Num $S.PushP99Ms 1)" } else { "-" } }), - @("Push p50 / p99 / max ms, flat out (10 nodes)", { param($R) $S = Get-Stage $R "10x0"; if ($S) { "$(Format-Num $S.PushP50Ms 1) / $(Format-Num $S.PushP99Ms 1) / $(Format-Num $S.PushMaxMs)" } else { "-" } }), - @("Replication lag, s of pushes, flat out", { param($R) Format-Num (Get-Max (Get-Stage $R "10x0") "LagMaxSeconds") 1 }), - @("Drain after the push, s, flat out", { param($R) Format-Num (Get-Stage $R "10x0").DrainSeconds 1 }), - @("Server CPU, % of a core, flat out (avg of the 4)", { param($R) Format-Num (Get-Avg (Get-Stage $R "10x0") "CpuAvgPush") }), - @("Machine CPU %, flat out", { param($R) Format-Num (Get-Stage $R "10x0").SystemCpuAvg }), - @("Hub RAM, working set MB, max", { param($R) Format-Num (($R.Results | ForEach-Object { $_.Servers[0].WorkingSetMaxMb } | Measure-Object -Maximum).Maximum) 1 }), - @("Rows per server at the end", { param($R) Format-Num $R.Results[-1].Servers[0].Rows }), - @("Query: latest message, ms (1M rows)", { param($R) Format-Num (Get-Query $R "latest_message") 1 }), - @("Query: last 50 of a node, ms", { param($R) Format-Num (Get-Query $R "last_50_of_node") 1 }), - @("Query: sync state (GROUP BY all), ms", { param($R) Format-Num (Get-Query $R "sync_state") 1 }), - @("Query: sync state from node_heads (what check-ins use now), ms", { param($R) Format-Num (Get-Query $R "sync_state_heads") 1 }), - @("Query: JSON count over all rows, ms", { param($R) Format-Num (Get-Query $R "json_count_all") 1 }), - @("Query: JSON aggregate over all rows, ms", { param($R) Format-Num (Get-Query $R "json_agg_all") 1 }), - @("**Mixed:** pushed of 400 msg/s with a query loop", { param($R) Format-Num (Get-Stage $R "mixed").PushRate }), - @("Mixed: push p99 / max ms", { param($R) $S = Get-Stage $R "mixed"; if ($S) { "$(Format-Num $S.PushP99Ms 1) / $(Format-Num $S.PushMaxMs)" } else { "-" } }), - @("Mixed: failed pushes", { param($R) $S = Get-Stage $R "mixed"; if ($S) { $S.Failed } else { "-" } }), - @("Mixed: JSON count over all rows, ms, under load", { param($R) Format-Num (Get-LoadQuery $R "json_count_all") 1 }), - @("Mixed: latest message, ms, under load", { param($R) Format-Num (Get-LoadQuery $R "latest_message") 1 }) -) - -$Lines = @() -$Lines += "| | " + (($Data | ForEach-Object { $_.Label }) -join " | ") + " |" -$Lines += "|---|" + (($Data | ForEach-Object { "---" }) -join "|") + "|" -foreach ($Row in $Rows) { - $Cells = foreach ($Run in $Data) { & $Row[1] $Run } - $Lines += "| $($Row[0]) | " + ($Cells -join " | ") + " |" -} - -$Text = $Lines -join "`r`n" -if ($Out) { Set-Content -Path $Out -Value $Text -Encoding UTF8 } -$Text diff --git a/Tests/Bench/Results-2026-11-07.md b/Tests/Bench/Results-2026-11-07.md deleted file mode 100644 index cad5af3..0000000 --- a/Tests/Bench/Results-2026-11-07.md +++ /dev/null @@ -1,182 +0,0 @@ -# Benchmark results, 2026-11-07 - -`Bench-Replication.ps1` with its defaults: 4 servers in a Y (a hub linked to -3 leaves), 5-10 nodes pushing to each, ~200-byte JSON messages, 30 s per -stage, `PeerSyncInterval = 5`, `PeerBatchSize = 100`. All on one machine -(i5-13500, 16 GB, NVMe), PureBasic 5.73 x64 unless said otherwise, SQLite -3.54.1. Table made with `Compare-Runs.ps1`. - -| Version | What changed | -|---|---| -| Before | Rollback journal, a sync to disk per push, every wait a `Delay(5)` / `Delay(1)` loop | -| WAL + wake-ups | WAL with `synchronous = NORMAL`, threads woken by an event / `select()`, a write mutex instead of SQLite's busy-wait | -| + grouping | Pushes arriving together share one transaction (group commit) | -| + no per-push log | The `PrintN()` per push / read / query removed (`#BakaShrot_Net_LogRequests`) | -| + prepared/cache/checkpoints/heads | One writer connection with prepared statements (SQLite's own API), next ids cached in memory, WAL checkpoints in a background thread, the sync state from `node_heads` (`Server/Storage/Writer.pbi`) | -| same on PB 6.40 C | The same code, built with PureBasic 6.40's C backend and `/OPTIMIZER` (the load generator too) | - -| | Before | WAL + wake-ups | + grouping | + no per-push log | + prepared/cache/checkpoints/heads (5.73) | same on PB 6.40 C | -|---|---|---|---|---|---|---| -| **Push ceiling**, msg/s, 5 nodes/server | 958 | 5,771 | 5,709 | 25,681 | 33,522 | 37,162 | -| **Push ceiling**, msg/s, 10 nodes/server | 904 | 5,726 | 5,814 | 25,707 | 34,345 | 38,358 | -| Pushed of 2,000 offered (10 x 50) | 924 | 1,999 | 2,000 | 2,000 | 2,000 | 1,999 | -| Pushed of 4,000 offered (10 x 100) | 899 | 4,000 | 4,000 | 4,000 | 4,000 | 4,000 | -| Push p50 / p99 ms, 10 x 50 | 18.0 / 491.5 | 0.4 / 5.1 | 0.5 / 7.2 | 0.5 / 13.6 | 0.3 / 0.8 | 0.2 / 0.9 | -| Push p50 / p99 / max ms, flat out (10 nodes) | 18.0 / 574.9 / 2,642 | 5.5 / 25.2 / 193 | 5.6 / 23.1 / 56 | 0.9 / 16.5 / 149 | 0.5 / 2.8 / 854 | 0.5 / 2.5 / 1,485 | -| Replication lag, s of pushes, flat out | 8.9 | 5.1 | 5.0 | 8.9 | 9.9 | 8.3 | -| Drain after the push, s, flat out | 6.2 | 5.8 | 5.8 | 10.3 | 11.3 | 11.3 | -| Server CPU, % of a core, flat out (avg of the 4) | 45 | 65 | 66 | 130 | 120 | 121 | -| Machine CPU %, flat out | 41 | 33 | 34 | 67 | 65 | 65 | -| Hub RAM, working set MB, max | 34.6 | 42.9 | 44.6 | 45.2 | 38.8 | 40.1 | -| Rows per server at the end | 1,021,883 | 1,024,025 | 1,024,025 | 1,887,117 | 2,389,201 | 2,619,806 | -| Query: latest message, ms (1M rows) | 5.9 | 0.5 | 0.5 | 0.1 | 0.1 | 0.1 | -| Query: last 50 of a node, ms | 5.8 | 1.0 | 1.0 | 0.7 | 0.8 | 0.7 | -| Query: sync state (GROUP BY all), ms | 78.0 | 73.1 | 72.1 | 131.9 | 166.7 | 184.1 | -| Query: sync state from node_heads (what check-ins use now), ms | - | - | - | - | 0.6 | 0.5 | -| Query: JSON count over all rows, ms | 473.6 | 475.1 | 475.3 | 857.5 | 1,080.7 | 1,199.4 | -| Query: JSON aggregate over all rows, ms | 1,647.8 | 1,575.8 | 1,533.9 | 2,800.2 | 3,974.2 | 4,371.2 | -| **Mixed:** pushed of 400 msg/s with a query loop | 323 | 396 | 397 | 397 | 392 | 396 | -| Mixed: push p99 / max ms | 820.2 / 5,119 | 0.7 / 17 | 7.9 / 17 | 18.0 / 30 | 1.2 / 17 | 0.9 / 17 | -| Mixed: failed pushes | 1 | 0 | 0 | 0 | 0 | 0 | -| Mixed: JSON count over all rows, ms, under load | 545.4 | 502.3 | 506.5 | 925.0 | 1,148.2 | 1,265.6 | -| Mixed: latest message, ms, under load | 12.0 | 0.2 | 0.2 | 0.1 | 0.2 | 0.2 | - -The full-table scans grow with the data, and the later runs' flat-out stages -wrote more of it: 1.9M, 2.4M, then 2.6M rows per server instead of ~1.02M. -Per row they cost the same (~0.45 ms per 1,000 rows for the JSON count). -PB 6.40 doesn't change them either, SQLite does the scanning. - -## What limited each version - -- **Before:** the sync to disk on every push, ~250 commits/s per database. -- **WAL + wake-ups:** not the database anymore. The `PrintN()` logging every - push takes ~0.4 ms and serializes every thread behind it: ~2,400 pushes/s - per server whatever the number of nodes, with the server mostly idle - (measured on a single server: the listener asleep in `select()` 91 % of - the time, the writes busy 33 %, 0.14 ms per push). -- **+ grouping:** same cap, so no gain yet: the pushes never piled up - behind the write mutex (1.0 per transaction on average). It did cut the - worst push from 193 to 56 ms. -- **+ no per-push log:** a single server went from ~2,400 to ~12,000 - pushes/s, and grouping now kicks in: 2.5 pushes per transaction at 5 - nodes, ~5-9 at 10-20, the database busy 70-90 % of the time at 0.07-0.11 - ms per push. The cluster tops out at ~25,700 msg/s with the machine at - 67 % CPU (the load generator itself ~85 % of a core). Next limits: each - server's write section, and running everything on one machine. -- **+ prepared/cache/checkpoints/heads:** ~25,700 -> ~34,300 msg/s. A push - costs ~0.05 ms of write time instead of 0.07-0.11, no statement is - prepared again, no MAX() per push. The p99 at moderate load is back under - 1 ms (13.6 -> 0.8 ms at 10 x 50, 18 -> 1.2 ms in the mixed stage): the - checkpoints were what held the writes up. Flat out, the WAL grows faster - than the background checkpoints keep up with, so the writer checkpoints by - itself past 10,000 frames, and the worst push goes from 149 to 854 ms. The - sync state every check-in reads: 0.5 ms instead of a 167 ms GROUP BY. -- **Same on PB 6.40 C:** ~34,300 -> ~38,400 msg/s (+12 %), the same - latencies, slightly less lag. Both the servers and the load generator are - built with it, so part of it may be the generator. The SQLite side (the - write section, the queries) is the same DLL either way. - -## Notes - -- Ids checked after the last four runs: every node 1..N, no gap, no - duplicate, on all 4 servers, and `node_heads` exactly matching `data`. -- **p99 at moderate load went up with grouping** (0.7 -> 8-18 ms), and came - back down once the checkpoints left the write path (see above). -- Replication keeps up at every load: it drains within ~11 s even after - 38,000 msg/s. The lag is the check-in wait (`PeerSyncInterval`) plus the - hub relaying to its leaves, see `Design/Suggestions.md` #2 to lower it. -- The worst push flat out (0.85-1.5 s) is the writer's backstop checkpoint, - see `Design/Suggestions.md` #3. - -## Names and wildcards (evening) - -Same benchmark, PureBasic 5.73, after topics and nodes got names, strict -"named on both sides" replication, and wildcards, run with `-Names -Wildcard`: each server only names its own nodes, and takes everyone else's -by `AcceptNodes = n*`, so each server adds the other servers' 30 nodes -under ids of its own (counting down from 65535), and the hub relays them on -by name. The worst case for the new code: every batch goes through a name -lookup and every check-in through the patterns. Run `20261107-220433`, -compared with `Compare-Runs.ps1` (`comparison.md` in the run's folder). - -| | Before names (5.73) | Before names (PB 6.40 C) | Names + wildcards (5.73) | -|---|---|---|---| -| **Push ceiling**, msg/s, 5 nodes/server | 33,522 | 37,162 | 35,124 | -| **Push ceiling**, msg/s, 10 nodes/server | 34,345 | 38,358 | 32,846 | -| Push p50 / p99 ms, 10 x 50 | 0.3 / 0.8 | 0.2 / 0.9 | 0.3 / 1.1 | -| Push p50 / p99 / max ms, flat out (10 nodes) | 0.5 / 2.8 / 854 | 0.5 / 2.5 / 1,485 | 0.6 / 3.2 / 1,503 | -| Replication lag, s of pushes, flat out | 9.9 | 8.3 | 8.6 | -| Drain after the push, s, flat out | 11.3 | 11.3 | 11.8 | -| Server CPU, % of a core, flat out (avg of the 4) | 120 | 121 | 129 | -| Hub RAM, working set MB, max | 38.8 | 40.1 | 39.3 | -| Rows per server at the end | 2,389,201 | 2,619,806 | 2,395,509 | -| Query: sync state from node_heads, ms | 0.6 | 0.5 | 0.7 | -| Query: JSON count over all rows, ms | 1,080.7 | 1,199.4 | 1,105.8 | -| **Mixed:** pushed of 400 msg/s with a query loop | 392 | 396 | 397 | -| Mixed: push p99 / max ms | 1.2 / 17 | 0.9 / 17 | 0.9 / 18 | -| Failed pushes, refusals between servers | 0 | 0 | 0 | - -- **Same speed, within run-to-run noise.** Flat out at 10 nodes, the same - build gave 32,976 and 37,003 msg/s in two ramp-only runs (declared names) - earlier this evening: ±6 % between runs is usual on this machine. The push - path itself didn't change, only the check-ins and the batches' first - lines. -- **Server CPU +7 %** flat out (129 vs 120 % of a core), the name lookups - and the bigger sync states, possibly part of the noise too. -- **Replication** keeps up at every load and drains in the same time; no - batch refused anywhere, every server ended with the same rows. -- **Measuring changed slightly:** the lag monitor now asks for each node's - latest id by name through the `messages` view (ids differ between - servers in this mode), the old runs asked `data` by id. Both are index - lookups. - -## Big messages, no JSON check on push, is_json clause (2026-11-08) - -Same setup as the evening run (`-Names Wildcard`), after: packets up to -16 MB once authenticated (new inbox: growth by doubling, a read offset), -replication batches still ~64 KB, pushes no longer checked to be JSON -(`ParseJSON()` gone from the push path, `is_json` flags them), and -`is_json = 1` added to the JSON queries. - -| | Before names (5.73) | Before names (PB 6.40 C) | Names + wildcards (5.73) | Big messages, no JSON check, is_json clause (5.73) | -|---|---|---|---|---| -| **Push ceiling**, msg/s, 5 nodes/server | 33,522 | 37,162 | 35,124 | **38,199** | -| **Push ceiling**, msg/s, 10 nodes/server | 34,345 | 38,358 | 32,846 | **37,745** | -| Pushed of 2,000 offered (10 x 50) | 2,000 | 1,999 | 1,999 | 2,001 | -| Pushed of 4,000 offered (10 x 100) | 4,000 | 4,000 | 4,000 | 4,000 | -| Push p50 / p99 ms, 10 x 50 | 0.3 / 0.8 | 0.2 / 0.9 | 0.3 / 1.1 | 0.3 / 1.0 | -| Push p50 / p99 / max ms, flat out (10 nodes) | 0.5 / 2.8 / 854 | 0.5 / 2.5 / 1,485 | 0.6 / 3.2 / 1,503 | 0.5 / 2.9 / 822 | -| Replication lag, s of pushes, flat out | 9.9 | 8.3 | 8.6 | 10.5 | -| Drain after the push, s, flat out | 11.3 | 11.3 | 11.8 | 13.8 | -| Server CPU, % of a core, flat out (avg of the 4) | 120 | 121 | 129 | 120 | -| Machine CPU %, flat out | 65 | 65 | 69 | 66 | -| Hub RAM, working set MB, max | 38.8 | 40.1 | 39.3 | 42.8 | -| Rows per server at the end | 2,389,201 | 2,619,806 | 2,395,509 | 2,628,001 | -| Query: latest message, ms | 0.1 | 0.1 | 0.1 | 0.1 | -| Query: last 50 of a node, ms | 0.8 | 0.7 | 0.8 | 0.8 | -| Query: sync state (GROUP BY all), ms | 166.7 | 184.1 | 170.5 | 187.9 | -| Query: sync state from node_heads (what check-ins use now), ms | 0.6 | 0.5 | 0.7 | 0.6 | -| Query: JSON count over all rows, ms | 1,080.7 | 1,199.4 | 1,105.8 | 1,233.6 | -| Query: JSON aggregate over all rows, ms | 3,974.2 | 4,371.2 | 4,084.2 | 4,464.4 | -| Same, per million rows: sync state / JSON count / JSON aggregate, ms | 69.8 / 452 / 1,663 | 70.3 / 458 / 1,669 | 71.2 / 462 / 1,705 | 71.5 / 469 / 1,699 | -| **Mixed:** pushed of 400 msg/s with a query loop | 392 | 396 | 397 | 384 | -| Mixed: push p99 / max ms | 1.2 / 17 | 0.9 / 17 | 0.9 / 18 | 1.0 / 15 | -| Mixed: failed pushes | 0 | 0 | 0 | 0 | -| Mixed: JSON count over all rows, ms, under load | 1,148.2 | 1,265.6 | 1,179.5 | 1,313.4 | -| Mixed: latest message, ms, under load | 0.2 | 0.2 | 0.2 | 0.2 | - -Runs: `20261107-140556`, `20261107-141735`, `20261107-220433`, `20261108-033149` (all 4 servers in a Y, ~200-byte messages; the last two with `-Names Wildcard`). Query times are from the end of each run, so they scale with its row count: compare the per-million row. - -- **Push ceiling up 9-15 %** (38,199 / 37,745 msg/s), the best yet on 5.73, - for the same server CPU (120 % of a core). Likely mostly `ParseJSON()` - leaving the push path, though runs of one build have spread 33-37k. -- **Lag and drain** are a bit higher in seconds, with 15 % more messages - pushed per second to relay (397,066 messages behind at most, vs 282,621). -- **The `is_json = 1` clause costs nothing measurable:** per million rows, - the JSON count is 469 ms vs 462, the aggregate 1,699 vs 1,705. -- **Mixed: 384 of 400 msg/s pushed** (397 before), with no failures and a - lower p99. The bench's pushers are paced by its own loop, and this run's - database was 10 % bigger, so the query loop beside them was slower. Worth - a second run before reading anything into it. -- 0 refused, failed or "too big" in the server logs, 2,628,001 rows on all - 4 servers. diff --git a/Tests/Bench/queries.txt b/Tests/Bench/queries.txt deleted file mode 100644 index 674bb8e..0000000 --- a/Tests/Bench/queries.txt +++ /dev/null @@ -1,30 +0,0 @@ -# Query suite, run by BenchClient's "query" mode after every stage, see -# Bench-Replication.ps1. One per line: Name | SQL -# {TOPIC} and {NODE} are replaced by the topic id and the server's first node. -# "@latest" is a GetLatestMessage of {NODE}, the regular read path. -# Results must fit in one packet (64 KB) and 10000 rows. -# -# The messages look like: -# {"kind":"temp","node":101,"seq":12,"value":42.17,"ts":1700000012,"pad":"xxx"} -# kind is "alert" for 1 in 50, the others are spread evenly. - -# Indexed, should stay flat as the data grows. -latest_message | @latest -last_50_of_node | SELECT message_id, message_data FROM data WHERE topic_id = {TOPIC} AND node_id = {NODE} ORDER BY message_id DESC LIMIT 50 -max_of_node | SELECT MAX(message_id) FROM data WHERE topic_id = {TOPIC} AND node_id = {NODE} -by_message_id | SELECT topic_id, node_id FROM data WHERE message_id = 100 -recent_global | SELECT topic_id, node_id, message_id FROM data ORDER BY rowid DESC LIMIT 100 - -# Bounded JSON scan: newest alerts of one node, about 50 rows read per hit. -json_alerts_node | SELECT message_id, message_data ->> '$.value' FROM data WHERE topic_id = {TOPIC} AND node_id = {NODE} AND is_json = 1 AND message_data ->> '$.kind' = 'alert' ORDER BY message_id DESC LIMIT 100 - -# Index scans, grow with the data. -count_node | SELECT COUNT(*) FROM data WHERE topic_id = {TOPIC} AND node_id = {NODE} -count_all | SELECT COUNT(*) FROM data -sync_state | SELECT topic_id, node_id, MAX(message_id) FROM data GROUP BY topic_id, node_id ORDER BY topic_id, node_id -sync_state_heads | SELECT topic_id, node_id, max_message_id FROM node_heads ORDER BY topic_id, node_id - -# Full table scans parsing every message's JSON, the ones that die first. -json_count_all | SELECT COUNT(*) FROM data WHERE is_json = 1 AND message_data ->> '$.kind' = 'alert' -json_agg_all | SELECT message_data ->> '$.kind', COUNT(*), ROUND(AVG(message_data ->> '$.value'), 2) FROM data WHERE is_json = 1 GROUP BY 1 -json_agg_node | SELECT message_data ->> '$.kind', COUNT(*), ROUND(AVG(message_data ->> '$.value'), 2) FROM data WHERE topic_id = {TOPIC} AND node_id = {NODE} AND is_json = 1 GROUP BY 1 diff --git a/Tests/Bench/queries_load.txt b/Tests/Bench/queries_load.txt deleted file mode 100644 index 8a8f4e7..0000000 --- a/Tests/Bench/queries_load.txt +++ /dev/null @@ -1,13 +0,0 @@ -# Queries run in a loop while pushing, in the "mixed" stage of -# Bench-Replication.ps1, to see how reads hold up under write load, and how -# much a long read slows the writes down (it used to block every commit, -# before WAL). -# Same format as queries.txt. - -latest_message | @latest -last_50_of_node | SELECT message_id, message_data FROM data WHERE topic_id = {TOPIC} AND node_id = {NODE} ORDER BY message_id DESC LIMIT 50 -json_alerts_node | SELECT message_id, message_data ->> '$.value' FROM data WHERE topic_id = {TOPIC} AND node_id = {NODE} AND is_json = 1 AND message_data ->> '$.kind' = 'alert' ORDER BY message_id DESC LIMIT 100 -count_node | SELECT COUNT(*) FROM data WHERE topic_id = {TOPIC} AND node_id = {NODE} -sync_state | SELECT topic_id, node_id, MAX(message_id) FROM data GROUP BY topic_id, node_id ORDER BY topic_id, node_id -sync_state_heads | SELECT topic_id, node_id, max_message_id FROM node_heads ORDER BY topic_id, node_id -json_count_all | SELECT COUNT(*) FROM data WHERE is_json = 1 AND message_data ->> '$.kind' = 'alert' diff --git a/Tests/BigMessages-Test.ps1 b/Tests/BigMessages-Test.ps1 deleted file mode 100644 index ccd9ca9..0000000 --- a/Tests/BigMessages-Test.ps1 +++ /dev/null @@ -1,346 +0,0 @@ -# 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 "BakaShrotGenerateKeyPairs.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 "BakaShrotQuery.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 BakaShrotPushMessage'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) -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 -Node = serverB -PublicKey = $($B.Pub) - -[BakaShrot.Client.b] -PublicKeys = $($B.Pub) -Node = serverB -DefaultTopic = logs - -[BakaShrot.Client.kitchen] -PublicKeys = $($K.Pub) -Node = kitchen -DefaultTopic = logs -ReadTopics = * -AllowQuery = 1 -"@ - -Set-Content (Join-Path $Dir "b.ini") -Encoding Ascii -Value @" -[BakaShrot] -PrivateKey = $($B.Priv) -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 -Node = serverA -PublicKey = $($A.Pub) - -[BakaShrot.Client.a] -PublicKeys = $($A.Pub) -Node = serverA -DefaultTopic = logs - -[BakaShrot.Client.kitchen] -PublicKeys = $($K.Pub) -Node = kitchen -DefaultTopic = logs -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`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 "BakaShrotPushMessage.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 "BakaShrotPushMessage.exe" @($Over, $OnA)) "too big" 1 - $Id++ - Expect "a small push after them" (Tool "BakaShrotPushMessage.exe" @($Small, $OnA)) "message #$Id" - - "--- Read back" - $T = Measure-Command { $O = & (Join-Path $Build "BakaShrotGetLatestMessage.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 "BakaShrotPushMessage.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 "BakaShrotGetLatestMessage.exe") "logs" "kitchen" $OnB 2>&1 } - $Code = $LASTEXITCODE - $Json = if ($O.Count -ge 2) { [string]$O[1] } else { "" } - Check ("BakaShrotGetLatestMessage 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 "BakaShrotPushMessage.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 "BakaShrotPushMessage.exe" @("@$Broken", $OnA)) "message #36" - Expect "plain text is stored" (Tool "BakaShrotPushMessage.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 "BakaShrotGetLatestMessage.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 "BakaShrotPushMessage.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. -# A and B start together: until its first link, the other one may not be -# listening yet. Refused at once on Linux, while Windows retries the connect -# for about a second, by which time it usually is. Those attempts are left out. -function Skip-EarlyLinkFailures([string[]]$Lines) { - $Linked = $false - foreach ($Line in $Lines) { - if ($Line -match "^\[Peer\] Linked to") { $Linked = $true } - if ($Linked -or $Line -notmatch "^\[Peer\] (Failed to link|Retrying)") { $Line } - } -} -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|Dropping the link|Retrying|disconnected|aborted|didn't answer") { $End-- } - @(Skip-EarlyLinkFailures $L[0..([math]::Max($End - 1, 0))]) -join "`n" -} -$LogA = Read-Log "a" -$LogB = Read-Log "b" -# The raw frames are cut as an invalid frame, or as too much data when the -# zeros after the header filled the inbox before its size was checked: -# either way right away, which one is down to timing. -# Client ids get reused, so whether each one is authenticated is followed -# line by line, from its "connected". -$Authenticated = @{}; $Cut = 0; $CutAuthenticated = 0 -foreach ($Line in ($LogA -split "`n")) { - if ($Line -match "Client (\d+) connected") { $Authenticated[$Matches[1]] = $false } - elseif ($Line -match "Client (\d+) authenticated") { $Authenticated[$Matches[1]] = $true } - elseif ($Line -match "Client (\d+) sent (an invalid frame|too much data)") { - $Cut++ - if ($Authenticated[$Matches[1]]) { $CutAuthenticated++ } - } -} -Check "A cut both raw frames (invalid frame or too much data)" ($Cut -ge 2) "$Cut times" -Check "none of them from an authenticated client" ($CutAuthenticated -eq 0) "$CutAuthenticated" -# Without the refusals this test asks for ("Query failed: malformed JSON", ...). -$UnrefusedA = ($LogA -split "`n" | Where-Object { $_ -notmatch "Refused a request" }) -join "`n" -$UnrefusedB = ($LogB -split "`n" | Where-Object { $_ -notmatch "Refused a request" }) -join "`n" -foreach ($P in @("too big", "Lost the link", "Failed")) { - Check "no '$P' in A's or B's log" (-not ($UnrefusedA -match [regex]::Escape($P)) -and -not ($UnrefusedB -match [regex]::Escape($P))) "checked" -} -Check "no 'sent too much data' in B's log" (-not ($LogB -match "sent too much data")) "checked" - -"" -if ($Fails) { "$Fails FAILED"; exit 1 } else { "All passed" } diff --git a/Tests/CipherTest.pb b/Tests/CipherTest.pb deleted file mode 100644 index 7c67703..0000000 --- a/Tests/CipherTest.pb +++ /dev/null @@ -1,404 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: CipherTest.pb -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; Tests of Commons/Cryptography/Cipher.pbi, no sockets: round trips in both -; directions, and everything that must be refused (tampering, replay, -; reordering, reflection, wrong key), empty and 16 MB buffers. -; And of Session.pbi: the sealed Hello (only its server opens it, tampering -; refused) and the key exchange (both ends agree, a swapped half or another -; connection's keys don't work, the key pairs are wiped). -; Compile as a console program into Build\ (libsodium.dll is there), run it -; from there. Exits with 0 if every check passed, 1 otherwise. -; ============================================================================ - -EnableExplicit - -XIncludeFile "../Commons/Cryptography/Session.pbi" - -Global Fails.i = 0 - -Procedure Check(What.s, Ok.i, Detail.s = "") - If Ok - PrintN("PASS " + What) - Else - PrintN("FAIL " + What) - Fails + 1 - EndIf - If Detail <> "" - PrintN(" -> " + Detail) - EndIf -EndProcedure - -; Text as a UTF-8 buffer, its size in *Size\i. -Procedure.i ToUtf8(Text.s, *Size.Integer) - Protected *Buffer - *Size\i = StringByteLength(Text, #PB_UTF8) - *Buffer = AllocateMemory(*Size\i + 1) - PokeS(*Buffer, Text, -1, #PB_UTF8) - ProcedureReturn *Buffer -EndProcedure - -; Encrypts Text with *From, decrypts it with *To, returns what came out ("" and -; *Ok\i #False if refused). -Procedure.s RoundTrip(*From.BakaShrot_Cipher, *To.BakaShrot_Cipher, Text.s, *Ok.Integer) - Protected *Plain, PlainSize.Integer, *Sealed, SealedSize.Integer, *Opened, OpenedSize.Integer, Result.s - *Ok\i = #False - *Plain = ToUtf8(Text, @PlainSize) - *Sealed = BakaShrot_Cipher_Encrypt(*From, *Plain, PlainSize\i, @SealedSize) - FreeMemory(*Plain) - If Not *Sealed - ProcedureReturn "" - EndIf - *Opened = BakaShrot_Cipher_Decrypt(*To, *Sealed, SealedSize\i, @OpenedSize) - FreeMemory(*Sealed) - If Not *Opened - ProcedureReturn "" - EndIf - Result = PeekS(*Opened, OpenedSize\i, #PB_UTF8 | #PB_ByteLength) - FreeMemory(*Opened) - *Ok\i = #True - ProcedureReturn Result -EndProcedure - -; Whether Text's UTF-8 bytes appear anywhere in *Buffer (Size bytes). -Procedure.i ContainsText(*Buffer, Size.i, Text.s) - Protected *Needle, NeedleSize.Integer, i.i, Found.i - *Needle = ToUtf8(Text, @NeedleSize) - For i = 0 To Size - NeedleSize\i - If CompareMemory(*Buffer + i, *Needle, NeedleSize\i) - Found = #True - Break - EndIf - Next - FreeMemory(*Needle) - ProcedureReturn Found -EndProcedure - -; Whether *Sealed (Size bytes) is refused by *To, without changing it. -Procedure.i IsRefused(*To.BakaShrot_Cipher, *Sealed, Size.i) - Protected *Opened, OpenedSize.Integer - *Opened = BakaShrot_Cipher_Decrypt(*To, *Sealed, Size, @OpenedSize) - If *Opened - FreeMemory(*Opened) - ProcedureReturn #False - EndIf - ProcedureReturn #True -EndProcedure - -; A copy of Size bytes at *Source. -Procedure.i Copy(*Source, Size.i) - Protected *Copy = AllocateMemory(Size) - CopyMemory(*Source, *Copy, Size) - ProcedureReturn *Copy -EndProcedure - - -Define *Key, *OtherKey -Define Client.BakaShrot_Cipher, Server.BakaShrot_Cipher, Other.BakaShrot_Cipher, Uninitialized.BakaShrot_Cipher -Define Ok.Integer, Text.s, i.i, Zero.i -Define *Plain, PlainSize.Integer, *Sealed, SealedSize.Integer, *Sealed2, Sealed2Size.Integer, *Opened, OpenedSize.Integer -Define *Tampered, Offset.i, Refused.i, StartTime.q, Elapsed.q - -OpenConsole() - -If Not InitCryptography() - PrintN("FAIL libsodium couldn't initialize") - End 1 -EndIf - -*Key = AllocateMemory(#BakaShrot_Cipher_KeySize) -*OtherKey = AllocateMemory(#BakaShrot_Cipher_KeySize) -BakaShrot_Cipher_GenerateKey(*Key) -BakaShrot_Cipher_GenerateKey(*OtherKey) -Check("Two generated keys differ", Bool(Not CompareMemory(*Key, *OtherKey, #BakaShrot_Cipher_KeySize))) - -Check("Init as client", BakaShrot_Cipher_Init(@Client, *Key, #BakaShrot_Cipher_Client)) -Check("Init as server", BakaShrot_Cipher_Init(@Server, *Key, #BakaShrot_Cipher_Server)) -Check("Init with role 0 refused", Bool(Not BakaShrot_Cipher_Init(@Other, *Key, 0))) - -; --- Round trips --------------------------------------------------------------- - -Text = RoundTrip(@Client, @Server, "hello, server", @Ok) -Check("Client -> server", Bool(Ok\i And Text = "hello, server"), Text) -Text = RoundTrip(@Server, @Client, "hello, client", @Ok) -Check("Server -> client", Bool(Ok\i And Text = "hello, client"), Text) -For i = 1 To 100 - Text = RoundTrip(@Client, @Server, "message " + Str(i), @Ok) - If Not Ok\i Or Text <> "message " + Str(i) - Break - EndIf -Next -Check("100 more in order", Bool(i = 101), Str(i - 1) + " went through") -Text = RoundTrip(@Client, @Server, "héllo wörld, 🌍", @Ok) -Check("Non-ASCII data", Bool(Ok\i And Text = "héllo wörld, 🌍"), Text) - -; --- What a sealed buffer looks like ------------------------------------------ - -*Plain = ToUtf8("same text", @PlainSize) -*Sealed = BakaShrot_Cipher_Encrypt(@Client, *Plain, PlainSize\i, @SealedSize) -*Sealed2 = BakaShrot_Cipher_Encrypt(@Client, *Plain, PlainSize\i, @Sealed2Size) -Check("Sealed size is the data + " + Str(#BakaShrot_Cipher_Overhead), Bool(SealedSize\i = PlainSize\i + #BakaShrot_Cipher_Overhead), Str(SealedSize\i) + " bytes for " + Str(PlainSize\i)) -Check("The data doesn't appear in it", Bool(Not CompareMemory(*Sealed + #BakaShrot_Cipher_SequenceSize, *Plain, PlainSize\i))) -Check("The same data twice seals differently", Bool(Not CompareMemory(*Sealed + #BakaShrot_Cipher_SequenceSize, *Sealed2 + #BakaShrot_Cipher_SequenceSize, PlainSize\i))) -Check("Each carries its sequence number", Bool(PeekQ(*Sealed2) = PeekQ(*Sealed) + 1), Str(PeekQ(*Sealed)) + ", " + Str(PeekQ(*Sealed2))) - -; --- Refused --------------------------------------------------------------------- - -; Reordered: the second one first. -Check("The next-but-one first: refused (reordered)", IsRefused(@Server, *Sealed2, Sealed2Size\i)) - -; Tampered anywhere: the sequence number, the data, the tag. -Refused = 0 -For Offset = 0 To SealedSize\i - 1 - *Tampered = Copy(*Sealed, SealedSize\i) - PokeA(*Tampered + Offset, PeekA(*Tampered + Offset) ! $01) - If IsRefused(@Server, *Tampered, SealedSize\i) - Refused + 1 - EndIf - FreeMemory(*Tampered) -Next -Check("One bit flipped anywhere: refused, at every one of its " + Str(SealedSize\i) + " bytes", Bool(Refused = SealedSize\i), Str(Refused) + " refused") -Check("Cut short by one byte: refused", IsRefused(@Server, *Sealed, SealedSize\i - 1)) -Check("Shorter than the overhead: refused", IsRefused(@Server, *Sealed, #BakaShrot_Cipher_Overhead - 1)) - -; None of that moved the receiver on: the genuine ones still go through, in order. -*Opened = BakaShrot_Cipher_Decrypt(@Server, *Sealed, SealedSize\i, @OpenedSize) -Check("After all that, the genuine one still decrypts", Bool(*Opened And OpenedSize\i = PlainSize\i And CompareMemory(*Opened, *Plain, PlainSize\i))) -If *Opened : FreeMemory(*Opened) : EndIf -Check("Replayed: refused", IsRefused(@Server, *Sealed, SealedSize\i)) -*Opened = BakaShrot_Cipher_Decrypt(@Server, *Sealed2, Sealed2Size\i, @OpenedSize) -Check("Then the next one", Bool(*Opened <> 0)) -If *Opened : FreeMemory(*Opened) : EndIf - -; Reflected: sent back to its sender, or to another client with the same key. -*Sealed2 = BakaShrot_Cipher_Encrypt(@Client, *Plain, PlainSize\i, @Sealed2Size) -BakaShrot_Cipher_Init(@Other, *Key, #BakaShrot_Cipher_Client) -; Same sequence number, so only the direction differs. -Other\ReceiveSequence = PeekQ(*Sealed2) -Check("Reflected to a client with the same key, same sequence number: refused", IsRefused(@Other, *Sealed2, Sealed2Size\i)) - -; Another key. -BakaShrot_Cipher_Init(@Other, *OtherKey, #BakaShrot_Cipher_Server) -Other\ReceiveSequence = PeekQ(*Sealed2) -Check("Another key: refused", IsRefused(@Other, *Sealed2, Sealed2Size\i)) -FreeMemory(*Sealed) -FreeMemory(*Sealed2) -FreeMemory(*Plain) - -Check("Not set up: refuses to encrypt", Bool(BakaShrot_Cipher_Encrypt(@Uninitialized, @Zero, 4, @SealedSize) = 0)) - -; --- Sizes --------------------------------------------------------------------- - -BakaShrot_Cipher_Init(@Client, *Key, #BakaShrot_Cipher_Client) -BakaShrot_Cipher_Init(@Server, *Key, #BakaShrot_Cipher_Server) -*Sealed = BakaShrot_Cipher_Encrypt(@Client, 0, 0, @SealedSize) -*Opened = 0 -If *Sealed - *Opened = BakaShrot_Cipher_Decrypt(@Server, *Sealed, SealedSize\i, @OpenedSize) -EndIf -Check("Empty data: sealed in " + Str(#BakaShrot_Cipher_Overhead) + " bytes, opens to 0 bytes", Bool(*Sealed And SealedSize\i = #BakaShrot_Cipher_Overhead And *Opened And OpenedSize\i = 0)) -If *Sealed : FreeMemory(*Sealed) : EndIf -If *Opened : FreeMemory(*Opened) : EndIf - -PlainSize\i = 16 * 1024 * 1024 -*Plain = AllocateMemory(PlainSize\i) -RandomData(*Plain, PlainSize\i) -StartTime = ElapsedMilliseconds() -*Sealed = BakaShrot_Cipher_Encrypt(@Client, *Plain, PlainSize\i, @SealedSize) -*Opened = BakaShrot_Cipher_Decrypt(@Server, *Sealed, SealedSize\i, @OpenedSize) -Elapsed = ElapsedMilliseconds() - StartTime -Check("16 MB both ways, intact", Bool(*Opened And OpenedSize\i = PlainSize\i And CompareMemory(*Opened, *Plain, PlainSize\i)), Str(Elapsed) + " ms to encrypt and decrypt") -FreeMemory(*Plain) -If *Sealed : FreeMemory(*Sealed) : EndIf -If *Opened : FreeMemory(*Opened) : EndIf - -; --- A key per direction ----------------------------------------------------- - -Check("Two keys: the same one twice refused", Bool(Not BakaShrot_Cipher_InitWithKeys(@Client, *Key, *Key))) -Check("Two keys: client sends with A, receives with B", BakaShrot_Cipher_InitWithKeys(@Client, *Key, *OtherKey)) -Check("Two keys: server the other way around", BakaShrot_Cipher_InitWithKeys(@Server, *OtherKey, *Key)) -Text = RoundTrip(@Client, @Server, "with two keys", @Ok) -Check("Two keys: client -> server", Bool(Ok\i And Text = "with two keys"), Text) -Text = RoundTrip(@Server, @Client, "and back", @Ok) -Check("Two keys: server -> client", Bool(Ok\i And Text = "and back"), Text) -BakaShrot_Cipher_InitWithKeys(@Other, *Key, *OtherKey) -*Plain = ToUtf8("to myself", @PlainSize) -*Sealed = BakaShrot_Cipher_Encrypt(@Other, *Plain, PlainSize\i, @SealedSize) -Check("Two keys: reflected to its sender, refused", IsRefused(@Other, *Sealed, SealedSize\i)) -FreeMemory(*Sealed) -FreeMemory(*Plain) - -; --- Clear ------------------------------------------------------------------------- - -BakaShrot_Cipher_Clear(@Client) -Zero = #True -For i = 0 To #BakaShrot_Cipher_KeySize - 1 - If Client\SendKey[i] Or Client\ReceiveKey[i] - Zero = #False - EndIf -Next -Check("Clear wipes both keys", Zero) -Check("Cleared: refuses to encrypt", Bool(BakaShrot_Cipher_Encrypt(@Client, @Zero, 4, @SealedSize) = 0)) - -sodium_memzero(*Key, #BakaShrot_Cipher_KeySize) -sodium_memzero(*OtherKey, #BakaShrot_Cipher_KeySize) - - -; --- Into a given buffer --------------------------------------------------------- - -BakaShrot_Cipher_Init(@Client, *Key, #BakaShrot_Cipher_Client) -BakaShrot_Cipher_Init(@Server, *Key, #BakaShrot_Cipher_Server) -*Plain = ToUtf8("in place", @PlainSize) -*Sealed = AllocateMemory(PlainSize\i + #BakaShrot_Cipher_Overhead) -Check("EncryptTo writes a sealed buffer", BakaShrot_Cipher_EncryptTo(@Client, *Plain, PlainSize\i, *Sealed)) -*Opened = BakaShrot_Cipher_Decrypt(@Server, *Sealed, PlainSize\i + #BakaShrot_Cipher_Overhead, @OpenedSize) -Check("EncryptTo's buffer decrypts", Bool(*Opened And PeekS(*Opened, OpenedSize\i, #PB_UTF8 | #PB_ByteLength) = "in place")) -If *Opened : FreeMemory(*Opened) : EndIf -Check("EncryptTo refuses without a cipher", Bool(Not BakaShrot_Cipher_EncryptTo(@Uninitialized, *Plain, PlainSize\i, *Sealed))) -FreeMemory(*Sealed) -FreeMemory(*Plain) -BakaShrot_Cipher_Clear(@Client) -BakaShrot_Cipher_Clear(@Server) - - -; --- Session: the sealed Hello --------------------------------------------------- - -Define *ServerPublic = AllocateMemory(#BakaShrot_Ed25519_PublicKeySize) -Define *ServerPrivate = AllocateMemory(#BakaShrot_Ed25519_PrivateKeySize) -Define *OtherPublic = AllocateMemory(#BakaShrot_Ed25519_PublicKeySize) -Define *OtherPrivate = AllocateMemory(#BakaShrot_Ed25519_PrivateKeySize) -Define *ZeroKey = AllocateMemory(32) -Define HelloKeys.BakaShrot_HelloKeys, OtherHelloKeys.BakaShrot_HelloKeys -Define ClientPair.BakaShrot_SessionKeyPair, ServerPair.BakaShrot_SessionKeyPair, MiddlePair.BakaShrot_SessionKeyPair -Define ClientHalf.BakaShrot_SessionKey, ServerHalf.BakaShrot_SessionKey, MiddleHalf.BakaShrot_SessionKey - -GenerateKeyPair(*ServerPublic, *ServerPrivate) -GenerateKeyPair(*OtherPublic, *OtherPrivate) -Check("Hello keys from a server's private key", BakaShrot_Session_LoadHelloKeys(@HelloKeys, *ServerPrivate)) -BakaShrot_Session_LoadHelloKeys(@OtherHelloKeys, *OtherPrivate) - -*Plain = ToUtf8("hello, I'm logs:kitchen", @PlainSize) -*Sealed = BakaShrot_Session_SealHello(*ServerPublic, *Plain, PlainSize\i, @SealedSize) -Check("Hello sealed, 48 bytes more", Bool(*Sealed And SealedSize\i = PlainSize\i + #BakaShrot_SealedBoxOverhead)) -Check("The sealed hello doesn't show the identity", Bool(*Sealed And Not ContainsText(*Sealed, SealedSize\i, "kitchen"))) -*Opened = BakaShrot_Session_OpenHello(@HelloKeys, *Sealed, SealedSize\i, @OpenedSize) -Check("The server opens it", Bool(*Opened And PeekS(*Opened, OpenedSize\i, #PB_UTF8 | #PB_ByteLength) = "hello, I'm logs:kitchen")) -If *Opened : FreeMemory(*Opened) : EndIf -*Opened = BakaShrot_Session_OpenHello(@OtherHelloKeys, *Sealed, SealedSize\i, @OpenedSize) -Check("Another server can't open it", Bool(Not *Opened)) -If *Opened : FreeMemory(*Opened) : EndIf - -Refused = #True -For Offset = 0 To SealedSize\i - 1 Step 7 - *Tampered = Copy(*Sealed, SealedSize\i) - PokeA(*Tampered + Offset, PeekA(*Tampered + Offset) ! $01) - *Opened = BakaShrot_Session_OpenHello(@HelloKeys, *Tampered, SealedSize\i, @OpenedSize) - If *Opened - Refused = #False - FreeMemory(*Opened) - EndIf - FreeMemory(*Tampered) -Next -Check("A tampered hello isn't opened", Refused) -*Opened = BakaShrot_Session_OpenHello(@HelloKeys, *Sealed, #BakaShrot_SealedBoxOverhead, @OpenedSize) -Check("A hello cut short isn't opened", Bool(Not *Opened)) -FreeMemory(*Sealed) - -*Sealed = BakaShrot_Session_SealHello(*ZeroKey, *Plain, PlainSize\i, @SealedSize) -Check("Sealing for an invalid server key refused", Bool(Not *Sealed)) -If *Sealed : FreeMemory(*Sealed) : EndIf -FreeMemory(*Plain) - - -; --- Session: the key exchange --------------------------------------------------- - -BakaShrot_Session_NewKeyPair(@ClientPair) -BakaShrot_Session_NewKeyPair(@ServerPair) -CopyMemory(@ClientPair\PublicKey[0], @ClientHalf, 32) -CopyMemory(@ServerPair\PublicKey[0], @ServerHalf, 32) -Check("Server starts from the client's half", BakaShrot_Session_StartServer(@Server, @ServerPair, @ClientHalf)) -Check("Client starts from the server's half", BakaShrot_Session_StartClient(@Client, @ClientPair, @ServerHalf)) -Zero = #True -For i = 0 To #BakaShrot_X25519_SecretKeySize - 1 - If ClientPair\SecretKey[i] Or ServerPair\SecretKey[i] - Zero = #False - EndIf -Next -Check("Both key pairs wiped once started", Zero) - -Text = RoundTrip(@Client, @Server, "push over a session", @Ok) -Check("Session: client -> server", Bool(Ok\i And Text = "push over a session"), Text) -Text = RoundTrip(@Server, @Client, "answer over a session", @Ok) -Check("Session: server -> client", Bool(Ok\i And Text = "answer over a session"), Text) -Check("Session: a key per direction", Bool(Not CompareMemory(@Client\SendKey[0], @Client\ReceiveKey[0], #BakaShrot_Cipher_KeySize))) -Check("Session: the client's send key is the server's receive key", CompareMemory(@Client\SendKey[0], @Server\ReceiveKey[0], #BakaShrot_Cipher_KeySize)) - -*Plain = ToUtf8("back to me", @PlainSize) -*Sealed = BakaShrot_Cipher_Encrypt(@Client, *Plain, PlainSize\i, @SealedSize) -Check("Session: reflected to the client, refused", IsRefused(@Client, *Sealed, SealedSize\i)) -FreeMemory(*Sealed) - -; Someone in the middle swapping the server's half for theirs: the client -; ends up with keys the real server doesn't have. (The server's signature -; of the halves catches it first, in the handshake.) -BakaShrot_Session_NewKeyPair(@ClientPair) -BakaShrot_Session_NewKeyPair(@ServerPair) -BakaShrot_Session_NewKeyPair(@MiddlePair) -CopyMemory(@ClientPair\PublicKey[0], @ClientHalf, 32) -CopyMemory(@MiddlePair\PublicKey[0], @MiddleHalf, 32) -BakaShrot_Session_StartServer(@Server, @ServerPair, @ClientHalf) -BakaShrot_Session_StartClient(@Client, @ClientPair, @MiddleHalf) -*Sealed = BakaShrot_Cipher_Encrypt(@Client, *Plain, PlainSize\i, @SealedSize) -Check("Session: halves swapped, the server can't decrypt", IsRefused(@Server, *Sealed, SealedSize\i)) -FreeMemory(*Sealed) - -; Another connection of the same client gets other keys. -Define Server2.BakaShrot_Cipher -CopyMemory(@Server, @Other, SizeOf(BakaShrot_Cipher)) -BakaShrot_Session_NewKeyPair(@ClientPair) -BakaShrot_Session_NewKeyPair(@ServerPair) -CopyMemory(@ClientPair\PublicKey[0], @ClientHalf, 32) -CopyMemory(@ServerPair\PublicKey[0], @ServerHalf, 32) -BakaShrot_Session_StartServer(@Server2, @ServerPair, @ClientHalf) -BakaShrot_Session_StartClient(@Client, @ClientPair, @ServerHalf) -Check("Session: another connection, other keys", Bool(Not CompareMemory(@Server2\ReceiveKey[0], @Other\ReceiveKey[0], #BakaShrot_Cipher_KeySize))) -*Sealed = BakaShrot_Cipher_Encrypt(@Client, *Plain, PlainSize\i, @SealedSize) -Check("Session: replayed into another connection, refused", IsRefused(@Other, *Sealed, SealedSize\i)) -FreeMemory(*Sealed) -FreeMemory(*Plain) - -BakaShrot_Session_NewKeyPair(@ServerPair) -Check("Session: an all-zero half refused", Bool(Not BakaShrot_Session_StartServer(@Server, @ServerPair, *ZeroKey))) -Check("Session: refused, the cipher isn't usable", Bool(Not Server\IsReady)) - -BakaShrot_Session_ClearHelloKeys(@HelloKeys) -BakaShrot_Session_ClearHelloKeys(@OtherHelloKeys) -sodium_memzero(*ServerPrivate, #BakaShrot_Ed25519_PrivateKeySize) -sodium_memzero(*OtherPrivate, #BakaShrot_Ed25519_PrivateKeySize) -BakaShrot_Cipher_Clear(@Client) -BakaShrot_Cipher_Clear(@Server) -BakaShrot_Cipher_Clear(@Server2) -BakaShrot_Cipher_Clear(@Other) - -PrintN("") -If Fails - PrintN(Str(Fails) + " check(s) failed") - End 1 -EndIf -PrintN("All checks passed") -End 0 diff --git a/Tests/GetMessages-Test.ps1 b/Tests/GetMessages-Test.ps1 deleted file mode 100644 index ed5662f..0000000 --- a/Tests/GetMessages-Test.ps1 +++ /dev/null @@ -1,251 +0,0 @@ -# End-to-end test of reading runs of messages: the GetMessages request -# (Commons/Networking/Packets/GetMessagesPacket.pbi), through the client DLL -# and Tools\BakaShrotGetMessages: 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 "BakaShrotGenerateKeyPairs.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 BakaShrotGetMessages 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 "BakaShrotPushMessage.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) -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) -Node = kitchen -DefaultTopic = logs -PushTopics = logs;secret -ReadTopics = * -AllowQuery = 1 - -[BakaShrot.Client.lounge] -PublicKeys = $($L.Pub) -Node = lounge -DefaultTopic = logs -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`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 "BakaShrotGetMessages.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 "BakaShrotGetMessages.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 "BakaShrotGetMessages.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 "BakaShrotGetMessages.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 "BakaShrotGetMessages.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 "BakaShrotGetMessages.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 "BakaShrotGetMessages.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 "BakaShrotGetMessages.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 "BakaShrotGetMessages.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 "BakaShrotGetMessages.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 "BakaShrotGetMessages.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 "BakaShrotGetMessages.exe" @("secret", "kitchen", $Lounge)) "Not allowed to read topic 'secret'" 1 - Expect "Unknown node: refused" (Tool "BakaShrotGetMessages.exe" @("logs", "nobody", $Kitchen)) "Unknown node 'nobody'" 1 - Expect "Unknown topic: refused" (Tool "BakaShrotGetMessages.exe" @("nothing", "kitchen", $Kitchen)) "Unknown topic 'nothing'" 1 - $R = Tool "BakaShrotGetMessages.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 "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "-3", $Kitchen)) "Invalid --after" 1 - Expect "Unknown option: refused by the tool" (Tool "BakaShrotGetMessages.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 "BakaShrotGetMessages.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 "BakaShrotGetMessages.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 "BakaShrotGetMessages.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 "BakaShrotGetMessages.exe") ` - -ArgumentList "logs", "kitchen", "--after", "latest", "--follow", "--interval", "100", "`"$Kitchen`"" ` - -WorkingDirectory $Build -RedirectStandardOutput $FollowOut -WindowStyle Hidden -PassThru - $null = $Follower.Handle - Start-Sleep -Milliseconds 1500 - Check "--follow keeps running once caught up" (-not $Follower.HasExited) $(if ($Follower.HasExited) { "exited with $($Follower.ExitCode)" } else { "running" }) - - $null = Push '{"f":1}' $Kitchen - $null = Push '{"f":2}' $Kitchen - $null = Push '{"f":3}' $Kitchen - $D = (Get-Date).AddSeconds(10) - do { - Start-Sleep -Milliseconds 200 - $Lines = @() - try { - $Fs = [IO.File]::Open($FollowOut, "Open", "Read", "ReadWrite") - $Text = (New-Object IO.StreamReader($Fs)).ReadToEnd(); $Fs.Close() - $Lines = @($Text -split "`r?`n" | Where-Object { $_ -ne "" }) - } catch { } - } while ($Lines.Count -lt 3 -and (Get-Date) -lt $D) - Check "--follow --after latest: only the 3 new ones" ( - $Lines.Count -eq 3 -and $Lines[0] -eq "129`t{`"f`":1}" -and $Lines[2] -eq "131`t{`"f`":3}" - ) ($Lines -join " / ") - - # The server going away ends it with a failure. - Set-Content $Stop "x" - if (-not $P.WaitForExit(15000)) { Stop-Process -Id $P.Id -Force } - $Ended = $Follower.WaitForExit(15000) - Check "--follow fails once the server is gone" ($Ended -and $Follower.ExitCode -eq 1) $(if ($Ended) { "exit code $($Follower.ExitCode)" } else { "still running" }) - - $Log = Get-Content (Join-Path $Dir "server.log") -Raw - $Bad = @($Log -split "`r?`n" | Where-Object { $_ -match "invalid|unexpected|Failed" }) - Check "Server log: no invalid or unexpected packets" ($Bad.Count -eq 0) $(if ($Bad.Count) { $Bad -join " / " } else { "clean" }) -} -finally { - if ($Follower -and -not $Follower.HasExited) { Stop-Process -Id $Follower.Id -Force } - if (-not $P.HasExited) { - Set-Content $Stop "x" - if (-not $P.WaitForExit(15000)) { Stop-Process -Id $P.Id -Force } - } -} - -"" -if ($Fails -eq 0) { "All checks passed" } else { "$Fails check(s) failed" } -exit $(if ($Fails -eq 0) { 0 } else { 1 }) diff --git a/Tests/HandshakeTest.pb b/Tests/HandshakeTest.pb deleted file mode 100644 index e09ad54..0000000 --- a/Tests/HandshakeTest.pb +++ /dev/null @@ -1,177 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: HandshakeTest.pb -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; 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\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\ClientNode = "34"), "Hello's ClientNode survived") -Check(Bool(*ServerHello\ClientPubKeyB64 = "Q2xpZW50UHViS2V5"), "Hello's ClientPubKeyB64 survived") -Check(CompareMemory(@*ServerHello\ClientSessionKey[0], @ClientHello\ClientSessionKey[0], #BakaShrot_SessionKeySize), "Hello's ClientSessionKey survived") - - -; --- 2. Server -> Client: ChallengeRequest ---------------------------------- - -Check(Bool(CryptRandomData(@ServerChallenge\Nonce[0], #BakaShrot_NonceSize)), "Server generated a nonce") -CopyMemory(@ServerChallenge\Nonce[0], *ServerConnectionNonce, #BakaShrot_NonceSize) -ServerChallenge\ChallengeB64 = "U2VydmVyQ2hhbGxlbmdl" -Check(Bool(CryptRandomData(@ServerChallenge\ServerSessionKey[0], #BakaShrot_SessionKeySize)), "Server made a session key") -Check(Bool(CryptRandomData(@ServerChallenge\ServerSignature[0], #BakaShrot_HandshakeSignatureSize)), "Server made a placeholder signature") - -*Wire = BakaShrot_ChallengeRequestPacket_Encode(@ServerChallenge, @WireSize) -Check(Bool(*Wire), "Server encoded the challenge request") - -*View = MsgPackWrapMsgBuffer(*Wire, WireSize\i) -Check(Bool(*View), "Client wrapped the challenge request") -*ClientChallenge = BakaShrot_ChallengeRequestPacket_Decode(*View) -MsgPackFree(*View, #False) -FreeMemory(*Wire) - -Check(Bool(*ClientChallenge), "Client decoded the challenge request") -Check(Bool(*ClientChallenge\ChallengeB64 = "U2VydmVyQ2hhbGxlbmdl"), "Challenge's ChallengeB64 survived") -Check(CompareMemory(@*ClientChallenge\Nonce[0], *ServerConnectionNonce, #BakaShrot_NonceSize), "Challenge's nonce survived") -Check(CompareMemory(@*ClientChallenge\ServerSessionKey[0], @ServerChallenge\ServerSessionKey[0], #BakaShrot_SessionKeySize), "Challenge's ServerSessionKey survived") -Check(CompareMemory(@*ClientChallenge\ServerSignature[0], @ServerChallenge\ServerSignature[0], #BakaShrot_HandshakeSignatureSize), "Challenge's ServerSignature survived") - - -; --- 3. Client -> Server: ChallengeResponse --------------------------------- - -; Placeholder for the real signature of ChallengeB64 + Nonce. -ClientResponse\ChallengeResponseB64 = "U2lnbmVkOiAiU2VydmVyQ2hhbGxlbmdlIg==" -CopyMemory(@*ClientChallenge\Nonce[0], @ClientResponse\Nonce[0], #BakaShrot_NonceSize) - -*Wire = BakaShrot_ChallengeResponsePacket_Encode(@ClientResponse, @WireSize) -Check(Bool(*Wire), "Client encoded the challenge response") - -*View = MsgPackWrapMsgBuffer(*Wire, WireSize\i) -Check(Bool(*View), "Server wrapped the challenge response") -*ServerResponse = BakaShrot_ChallengeResponsePacket_Decode(*View) -MsgPackFree(*View, #False) - -Check(Bool(*ServerResponse), "Server decoded the challenge response") -Check(Bool(*ServerResponse\ChallengeResponseB64 = "U2lnbmVkOiAiU2VydmVyQ2hhbGxlbmdlIg=="), "Response's ChallengeResponseB64 survived") -Check(CompareMemory(@*ServerResponse\Nonce[0], *ServerConnectionNonce, #BakaShrot_NonceSize), "Server accepted the nonce it issued") - - -; --- 4. Replay: the same response sent on another connection ---------------- -; *Wire still holds the response captured in step 3. - -Check(Bool(CryptRandomData(*OtherConnectionNonce, #BakaShrot_NonceSize)), "Server generated a nonce for another connection") - -*View = MsgPackWrapMsgBuffer(*Wire, WireSize\i) -Check(Bool(*View), "Server wrapped the replayed response") -*ServerReplayed = BakaShrot_ChallengeResponsePacket_Decode(*View) -MsgPackFree(*View, #False) -FreeMemory(*Wire) - -Check(Bool(*ServerReplayed), "Replayed response is still a well-formed packet") -Check(Bool(Not CompareMemory(@*ServerReplayed\Nonce[0], *OtherConnectionNonce, #BakaShrot_NonceSize)), "Server rejected the replayed response's nonce") - - -; --- 5. A hello sent where a challenge response is expected ------------------ - -*Wire = BakaShrot_HelloPacket_Encode(@ClientHello, @WireSize) -Check(Bool(*Wire), "Client encoded a second hello") - -*View = MsgPackWrapMsgBuffer(*Wire, WireSize\i) -Check(Bool(*View), "Server wrapped the misplaced hello") -*ServerWrongType = BakaShrot_ChallengeResponsePacket_Decode(*View) -MsgPackFree(*View, #False) -FreeMemory(*Wire) - -Check(Bool(Not *ServerWrongType), "Challenge response decoder rejected a hello") - - -; --- Cleanup ----------------------------------------------------------------- - -FreeStructure(*ServerHello) -FreeStructure(*ClientChallenge) -FreeStructure(*ServerResponse) -FreeStructure(*ServerReplayed) -FreeMemory(*ServerConnectionNonce) -FreeMemory(*OtherConnectionNonce) -CloseCryptRandom() - -PrintN("") -PrintN("Handshake simulation passed.") -End 0 diff --git a/Tests/Names-Test.ps1 b/Tests/Names-Test.ps1 deleted file mode 100644 index b408476..0000000 --- a/Tests/Names-Test.ps1 +++ /dev/null @@ -1,478 +0,0 @@ -# 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 "BakaShrotGenerateKeyPairs.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 "BakaShrotQuery.exe" @("@$F", $Ini) -} - -$A = New-KeyPair; $B = New-KeyPair; $K = New-KeyPair; $G = New-KeyPair; $BC = New-KeyPair; $K2 = New-KeyPair; $R = New-KeyPair - -# --- Server A: new keys, logs = 1, sensors = 2 ----------------------------- -Set-Content (Join-Path $Dir "a.ini") -Encoding Ascii -Value @" -[BakaShrot] -PrivateKey = $($A.Priv) -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 -reader = 30 - -[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 -Node = serverB -PublicKey = $($B.Pub) -AcceptTopics = logs - -[BakaShrot.Client.b] -PublicKeys = $($B.Pub) -Node = serverB -DefaultTopic = logs - -[BakaShrot.Client.kitchen] -PublicKeys = $($K.Pub) -Node = kitchen -DefaultTopic = logs -PushTopics = logs;sensors* -ReadTopics = * -AllowQuery = 1 - -[BakaShrot.Client.kitchen2] -PublicKeys = $($K2.Pub) -Node = kitchen-2 -DefaultTopic = logs -PushTopics = logs;sensors.temp - -[BakaShrot.Client.garage] -PublicKeys = $($G.Pub) -Node = garage -DefaultTopic = logs - -; No DefaultTopic: its pushes must name their topic. -[BakaShrot.Client.reader] -PublicKeys = $($R.Pub) -Node = reader -PushTopics = logs -"@ - -# --- 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) -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 -NodeId = serverA -PublicKey = $($A.Pub) -AcceptTopics = logs;sensors;sensors.* -AcceptNodes = kitchen;blocal;kitchen-* -SendNodes = blocal;9 - -[BakaShrot.Client.a] -PublicKeys = $($A.Pub) -Node = serverA -DefaultTopic = logs - -; One key, three nodes: a section each. -[BakaShrot.Client.local] -PublicKeys = $($BC.Pub) -Node = blocal -DefaultTopic = sensors -PushTopics = sensors;logs;extra -ReadTopics = * -AllowQuery = 1 - -[BakaShrot.Client.local9] -PublicKeys = $($BC.Pub) -Node = 9 -DefaultTopic = logs -PushTopics = sensors;logs;extra -ReadTopics = * -AllowQuery = 1 - -[BakaShrot.Client.localsecret] -PublicKeys = $($BC.Pub) -Node = bsecret -DefaultTopic = logs -PushTopics = sensors;logs;extra -ReadTopics = * -AllowQuery = 1 -"@ -} -Write-B "7" - -# New key names, except garage's (NodeId, by id). No Topic: the server's -# DefaultTopic for each client says where its pushes go. -$ServerKeys = @{ 12401 = $A.Pub; 12402 = $B.Pub } -function Client-Ini($Name, $Keys, $Topic, $Node, $Port, [switch]$OldKeys) { - $P = Join-Path $Dir "$Name.ini" - $NK = "Node" - if ($OldKeys) { $NK = "NodeId" } - Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($Keys.Priv)`r`nPublicKey = $($Keys.Pub)`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 -$Reader = Client-Ini "reader" $R "logs" "reader" 12401 -# reader's key, but kitchen's node: its section only gives it reader. -$Impostor = Client-Ini "impostor" $R "logs" "kitchen" 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 "BakaShrotPushMessage.exe" @($M1, $Kitchen)) "message #1" - Expect "kitchen pushes into sensors by name" (Tool "BakaShrotPushMessage.exe" @("-t", "sensors", $M2, $Kitchen)) "message #1" - Expect "kitchen pushes into logs by id" (Tool "BakaShrotPushMessage.exe" @("-t", "1", $M2, $Kitchen)) "message #2" - Expect "kitchen can't push into secret" (Tool "BakaShrotPushMessage.exe" @("-t", "secret", $M1, $Kitchen)) "Not allowed to push to topic 'secret'" 1 - Expect "unknown topic refused, with its code" (Tool "BakaShrotPushMessage.exe" @("-t", "nope", $M1, $Kitchen)) "\(UnknownName\): Unknown topic 'nope'" 1 - Expect "garage (old keys, by ids 1:5) pushes into logs" (Tool "BakaShrotPushMessage.exe" @($M1, $Garage)) "message #1" - Expect "kitchen pushes into sensors.temp (PushTopics sensors*)" (Tool "BakaShrotPushMessage.exe" @("-t", "sensors.temp", $M2, $Kitchen)) "message #1" - Expect "kitchen-2 pushes into logs" (Tool "BakaShrotPushMessage.exe" @($M1, $Kitchen2)) "message #1" - Expect "kitchen-2 pushes into sensors.temp" (Tool "BakaShrotPushMessage.exe" @("-t", "sensors.temp", $M1, $Kitchen2)) "message #1" - Expect "kitchen-2 can't push into sensors" (Tool "BakaShrotPushMessage.exe" @("-t", "sensors", $M1, $Kitchen2)) "Not allowed to push to topic 'sensors'" 1 - - "--- Server A: identities (a node per key, the default topic the server's)" - Expect "reader (no DefaultTopic) can't push without naming a topic" (Tool "BakaShrotPushMessage.exe" @($M1, $Reader)) "\(NoDefaultTopic\): No default topic for this client" 1 - Expect "reader pushes when it names one" (Tool "BakaShrotPushMessage.exe" @("-t", "logs", $M1, $Reader)) "message #1" - Expect "reader's key can't write as kitchen" (Tool "BakaShrotPushMessage.exe" @("-t", "logs", $M1, $Impostor)) "Failed to connect and authenticate to [^ ]+ \(AuthRejected\)" 1 - - "--- Server A: reads and the read filter" - Expect "garage reads logs:kitchen by name" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "kitchen", $Garage)) "logs:kitchen#2 \(ids 1:2\)" - Expect "garage reads it by ids, case-insensitive name" (Tool "BakaShrotGetLatestMessage.exe" @("1", "KITCHEN", $Garage)) "logs:kitchen#2" - Expect "garage can't read sensors (default ReadTopics)" (Tool "BakaShrotGetLatestMessage.exe" @("sensors", "kitchen", $Garage)) "Not allowed to read topic 'sensors'" 1 - Expect "kitchen reads sensors (ReadTopics = *)" (Tool "BakaShrotGetLatestMessage.exe" @("sensors", "kitchen", $Kitchen)) "sensors:kitchen#1 \(ids 2:2\)" - - "--- Server A: resolving and listing" - Expect "kitchen resolves topic sensors" (Tool "BakaShrotResolveIds.exe" @("topic", "sensors", $Kitchen)) "topic sensors = 2" - Expect "kitchen resolves topic id 1" (Tool "BakaShrotResolveIds.exe" @("topic", "1", $Kitchen)) "topic logs = 1" - Expect "kitchen resolves node garage" (Tool "BakaShrotResolveIds.exe" @("node", "garage", $Kitchen)) "node garage = 5" - Expect "garage can't resolve sensors (no access)" (Tool "BakaShrotResolveIds.exe" @("topic", "sensors", $Garage)) "Unknown topic" 1 - Expect "kitchen can resolve secret (it may query)" (Tool "BakaShrotResolveIds.exe" @("topic", "secret", $Kitchen)) "topic secret = 3" - Expect "kitchen lists every topic (it may query)" (Tool "BakaShrotList.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 "BakaShrotList.exe" @("topics", $Garage)) "Topics \(1\): \|\s+1 logs" - Expect "the nodes, as JSON" (Tool "BakaShrotList.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 "BakaShrotGetLatestMessage.exe" @("logs", "kitchen", $Local)) "logs:kitchen#2 \(ids 200:7\)" - Expect "B has sensors:kitchen" (Tool "BakaShrotGetLatestMessage.exe" @("sensors", "kitchen", $Local)) "sensors:kitchen#1 \(ids 201:7\)" - Expect "B didn't get logs:garage (garage isn't named on B)" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "garage", $Local)) "Unknown node 'garage'" 1 - Expect "B took sensors.temp by AcceptTopics sensors.* (new topic id 65535)" (Tool "BakaShrotGetLatestMessage.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 "BakaShrotGetLatestMessage.exe" @("logs", "kitchen-2", $Local)) "logs:kitchen-2#1 \(ids 200:65535\)" - Expect "B: both new ones" (Tool "BakaShrotGetLatestMessage.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 "BakaShrotPushMessage.exe" @($M3, $Local)) "message #1" - Expect "B's local pushes into logs" (Tool "BakaShrotPushMessage.exe" @("-t", "logs", $M3, $Local)) "message #1" - Expect "B's local pushes into extra" (Tool "BakaShrotPushMessage.exe" @("-t", "extra", $M3, $Local)) "message #1" - Expect "B's unnamed node 9 pushes into logs" (Tool "BakaShrotPushMessage.exe" @($M3, $Anon)) "message #1" - Expect "B's bsecret pushes into logs" (Tool "BakaShrotPushMessage.exe" @($M3, $BSecret)) "message #1" - Start-Sleep -Seconds 4 - Expect "A got logs:blocal (ids 1:20)" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "blocal", $Kitchen)) 'logs:blocal#1 \(ids 1:20\), pushed \d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z \| \{"from":"b-local"\}' - Expect "A didn't get sensors:blocal (not accepted)" (Tool "BakaShrotGetLatestMessage.exe" @("sensors", "blocal", $Kitchen)) "No message" 1 - Expect "A didn't get logs:9 (unnamed)" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "9", $Kitchen)) "No message" 1 - Expect "A didn't get logs:bsecret (B's SendNodes)" (Tool "BakaShrotGetLatestMessage.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"\],\["logs","reader","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 " | " }) -$Ok = (Get-Content (Join-Path $Dir "a.log") -Raw) -match "isn't allowed to write as node kitchen with its public key" -if (-not $Ok) { $Fails++ } -"{0} A logged why the impostor was refused" -f $(if ($Ok) { "PASS" } else { "FAIL" }) -"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 "BakaShrotList.exe" @("nodes", $Local)) "\s+7 kitchen\s+config" -} finally { Stop-Srv $SB } - -"--- The old Identities (before protocol 5): refused at start, saying what to write" -(Get-Content (Join-Path $Dir "a.ini") -Raw) -replace "Node = garage\r?\nDefaultTopic = logs", "Identities = logs:garage" | Set-Content (Join-Path $Dir "old.ini") -Encoding Ascii -$SO = Start-Srv "old" -$Exited = $SO.P.WaitForExit(10000) -if (-not $Exited) { Stop-Srv $SO } -$Log = Get-Content (Join-Path $Dir "old.log") -Raw -$Ok = $Exited -and $SO.P.ExitCode -ne 0 -and $Log -match "write Node = garage and DefaultTopic = logs instead of Identities = logs:garage" -if (-not $Ok) { $Fails++ } -"{0} refused, with what to write instead`n -> {1}" -f $(if ($Ok) { "PASS" } else { "FAIL" }), (($Log -split "`n") | Select-String "Identities" | Select-Object -First 1) - -# --- C and D: topics listed without ids, no nodes listed at all ------------ -# The servers pick the ids, the nodes come from the sections (C's own, its -# peer's, its client's), D takes the client's node from C as it comes. -$C = New-KeyPair; $D = New-KeyPair; $KC = New-KeyPair -# LF line endings on purpose: the names sections are read by hand, the -# Preferences library misreads a bare name there (Config.pbi). -function Write-C([string]$Topics, [string]$Sync = "NORMAL") { -$Text = @" -[BakaShrot] -PrivateKey = $($C.Priv) -Node = serverC - -[BakaShrot.Topics] -$Topics - -[BakaShrot.Server] -Host = 127.0.0.1 -Port = 12401 -ReplicatingTopics = logs -DatabasePath = $(Join-Path $Dir "c.sqlite") -PeerSyncInterval = 1 -PeerRetryDelay = 1 -Synchronous = $Sync - -[BakaShrot.Peer.d] -Host = 127.0.0.1 -Port = 12402 -Node = serverD -PublicKey = $($D.Pub) - -[BakaShrot.Client.d] -PublicKeys = $($D.Pub) -Node = serverD -AllowWrite = 0 - -[BakaShrot.Client.kitchen] -PublicKeys = $($KC.Pub) -Node = kitchen -DefaultTopic = logs -ReadTopics = * -"@ -[IO.File]::WriteAllText((Join-Path $Dir "c.ini"), ($Text -replace "`r`n", "`n")) -} -Write-C "logs`nsensors" -Set-Content (Join-Path $Dir "d.ini") -Encoding Ascii -Value @" -[BakaShrot] -PrivateKey = $($D.Priv) -Node = serverD - -[BakaShrot.Topics] -logs - -[BakaShrot.Server] -Host = 127.0.0.1 -Port = 12402 -ReplicatingTopics = logs -DatabasePath = $(Join-Path $Dir "d.sqlite") -PeerSyncInterval = 1 -PeerRetryDelay = 1 - -[BakaShrot.Peer.c] -Host = 127.0.0.1 -Port = 12401 -Node = serverC -PublicKey = $($C.Pub) - -[BakaShrot.Client.c] -PublicKeys = $($C.Pub) -Node = serverC -AllowWrite = 0 - -[BakaShrot.Client.watcher] -PublicKeys = $($KC.Pub) -Node = watcher -ReadTopics = * -"@ -$ServerKeys[12401] = $C.Pub; $ServerKeys[12402] = $D.Pub -$KitchenC = Client-Ini "kitchen-c" $KC "logs" "kitchen" 12401 -$Watcher = Client-Ini "watcher" $KC "logs" "watcher" 12402 - -"--- C and D: names without ids" -$SC = Start-Srv "c"; $SD = Start-Srv "d" -try { - Wait-Port 12401 $SC; Wait-Port 12402 $SD - Expect "C gives the listed topics ids, in order" (Tool "BakaShrotList.exe" @("topics", $KitchenC)) "\s1 logs\s+config.*\s2 sensors\s+config" - Expect "C names its own, its peer's and its client's nodes" (Tool "BakaShrotList.exe" @("nodes", $KitchenC)) "\s1 serverC\s+config.*\s2 serverD\s+config.*\s3 kitchen\s+config" - Expect "kitchen pushes to its DefaultTopic" (Tool "BakaShrotPushMessage.exe" @($M1, $KitchenC)) "message #1" - $Deadline = (Get-Date).AddSeconds(15) - do { - $R = Tool "BakaShrotGetLatestMessage.exe" @("logs", "kitchen", $Watcher) - if ($R.Code -eq 0) { break } - Start-Sleep -Milliseconds 300 - } while ((Get-Date) -lt $Deadline) - Expect "D took logs:kitchen though it never named kitchen (AcceptNodes = * by default)" $R "logs:kitchen#1 \(ids 1:65535\)" -} finally { - Stop-Srv $SC; Stop-Srv $SD -} - -"--- C again, its topics reordered and a new one first: the ids stay" -Write-C "alpha`nsensors`nlogs" -$SC = Start-Srv "c" -try { - Wait-Port 12401 $SC - Expect "logs and sensors keep 1 and 2, alpha gets 3" (Tool "BakaShrotList.exe" @("topics", $KitchenC)) "\s1 logs\s+config.*\s2 sensors\s+config.*\s3 alpha\s+config" - Expect "kitchen's message still under logs" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "kitchen", $KitchenC)) "logs:kitchen#1 \(ids 1:3\)" -} finally { Stop-Srv $SC } - -"--- Synchronous: C ran with NORMAL, D with the default FULL, OFF is refused" -$Ok = ((Get-Content (Join-Path $Dir "c.log") -Raw) -match "is ready \(synchronous NORMAL\)") -and ((Get-Content (Join-Path $Dir "d.log") -Raw) -match "is ready \(synchronous FULL\)") -if (-not $Ok) { $Fails++ } -"{0} C logged NORMAL, D FULL" -f $(if ($Ok) { "PASS" } else { "FAIL" }) -Write-C "logs" "OFF" -$SO = Start-Srv "c" -$Exited = $SO.P.WaitForExit(10000) -if (-not $Exited) { Stop-Srv $SO } -$Log = Get-Content (Join-Path $Dir "c.log") -Raw -$Ok = $Exited -and $SO.P.ExitCode -ne 0 -and $Log -match "Synchronous = OFF isn't allowed" -if (-not $Ok) { $Fails++ } -"{0} Synchronous = OFF refused at start`n -> {1}" -f $(if ($Ok) { "PASS" } else { "FAIL" }), (($Log -split "`n") | Select-String "Synchronous" | Select-Object -First 1) - -"--- browse / browse_messages, as a database tool uses them (C stopped)" -$PythonExe = Get-Command python -ErrorAction SilentlyContinue -if ($PythonExe) { - Set-Content (Join-Path $Dir "browse.py") -Encoding Ascii -Value @' -import sqlite3, sys -db = sqlite3.connect(sys.argv[1]) -db.execute("PRAGMA foreign_keys = ON") # like SQLiteStudio -print("rows", db.execute("SELECT COUNT(*) FROM browse").fetchone()[0]) -db.execute("UPDATE browse SET topic = 'logs', node = NULL"); db.commit() -print("logs", db.execute("SELECT node, message_id, attachment_size FROM browse_messages").fetchall()) -db.execute("UPDATE browse SET topic = 'LOGS', node = 'kitchen'"); db.commit() -print("kitchen", db.execute("SELECT node, message_id FROM browse_messages").fetchall()) -try: - db.execute("UPDATE browse SET topic = 'nope'"); db.commit(); print("bad accepted") -except sqlite3.IntegrityError: - print("bad refused") -db.execute("UPDATE browse SET topic = 'sensors', node = NULL"); db.commit() -print("sensors", db.execute("SELECT COUNT(*) FROM browse_messages").fetchone()[0]) -'@ - $Out = (& $PythonExe.Source -B (Join-Path $Dir "browse.py") (Join-Path $Dir "c.sqlite") 2>&1) -join " | " - $Ok = $Out -eq "rows 1 | logs [('kitchen', 1, None)] | kitchen [('kitchen', 1)] | bad refused | sensors 0" - if (-not $Ok) { $Fails++ } - "{0} one row, a topic shows its messages, a node narrows them, an unknown topic is refused`n -> {1}" -f $(if ($Ok) { "PASS" } else { "FAIL" }), $Out -} else { - "SKIP browse: no python on the PATH" -} - -"" -if ($Fails -eq 0) { "ALL PASSED" } else { "$Fails FAILED"; exit 1 } diff --git a/Tests/Python-Test.ps1 b/Tests/Python-Test.ps1 deleted file mode 100644 index d8518e3..0000000 --- a/Tests/Python-Test.ps1 +++ /dev/null @@ -1,119 +0,0 @@ -# End-to-end test of the Python interactor (Interactors/Python/bakashrot.py): -# starts a server with an empty database and runs -# Interactors/Python/check_bakashrot.py against it, through Build\'s DLL, -# then Tests/wire_check.py: what goes over the wire is encrypted. -# Needs Build\ (Build.ps1), Build\Bench\BenchServer.exe (Bench-Replication.ps1, -# or compile Tests\Bench\BenchServer.pb into it) and a 64-bit Python 3.8+. -# Uses ports 12406 and 12407. -# Usage: powershell -ExecutionPolicy Bypass -File Tests\Python-Test.ps1 [-Python ] -param( - [string]$Build = (Join-Path $PSScriptRoot "..\Build"), - [string]$Python = "python" -) -$ErrorActionPreference = "Stop" -$Build = (Resolve-Path $Build).Path -$Dir = Join-Path $Build "_pythontest" -Remove-Item -Recurse -Force $Dir -ErrorAction SilentlyContinue -New-Item -ItemType Directory $Dir | Out-Null -$Server = Join-Path $Build "Bench\BenchServer.exe" -$Port = 12406 -$ProxyPort = 12407 - -function New-KeyPair { - $L = & (Join-Path $Build "BakaShrotGenerateKeyPairs.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) -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) -Node = kitchen -DefaultTopic = logs -PushTopics = logs;secret -ReadTopics = * -AllowQuery = 1 - -[BakaShrot.Client.lounge] -PublicKeys = $($L.Pub) -Node = lounge -DefaultTopic = logs -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`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 - - # Refusals are expected (the checks ask for them), their codes' names - # (QueryFailed, InvalidRequest) aren't problems. - $Bad = @(Get-Content (Join-Path $Dir "server.log") | Where-Object { $_ -notmatch "Refused a request" -and $_ -match "invalid|unexpected|Failed|decrypt|sealed" }) - if ($Bad.Count) { "FAIL Server log: $($Bad -join ' / ')"; $Code = 1 } else { "PASS Server log: no invalid or unexpected packets" } - - # The wire: encrypted, tampering and a wrong server key refused. Another - # key pair's public key plays the wrong server's. - "" - & $Python -B (Join-Path $PSScriptRoot "wire_check.py") (Join-Path $Build "BakaShrot_Client.dll") $Kitchen $ProxyPort $L.Pub - if ($LASTEXITCODE) { $Code = 1 } - Start-Sleep -Milliseconds 300 - $Log = Get-Content (Join-Path $Dir "server.log") - $Checks = [ordered]@{ - "Server log: the tampered packet didn't decrypt" = "sent a packet that doesn't decrypt" - "Server log: the hello for another server wasn't opened" = "hello that isn't sealed for this server" - } - foreach ($Name in $Checks.Keys) { - if (@($Log | Where-Object { $_ -match [regex]::Escape($Checks[$Name]) }).Count) { "PASS $Name" } else { "FAIL $Name"; $Code = 1 } - } -} -finally { - if (-not $P.HasExited) { - Set-Content $Stop "x" - if (-not $P.WaitForExit(15000)) { Stop-Process -Id $P.Id -Force } - } -} -exit $Code diff --git a/Tests/Restart-Test.ps1 b/Tests/Restart-Test.ps1 deleted file mode 100644 index 6cc521b..0000000 --- a/Tests/Restart-Test.ps1 +++ /dev/null @@ -1,280 +0,0 @@ -# End-to-end test of a server killed mid-traffic and restarted (a crash, -# not a clean stop): what it acknowledged survives, its ids carry on where -# they stopped, and the two servers catch up with each other both ways. -# -# Two linked servers, A and B, each with its own client node pushing -# (kitchen on A, garage on B: one writer per topic/node pair) through -# Tests/restart_pusher.py, as fast as acknowledgements come back: -# 1. B killed while both push; A keeps pushing while B is down; B -# restarted: every push it acknowledged is there, no gap, its next id -# follows, and both servers end up with the same messages. -# 2. B killed again a fraction of a second into that catch-up, restarted: -# still converges. -# 3. A killed while both push (the other direction), restarted: same. -# The servers are killed with Stop-Process -Force (TerminateProcess), like -# a crash. Synchronous is the default (FULL); a killed process loses -# nothing committed with NORMAL either, only a power loss would. -# -# Needs Build\ (Build.ps1), Build\Bench\BenchServer.exe, and Python 3 on the -# PATH (the pushers use Interactors/Python/bakashrot.py). Uses ports -# 12415-12416. -# Usage: powershell -ExecutionPolicy Bypass -File Tests\Restart-Test.ps1 - -param([string]$Build = (Join-Path $PSScriptRoot "..\Build"), [string]$Python = "python") - -$ErrorActionPreference = "Stop" -$Build = (Resolve-Path $Build).Path -$Dir = Join-Path $Build "_restarttest" -Remove-Item -Recurse -Force $Dir -ErrorAction SilentlyContinue -New-Item -ItemType Directory $Dir | Out-Null -$Server = Join-Path $Build "Bench\BenchServer.exe" -$Dll = Join-Path $Build "BakaShrot_Client.dll" -$Pusher = Join-Path $PSScriptRoot "restart_pusher.py" -$Fails = 0 - -$PythonExe = (Get-Command $Python -ErrorAction SilentlyContinue) -if (-not $PythonExe) { "FAIL no Python ($Python), the pushers need it"; exit 1 } -$PythonExe = $PythonExe.Source - -function New-KeyPair { - $L = & (Join-Path $Build "BakaShrotGenerateKeyPairs.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 Start-Srv($Name) { - $Stop = Join-Path $Dir "$Name.stop" - Remove-Item $Stop -ErrorAction SilentlyContinue - # Each run its own log, the previous ones are kept for a look. - $script:Runs[$Name] = 1 + [int]$script:Runs[$Name] - $P = Start-Process -FilePath $Server -ArgumentList "`"$(Join-Path $Dir "$Name.ini")`"", "`"$Stop`"" -WorkingDirectory $Dir ` - -RedirectStandardOutput (Join-Path $Dir ("{0}.{1}.log" -f $Name, $script:Runs[$Name])) -WindowStyle Hidden -PassThru - $null = $P.Handle - @{ P = $P; Stop = $Stop; Name = $Name } -} -function Stop-Srv($S) { - if ($S.P.HasExited) { return } - Set-Content $S.Stop "x" - if (-not $S.P.WaitForExit(15000)) { Stop-Process -Id $S.P.Id -Force } -} -function Kill-Srv($S) { - Stop-Process -Id $S.P.Id -Force - $null = $S.P.WaitForExit(10000) -} -function Wait-Port($Port, $S) { - $D = (Get-Date).AddSeconds(15) - while (-not (Test-Port $Port)) { - if ($S.P.HasExited) { throw "$($S.Name) exited" } - if ((Get-Date) -gt $D) { throw "$($S.Name) not listening" } - Start-Sleep -Milliseconds 100 - } -} -function Query($Sql, $Ini) { - $F = Join-Path $Dir ("q-" + [guid]::NewGuid().ToString("N") + ".sql"); Set-Content $F -Encoding Ascii -Value $Sql - $R = Tool "BakaShrotQuery.exe" @("@$F", $Ini) - Remove-Item $F - $R -} - -# A pusher in the background: Name's out file gets " " per -# acknowledged push, then STOPPED or ERR. -function Start-Pusher($Name, $Ini) { - $Out = Join-Path $Dir "$Name.out"; $Stop = Join-Path $Dir "$Name.stop" - Remove-Item $Out, $Stop -ErrorAction SilentlyContinue - $P = Start-Process -FilePath $PythonExe -ArgumentList "-B", "`"$Pusher`"", "`"$Dll`"", "`"$Ini`"", "`"$Stop`"", "`"$Out`"", $Name ` - -WorkingDirectory $Build -WindowStyle Hidden -PassThru - $null = $P.Handle - @{ P = $P; Out = $Out; Stop = $Stop; Name = $Name } -} -function Stop-Pusher($Pu) { - Set-Content $Pu.Stop "x" - if (-not $Pu.P.WaitForExit(15000)) { Stop-Process -Id $Pu.P.Id -Force } -} -# What a pusher saw: how many acknowledged, the last id and seq, how it ended. -function Read-Pusher($Pu) { - $Lines = @(Get-Content $Pu.Out -ErrorAction SilentlyContinue) - $Acked = @($Lines | Where-Object { $_ -match "^\d+ \d+$" }) - $Last = if ($Acked.Count) { $Acked[-1] -split " " } else { @("0", "0") } - @{ Count = $Acked.Count; LastId = [int64]$Last[0]; LastSeq = [int]$Last[1]; End = [string]($Lines | Select-Object -Last 1) } -} - -# Every node of logs on a server: count, first and last id, and sums over -# the data and the push times, to compare two servers. -$StatsSql = "SELECT node, COUNT(*), MIN(message_id), MAX(message_id), SUM(length(message_data)), SUM(pushed_at % 1000003), SUM(message_id * length(message_data)) FROM messages WHERE topic = 'logs' GROUP BY node ORDER BY node" -function Stats($Ini) { - $R = Query $StatsSql $Ini - if ($R.Code -ne 0) { return "query failed: " + $R.Out } - ($R.Out -replace '^.*"rows":', '') -} -# The highest id and the count of a node on a server. -function Head($Node, $Ini) { - $R = Query "SELECT COUNT(*), COALESCE(MAX(message_id), 0) FROM messages WHERE topic = 'logs' AND node = '$Node'" $Ini - if ($R.Out -match '\[\["(\d+)","(\d+)"\]\]') { @{ Count = [int64]$Matches[1]; Max = [int64]$Matches[2] } } else { @{ Count = -1; Max = -1; Out = $R.Out } } -} -# Waits until A and B have the same messages, and at least Kitchen and -# Garage messages of each node. Returns the stats, and whether they matched. -function Wait-Converged($Kitchen, $Garage, $Seconds = 60) { - $D = (Get-Date).AddSeconds($Seconds) - do { - $SA = Stats $OnA; $SB = Stats $OnB - $HK = Head "kitchen" $OnB; $HG = Head "garage" $OnA - if ($SA -eq $SB -and $HK.Count -ge $Kitchen -and $HG.Count -ge $Garage) { return @{ Ok = $true; A = $SA; B = $SB } } - Start-Sleep -Milliseconds 250 - } while ((Get-Date) -lt $D) - @{ Ok = $false; A = $SA; B = $SB } -} -# What a restarted server must show for the node its pusher wrote to: every -# acknowledged push there (ids 1..max without a gap, max at least the last -# acknowledged one, its data the one acknowledged), and at most one more -# (committed, the answer lost with the kill). Leaves the node's head in -# $Survived: a function's return value would take its PASS/FAIL lines too. -function Check-Survived($What, $Node, $Pu, $Ini) { - $Seen = Read-Pusher $Pu - $H = Head $Node $Ini - Check "$What`: every acknowledged push survived, ids without a gap" ` - ($Seen.LastId -gt 0 -and $H.Count -eq $H.Max -and $H.Max -ge $Seen.LastId -and $H.Max -le $Seen.LastId + 1) ` - ("{0} acknowledged, last #{1}; stored {2}, last #{3}; pusher: {4}" -f $Seen.Count, $Seen.LastId, $H.Count, $H.Max, $Seen.End) - $R = Query "SELECT message_data FROM messages WHERE topic = 'logs' AND node = '$Node' AND message_id = $($Seen.LastId)" $Ini - Check "$What`: the last acknowledged one is the one pushed" ($R.Out -match ('\\"seq\\":' + $Seen.LastSeq + '[,}]')) $R.Out - $script:Survived = $H -} - -$A = New-KeyPair; $B = New-KeyPair; $K = New-KeyPair; $G = New-KeyPair -$Runs = @{} - -# Topics listed by name, nodes from the sections: a restart must give every -# name its id back, by the database. -function Write-Config($Name, $Keys, $Port, $Node, $PeerName, $PeerPort, $PeerNode, $PeerKey, $ClientNode, $ClientKey) { - Set-Content (Join-Path $Dir "$Name.ini") -Encoding Ascii -Value @" -[BakaShrot] -PrivateKey = $($Keys.Priv) -Node = $Node - -[BakaShrot.Topics] -logs - -[BakaShrot.Server] -Host = 127.0.0.1 -Port = $Port -ReplicatingTopics = logs -DatabasePath = $(Join-Path $Dir "$Name.sqlite") -PeerSyncInterval = 1 -PeerRetryDelay = 1 -PeerBatchSize = 10 - -[BakaShrot.Peer.$PeerName] -Host = 127.0.0.1 -Port = $PeerPort -Node = $PeerNode -PublicKey = $PeerKey - -[BakaShrot.Client.$PeerName] -PublicKeys = $PeerKey -Node = $PeerNode -AllowWrite = 0 - -[BakaShrot.Client.$ClientNode] -PublicKeys = $ClientKey -Node = $ClientNode -DefaultTopic = logs -ReadTopics = * -AllowQuery = 1 -"@ -} -Write-Config "a" $A 12415 "serverA" "b" 12416 "serverB" $B.Pub "kitchen" $K.Pub -Write-Config "b" $B 12416 "serverB" "a" 12415 "serverA" $A.Pub "garage" $G.Pub -Set-Content (Join-Path $Dir "kitchen.ini") -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($K.Priv)`r`nPublicKey = $($K.Pub)`r`nNode = kitchen`r`nServerHost = 127.0.0.1`r`nServerPort = 12415`r`nServerPublicKey = $($A.Pub)" -Set-Content (Join-Path $Dir "garage.ini") -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($G.Priv)`r`nPublicKey = $($G.Pub)`r`nNode = garage`r`nServerHost = 127.0.0.1`r`nServerPort = 12416`r`nServerPublicKey = $($B.Pub)" -$OnA = Join-Path $Dir "kitchen.ini"; $OnB = Join-Path $Dir "garage.ini" -Set-Content (Join-Path $Dir "next.json") -Encoding Ascii -Value '{"after":"restart"}' -$Next = "@" + (Join-Path $Dir "next.json") - -$SA = Start-Srv "a"; $SB = Start-Srv "b" -$Pushers = @() -try { - Wait-Port 12415 $SA; Wait-Port 12416 $SB - - "--- 1. B killed while both push, A keeps pushing, B restarted" - $PK = Start-Pusher "kitchen-1" $OnA; $PG = Start-Pusher "garage-1" $OnB; $Pushers += $PK, $PG - Start-Sleep -Seconds 3 - Kill-Srv $SB - $null = $PG.P.WaitForExit(15000) - Start-Sleep -Seconds 3 # A goes on alone - Stop-Pusher $PK - $KSeen = Read-Pusher $PK - # 104 (ConnectionLost) if killed during a push, 100 (NotConnected) if - # between two: the next push finds the connection already gone. - Check "the garage pusher noticed B was gone: ConnectionLostError, code 104 or 100" ($PG.P.HasExited -and (Read-Pusher $PG).End -match "^ERR 10[04] ConnectionLostError") (Read-Pusher $PG).End - Check "kitchen kept pushing on A meanwhile" ($KSeen.Count -gt 100 -and $KSeen.End -eq "STOPPED") ("{0} acknowledged" -f $KSeen.Count) - - $SB = Start-Srv "b"; Wait-Port 12416 $SB - Check-Survived "B" "garage" $PG $OnB - $HG = $Survived - $R = Tool "BakaShrotPushMessage.exe" @($Next, $OnB) - Check "B: the next push carries on from the last id" ($R.Out -match "message #$($HG.Max + 1)\b") ("after #{0}: {1}" -f $HG.Max, $R.Out) - $C = Wait-Converged $KSeen.LastId ($HG.Max + 1) - Check "A and B converged (B caught up on kitchen, A on garage)" $C.Ok ("A {0}`n B {1}" -f $C.A, $C.B) - - "--- 2. B killed again in the middle of its catch-up" - $Before = (Head "kitchen" $OnB).Count - $PK = Start-Pusher "kitchen-2" $OnA; $Pushers += $PK - Start-Sleep -Seconds 1 - Kill-Srv $SB - Start-Sleep -Seconds 6 # a backlog for B - Stop-Pusher $PK - $Total = (Head "kitchen" $OnA).Max - $SB = Start-Srv "b"; Wait-Port 12416 $SB - # Killed as soon as some of the backlog is in, not all of it. - $D = (Get-Date).AddSeconds(30) - do { - $Mid = Head "kitchen" $OnB - if ($Mid.Count -gt $Before -and $Mid.Count -lt $Total) { Kill-Srv $SB; break } - Start-Sleep -Milliseconds 20 - } while ($Mid.Count -lt $Total -and (Get-Date) -lt $D) - Check "B killed partway through its catch-up" ($Mid.Count -gt $Before -and $Mid.Count -lt $Total) ` - ("B had {0} kitchen messages before, {1} when killed, A {2}" -f $Before, $Mid.Count, $Total) - if (-not $SB.P.HasExited) { Kill-Srv $SB } - $SB = Start-Srv "b"; Wait-Port 12416 $SB - $C = Wait-Converged $Total 0 - Check "B restarted, still converged" $C.Ok ("A {0}`n B {1}" -f $C.A, $C.B) - $H = Head "kitchen" $OnB - Check "B's copy of kitchen has no gap" ($H.Count -eq $H.Max -and $H.Max -eq $Total) ("{0} stored, last #{1}, A's last #{2}" -f $H.Count, $H.Max, $Total) - - "--- 3. A killed while both push, B keeps pushing, A restarted" - $PK = Start-Pusher "kitchen-3" $OnA; $PG = Start-Pusher "garage-3" $OnB; $Pushers += $PK, $PG - Start-Sleep -Seconds 3 - Kill-Srv $SA - $null = $PK.P.WaitForExit(15000) - Start-Sleep -Seconds 3 # B goes on alone - Stop-Pusher $PG - $GSeen = Read-Pusher $PG - Check "the kitchen pusher noticed A was gone: ConnectionLostError, code 104 or 100" ($PK.P.HasExited -and (Read-Pusher $PK).End -match "^ERR 10[04] ConnectionLostError") (Read-Pusher $PK).End - - $SA = Start-Srv "a"; Wait-Port 12415 $SA - Check-Survived "A" "kitchen" $PK $OnA - $HK = $Survived - $R = Tool "BakaShrotPushMessage.exe" @($Next, $OnA) - Check "A: the next push carries on from the last id" ($R.Out -match "message #$($HK.Max + 1)\b") ("after #{0}: {1}" -f $HK.Max, $R.Out) - $C = Wait-Converged ($HK.Max + 1) $GSeen.LastId - Check "A and B converged again" $C.Ok ("A {0}`n B {1}" -f $C.A, $C.B) - - "--- Logs" - $Bad = @(Get-ChildItem $Dir -Filter "*.log" | Select-String "Failed|refused|corrupt|malformed" | Where-Object { $_.Line -notmatch "Failed to connect|Lost the link|link to .* failed" }) - Check "no failure in either server's logs, other than the links lost to the kills" ($Bad.Count -eq 0) $(if ($Bad.Count) { ($Bad | Select-Object -First 5 | ForEach-Object { "$($_.Filename): $($_.Line)" }) -join " | " } else { "none" }) -} finally { - foreach ($Pu in $Pushers) { if (-not $Pu.P.HasExited) { Stop-Process -Id $Pu.P.Id -Force } } - Stop-Srv $SA; Stop-Srv $SB -} - -"" -if ($Fails) { "$Fails FAILED"; exit 1 } else { "All passed" } diff --git a/Tests/Retention-Test.ps1 b/Tests/Retention-Test.ps1 deleted file mode 100644 index b347916..0000000 --- a/Tests/Retention-Test.ps1 +++ /dev/null @@ -1,353 +0,0 @@ -# End-to-end test of pushed_at and [BakaShrot.Retention]: -# - a database from before pushed_at gets it (the time of the upgrade), and -# its ids go on; -# - a push is stamped with the time it arrived (UTC), BakaShrotGetMessages -# --time and BakaShrotGetLatestMessage show it, replication carries it as is; -# - each server deletes a topic's messages past its own max age (by name, -# by pattern, "*"), only its own: the peer keeps its copies; -# - after deleting, ids go on, and the peer doesn't send them again; -# - what a peer replicates already past the max age isn't stored, but -# counts as received: not sent again; -# - an age without a unit is refused at start. -# Two linked servers, A (port 12408) and B (12409). -# Needs Build\ (Build.ps1), Build\Bench\BenchServer.exe (or compile -# Tests\Bench\BenchServer.pb into it), and Python 3 for the old database -# (skipped without it). -# Usage: powershell -ExecutionPolicy Bypass -File Tests\Retention-Test.ps1 [-Python ] -param( - [string]$Build = (Join-Path $PSScriptRoot "..\Build"), - [string]$Python = "python" -) -$ErrorActionPreference = "Stop" -$Build = (Resolve-Path $Build).Path -$Dir = Join-Path $Build "_retentiontest" -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 "BakaShrotGenerateKeyPairs.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 " | "); Lines = @($O | Where-Object { "$_" -ne "" }) } -} -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) { - Check $What (($Result.Code -eq $Code) -and ($Result.Out -match $Pattern)) ("[{0}] {1}" -f $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) { - if ($S.P.HasExited) { return } - 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 "BakaShrotQuery.exe" @("@$F", $Ini) -} -# Waits until Sql answers something matching Pattern, for up to Seconds. -function Wait-Query($Sql, $Ini, $Pattern, $Seconds = 20) { - $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 -} -function Count($Topic, $Where = "") { - "SELECT COUNT(*) AS n FROM messages WHERE topic = '$Topic' AND node = 'kitchen' $Where" -} -function NowMs { [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() } -# Pushes Data from a file (PowerShell 5 strips the quotes of an argument). -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 "BakaShrotPushMessage.exe" ($A + @("@$F", $Ini)) -} - -$A = New-KeyPair; $B = New-KeyPair; $K = New-KeyPair - -# A: short is kept 3 s here, everything else forever. Checked every second. -Set-Content (Join-Path $Dir "a.ini") -Encoding Ascii -Value @" -[BakaShrot] -PrivateKey = $($A.Priv) -Node = serverA - -[BakaShrot.Topics] -logs = 1 -short = 2 -keep = 3 -late = 4 - -[BakaShrot.Nodes] -serverA = 10 -serverB = 11 -kitchen = 2 - -[BakaShrot.Retention] -short = 3s - -[BakaShrot.Server] -Host = 127.0.0.1 -Port = 12408 -ReplicatingTopics = logs;short;keep;late -DatabasePath = $(Join-Path $Dir "a.sqlite") -PeerSyncInterval = 1 -PeerRetryDelay = 1 -RetentionInterval = 1 - -[BakaShrot.Peer.b] -Host = 127.0.0.1 -Port = 12409 -Node = serverB -PublicKey = $($B.Pub) - -[BakaShrot.Client.b] -PublicKeys = $($B.Pub) -Node = serverB -DefaultTopic = logs - -[BakaShrot.Client.kitchen] -PublicKeys = $($K.Pub) -Node = kitchen -DefaultTopic = logs -PushTopics = logs;short;keep;late -ReadTopics = * -AllowQuery = 1 -"@ - -# B: other ids. short forever, keep by a pattern (4 s), the rest 1 h. -Set-Content (Join-Path $Dir "b.ini") -Encoding Ascii -Value @" -[BakaShrot] -PrivateKey = $($B.Priv) -Node = serverB - -[BakaShrot.Topics] -logs = 300 -short = 301 -keep = 302 -late = 303 - -[BakaShrot.Nodes] -serverA = 1 -serverB = 2 -kitchen = 30 - -[BakaShrot.Retention] -short = forever -ke* = 4s -late = 3s -* = 1h - -[BakaShrot.Server] -Host = 127.0.0.1 -Port = 12409 -ReplicatingTopics = logs;short;keep;late -DatabasePath = $(Join-Path $Dir "b.sqlite") -PeerSyncInterval = 1 -PeerRetryDelay = 1 -RetentionInterval = 1 - -[BakaShrot.Peer.a] -Host = 127.0.0.1 -Port = 12408 -Node = serverA -PublicKey = $($A.Pub) - -[BakaShrot.Client.a] -PublicKeys = $($A.Pub) -Node = serverA -DefaultTopic = logs - -[BakaShrot.Client.kitchen] -PublicKeys = $($K.Pub) -Node = kitchen -DefaultTopic = logs -ReadTopics = * -AllowQuery = 1 -"@ - -$ServerKeys = @{ 12408 = $A.Pub; 12409 = $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`nNode = kitchen`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($ServerKeys[$Port])" - $P -} -$OnA = Client-Ini "kitchen-a" 12408 -$OnB = Client-Ini "kitchen-b" 12409 - -# A database from before pushed_at, for A: one message, logs:kitchen #1. -$HasOld = $false -$Seed = @" -import sqlite3, sys -db = sqlite3.connect(sys.argv[1]) -db.execute("CREATE TABLE 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))") -db.execute("INSERT INTO data (topic_id, node_id, message_id, message_data) VALUES (1, 2, 1, '{\"old\":1}')") -db.commit() -"@ -Set-Content (Join-Path $Dir "seed.py") -Encoding Ascii -Value $Seed -try { - & $Python -B (Join-Path $Dir "seed.py") (Join-Path $Dir "a.sqlite") 2>&1 | Out-Null - $HasOld = ($LASTEXITCODE -eq 0) -} catch { $HasOld = $false } -if (-not $HasOld) { "SKIP the old database: no Python ($Python)" ; Remove-Item (Join-Path $Dir "a.sqlite") -ErrorAction SilentlyContinue } - -foreach ($Port in 12408, 12409) { if (Test-Port $Port) { throw "Port $Port is already in use" } } -$Before = NowMs -$SA = Start-Srv "a"; $SB = $null -try { - Wait-Port 12408 $SA - "--- Before B starts: late #1-#2 on A, past B's 3 s once B gets them" - foreach ($i in 1..2) { Expect "push late #$i" (Push "{`"late`":$i}" $OnA "late") "message #$i" } - Start-Sleep -Seconds 5 - $SB = Start-Srv "b" - Wait-Port 12409 $SB - Start-Sleep -Seconds 2 - - "--- The old database" - if ($HasOld) { - $R = Query "SELECT message_id, pushed_at FROM data WHERE topic_id = 1 AND node_id = 2" $OnA - $Stamp = 0; if ($R.Out -match '\[\["1","(\d+)"\]\]') { $Stamp = [int64]$Matches[1] } - Check "the old message got pushed_at: the time of the upgrade" ($Stamp -ge $Before - 1000 -and $Stamp -le (NowMs)) $R.Out - Expect "its ids go on: the next push is #2" (Push '{"n":"after upgrade"}' $OnA) "message #2" - } else { - Expect "first push" (Push '{"n":"first"}' $OnA) "message #1" - Expect "second push" (Push '{"n":"after upgrade"}' $OnA) "message #2" - } - - "--- pushed_at" - $PushedFrom = NowMs - Expect "push logs #3" (Push '{"n":"stamped"}' $OnA) "message #3" - $PushedTo = NowMs - $R = Query "SELECT pushed_at, pushed_utc FROM messages WHERE topic = 'logs' AND node = 'kitchen' AND message_id = 3" $OnA - $Stamp = 0; if ($R.Out -match '\[\["(\d+)","([^"]+)"\]\]') { $Stamp = [int64]$Matches[1]; $Utc = $Matches[2] } - Check "stamped with the time it arrived, in UTC ms" ($Stamp -ge $PushedFrom - 50 -and $Stamp -le $PushedTo + 50) "$Stamp in [$PushedFrom, $PushedTo]" - $Expected = [DateTimeOffset]::FromUnixTimeMilliseconds($Stamp).UtcDateTime.ToString("yyyy-MM-ddTHH:mm:ss.fffZ") - Check "the view's pushed_utc is the same, as text" ($Utc -eq $Expected) "$Utc, expected $Expected" - - $R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "2", "--time", $OnA) - Check "BakaShrotGetMessages --time: id, time, data" ($R.Code -eq 0 -and $R.Lines.Count -eq 1 -and $R.Lines[0] -eq "3`t$Expected`t{`"n`":`"stamped`"}") $R.Out - $R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "2", $OnA) - Check "BakaShrotGetMessages without --time: as before" ($R.Code -eq 0 -and $R.Lines.Count -eq 1 -and $R.Lines[0] -eq "3`t{`"n`":`"stamped`"}") $R.Out - Expect "BakaShrotGetLatestMessage shows it" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "kitchen", $OnA)) ("#3 \(ids 1:2\), pushed " + [regex]::Escape($Expected)) - - $Sql = "SELECT message_id, pushed_at FROM messages WHERE topic = 'logs' AND node = 'kitchen' ORDER BY message_id" - $OnAStamps = (Query $Sql $OnA).Out - $R = Wait-Query $Sql $OnB '"3","\d+"' - Check "replicated with the same pushed_at, every one" ($R.Out -eq $OnAStamps) "A $OnAStamps | B $($R.Out)" - Expect "BakaShrotGetLatestMessage on B: the same time" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "kitchen", $OnB)) ("#3 \(ids 300:30\), pushed " + [regex]::Escape($Expected)) - - "--- Retention on A (short = 3s), not on B (short = forever)" - foreach ($i in 1..3) { Expect "push short #$i" (Push "{`"short`":$i}" $OnA "short") "message #$i" } - $R = Wait-Query (Count "short") $OnB '\[\["3"\]\]' 10 - Check "B got the 3 short ones" ($R.Out -match '\[\["3"\]\]') $R.Out - $R = Wait-Query (Count "short") $OnA '\[\["0"\]\]' 10 - Check "A deleted them past 3 s" ($R.Out -match '\[\["0"\]\]') $R.Out - Expect "A kept logs (no max age)" (Query (Count "logs") $OnA) '\[\["3"\]\]' - Expect "B kept them (its own rules)" (Query (Count "short") $OnB) '\[\["3"\]\]' - Expect "A: no message left in short" (Tool "BakaShrotGetLatestMessage.exe" @("short", "kitchen", $OnA)) "No message" 1 - Expect "A's ids go on after deleting: #4" (Push '{"short":4}' $OnA "short") "message #4" - $R = Wait-Query (Count "short") $OnB '\[\["4"\]\]' 10 - Check "B got #4" ($R.Out -match '\[\["4"\]\]') $R.Out - Start-Sleep -Seconds 3 - Expect "B didn't send A back what A deleted" (Query (Count "short" "AND message_id <= 3") $OnA) '\[\["0"\]\]' - - "--- Retention on B by pattern (ke* = 4s), not on A" - foreach ($i in 1..2) { Expect "push keep #$i" (Push "{`"keep`":$i}" $OnA "keep") "message #$i" } - $R = Wait-Query (Count "keep") $OnB '\[\["2"\]\]' 10 - Check "B got the 2 keep ones" ($R.Out -match '\[\["2"\]\]') $R.Out - $R = Wait-Query (Count "keep") $OnB '\[\["0"\]\]' 10 - Check "B deleted them past 4 s" ($R.Out -match '\[\["0"\]\]') $R.Out - Expect "A kept them" (Query (Count "keep") $OnA) '\[\["2"\]\]' - Expect "push keep #3" (Push '{"keep":3}' $OnA "keep") "message #3" - $R = Wait-Query (Count "keep") $OnB '\[\["1"\]\]' 10 - Check "B only got #3, not #1 and #2 again" ($R.Out -match '\[\["1"\]\]') $R.Out - Expect "B: it's #3" (Tool "BakaShrotGetLatestMessage.exe" @("keep", "kitchen", $OnB)) "keep:kitchen#3" - Expect "B's * = 1h keeps logs" (Query (Count "logs") $OnB) '\[\["3"\]\]' - - "--- Replicated already past the max age (B: late = 3s)" - $Head = "SELECT h.max_message_id FROM node_heads h JOIN topics t ON t.topic_id = h.topic_id WHERE t.name = 'late'" - $R = Wait-Query $Head $OnB '\[\["2"\]\]' 10 - Check "B counts late #1-#2 as received (its head is 2)" ($R.Out -match '\[\["2"\]\]') $R.Out - Expect "but didn't store them" (Query (Count "late") $OnB) '\[\["0"\]\]' - Expect "A has them" (Query (Count "late") $OnA) '\[\["2"\]\]' - Expect "push late #3, fresh" (Push '{"late":3}' $OnA "late") "message #3" - $R = Wait-Query $Head $OnB '\[\["3"\]\]' 10 - Check "B got #3" ($R.Out -match '\[\["3"\]\]') $R.Out - # Stored, then deleted 3 s later by the pass, alone: #1-#2 never were. - $D = (Get-Date).AddSeconds(10) - while ((Get-Date) -lt $D -and -not ((Get-Content (Join-Path $Dir "b.log") -Raw) -match "deleted 1 messages of topic 'late'")) { Start-Sleep -Milliseconds 250 } - Check "B stored #3, and deleted it alone past 3 s" ((Get-Content (Join-Path $Dir "b.log") -Raw) -match "deleted 1 messages of topic 'late'") "checked" - Start-Sleep -Seconds 2 -} -finally { - Stop-Srv $SA; if ($SB) { Stop-Srv $SB } -} - -"--- Logs" -$LogA = Get-Content (Join-Path $Dir "a.log") -Raw -$LogB = Get-Content (Join-Path $Dir "b.log") -Raw -# How many messages of Topic a log says were deleted. Pushed a few ms apart, -# they can fall on both sides of a retention check (every 1 s), and be -# deleted over two of them. -function Count-Deleted($Log, $Topic) { - $N = 0 - foreach ($M in [regex]::Matches($Log, "Retention: deleted (\d+) messages of topic '$Topic' pushed before \d{4}-")) { $N += [int]$M.Groups[1].Value } - $N -} -Check "A logged its rule" ($LogA -match "Retention: short = 3s") "checked" -$N = Count-Deleted $LogA "short" -Check "A logged what it deleted: short #1-#3, maybe #4 since" ($N -ge 3) "$N deleted" -Check "B logged its rules" ($LogB -match "Retention: ke\* = 4s" -and $LogB -match "Retention: \* = 1h") "checked" -$N = Count-Deleted $LogB "keep" -Check "B deleted keep: #1-#2, maybe #3 since" ($N -ge 2) "$N deleted" -Check "B never sent A short messages (A is ahead, deleted or not)" (-not ($LogB -match "Sent \d+ messages of short")) "checked" -Check "A sent B late once each: #1-#2, then #3 alone" (([regex]::Matches($LogA, "Sent 2 messages of late:kitchen")).Count -eq 1 -and ([regex]::Matches($LogA, "Sent 1 messages of late:kitchen")).Count -eq 1) "checked" -Check "B never stored late #1-#2" (-not ($LogB -match "deleted [23] messages of topic 'late'")) "checked" -Check "A sent B keep twice: #1-#2, then #3 alone" ($LogA -match "Sent 2 messages of keep:kitchen" -and $LogA -match "Sent 1 messages of keep:kitchen" -and -not ($LogA -match "Sent 3 messages of keep")) "checked" -# A tries to link to B in the 5 s before B starts: those are expected. -$LinkTries = @([regex]::Matches($LogA, "Failed to link to 'b'")).Count -Check "A only failed to link to B before B started" ($LinkTries -le 8) "$LinkTries tries" -$LogAOther = ($LogA -split "`r?`n" | Where-Object { $_ -notmatch "Failed to link to 'b'|Retrying 'b'" }) -join "`n" -foreach ($P in @("Failed", "invalid", "unexpected", "doesn't decrypt")) { - Check "no '$P' in A's or B's log" (-not ($LogAOther -match [regex]::Escape($P)) -and -not ($LogB -match [regex]::Escape($P))) "checked" -} - -"--- An age without a unit" -(Get-Content (Join-Path $Dir "a.ini") -Raw) -replace "short = 3s", "short = 30" | Set-Content (Join-Path $Dir "bad.ini") -Encoding Ascii -$SBad = Start-Srv "bad" -$Exited = $SBad.P.WaitForExit(10000) -if (-not $Exited) { Stop-Srv $SBad } -$LogBad = Get-Content (Join-Path $Dir "bad.log") -Raw -Check "refused at start" ($Exited -and $SBad.P.ExitCode -ne 0 -and $LogBad -match "short = '30' isn't an age") $LogBad.Trim() - -"" -if ($Fails) { "$Fails FAILED"; exit 1 } else { "All passed" } diff --git a/Tests/restart_pusher.py b/Tests/restart_pusher.py deleted file mode 100644 index 91c2ff2..0000000 --- a/Tests/restart_pusher.py +++ /dev/null @@ -1,36 +0,0 @@ -"""Pushes as fast as the server acknowledges, for Tests/Restart-Test.ps1. - -Usage: restart_pusher.py -Pushes {"by": tag, "seq": n} to the client's DefaultTopic until the stop -file exists, writing " " to the out file once each push is -acknowledged. Ends with "STOPPED", or "ERR " when the server -goes away (the test kills it; code 104, ConnectionLost, during a push, or -100, NotConnected, between two): what was -acknowledged before is what must survive. -""" - -import os -import sys - -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, stop_path, out_path, tag = sys.argv[1:6] - -client = Client.from_ini(ini_path, dll_path) -with open(out_path, "a", buffering=1) as out: - try: - client.connect() - seq = 0 - while not os.path.exists(stop_path): - seq += 1 - message_id = client.push({"by": tag, "seq": seq}) - out.write(f"{message_id} {seq}\n") - out.write("STOPPED\n") - except BakaShrotError as error: - out.write(f"ERR {int(error.code)} {type(error).__name__}: {error}\n") - finally: - try: - client.close() - except BakaShrotError: - pass diff --git a/Tests/wire_check.py b/Tests/wire_check.py deleted file mode 100644 index 0bb2f2b..0000000 --- a/Tests/wire_check.py +++ /dev/null @@ -1,147 +0,0 @@ -"""What goes over the wire, run by Tests/Python-Test.ps1. - -Puts a TCP proxy between the client (BakaShrot_Client.dll, through -Interactors/Python/bakashrot.py) and the server, recording every byte, then -checks that: - - a pushed message, the client's identity and its topic never show up in - plain text, either way, handshake included; - - the message still makes it through and back; - - a byte flipped by the proxy after the handshake drops the connection; - - a client given another server's public key can't connect. - -Usage: wire_check.py -Exits with 0 if every check passed, 1 otherwise. -""" - -import os -import socket -import sys -import threading - -sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "Interactors", "Python")) -from bakashrot import BakaShrotError, Client # noqa: E402 - -dll_path, ini_path, proxy_port, other_key = sys.argv[1], sys.argv[2], int(sys.argv[3]), sys.argv[4] -fails = 0 - - -def check(what, ok, detail=""): - global fails - print(("PASS " if ok else "FAIL ") + what) - if detail: - print(" -> " + detail) - if not ok: - fails += 1 - - -class Proxy: - """Forwards one connection at a time to the server, keeping what passed. - tamper: flips a bit in the next chunk the client sends.""" - - def __init__(self, listen_port, server_host, server_port): - self.server = (server_host, server_port) - self.listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - self.listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - self.listener.bind(("127.0.0.1", listen_port)) - self.listener.listen(4) - self.to_server = bytearray() - self.to_client = bytearray() - self.tamper = False - threading.Thread(target=self._accept, daemon=True).start() - - def _accept(self): - while True: - try: - client, _ = self.listener.accept() - except OSError: - return - upstream = socket.create_connection(self.server) - threading.Thread(target=self._pump, args=(client, upstream, True), daemon=True).start() - threading.Thread(target=self._pump, args=(upstream, client, False), daemon=True).start() - - def _pump(self, source, target, from_client): - try: - while True: - data = source.recv(65536) - if not data: - break - data = bytearray(data) - if from_client and self.tamper: - self.tamper = False - data[-1] ^= 0x01 - (self.to_server if from_client else self.to_client).extend(data) - target.sendall(data) - except OSError: - pass - for s in (source, target): - try: - s.shutdown(socket.SHUT_RDWR) - except OSError: - pass - s.close() - - -base = Client.from_ini(ini_path, dll_path) -proxy = Proxy(proxy_port, base.host, base.port) -marker = "wire-marker-7f3a91" -# The client's DefaultTopic in Python-Test.ps1's server config: its pushes -# land there, and it reads them back from there. -topic = "logs" - -client = Client(base.private_key, base.public_key, base.server_public_key, 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(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(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), 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.node, - base.host, base.port, dll_path) -try: - impostor.connect() - check("Another server's public key can't connect", False, "it connected") - impostor.close() -except BakaShrotError as error: - check("Another server's public key can't connect", True, str(error)) - -# And the right one still can, straight to the server. -try: - base.connect() - check("The right key still connects", base.connected) - base.close() -except BakaShrotError as error: - check("The right key still connects", False, str(error)) - -print() -print("All checks passed" if not fails else f"{fails} check(s) failed") -sys.exit(1 if fails else 0) diff --git a/Tools/BakaShrotGenerateKeyPairs/BakaShrotGenerateKeyPairs.pb b/Tools/BakaShrotGenerateKeyPairs/BakaShrotGenerateKeyPairs.pb deleted file mode 100644 index f49ee1d..0000000 --- a/Tools/BakaShrotGenerateKeyPairs/BakaShrotGenerateKeyPairs.pb +++ /dev/null @@ -1,68 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: BakaShrotGenerateKeyPairs.pb -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; BakaShrotGenerateKeyPairs -; -; Generates a new Ed25519 keypair and prints it as two ini-style lines: -; PrivateKey = -; PublicKey = -; -; The private key goes in the node's own [BakaShrot] PrivateKey, the public -; key goes in the configs of whoever needs to trust that node. -; -; Compile as a console program, exits with 0 on success, 1 on failure. -; ============================================================================ - -EnableExplicit - -XIncludeFile "../Common/ToolConsole.pbi" -XIncludeFile "../../Commons/Cryptography/Libsodium.pbi" - - -Define *PublicKey, *PrivateKey - -OpenConsole() - -If Not InitCryptography() - PrintN("Failed to initialize libsodium") - ToolConsole_End(1) -EndIf - -*PublicKey = AllocateMemory(#BakaShrot_Ed25519_PublicKeySize) -If Not *PublicKey - PrintN("Failed to allocate the public key") - ToolConsole_End(1) -EndIf - -*PrivateKey = AllocateMemory(#BakaShrot_Ed25519_PrivateKeySize) -If Not *PrivateKey - PrintN("Failed to allocate the private key") - ToolConsole_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) - -ToolConsole_End(0) diff --git a/Tools/BakaShrotGetAttachment/BakaShrotGetAttachment.pb b/Tools/BakaShrotGetAttachment/BakaShrotGetAttachment.pb deleted file mode 100644 index 31f1824..0000000 --- a/Tools/BakaShrotGetAttachment/BakaShrotGetAttachment.pb +++ /dev/null @@ -1,85 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: BakaShrotGetAttachment.pb -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; BakaShrotGetAttachment -; -; Usage: BakaShrotGetAttachment [ClientIni] -; Topic, Node Whose message, each a name or an id. -; MessageId Which message. -; OutFile Where to save its attachment (replaced). -; ClientIni Identity and server to use, defaults to "client.ini". -; -; Saves the attachment of a message, read from the server a part at a time -; and checked with its SHA-256, and prints its size. The server refuses if -; the client's ReadTopics don't allow the topic, if the message has none, or -; if it isn't on that server yet (a replicated one comes after its message). -; A failed one leaves no file. See Design/Attachments.md. -; 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, MessageText.s, OutFile.s, IniPath.s, MessageId.q, Size.q, StartTime.i - -OpenConsole() - -If CountProgramParameters() < 4 - PrintN("Usage: BakaShrotGetAttachment [ClientIni]") - PrintN(" Topic and Node are names or ids.") - ToolConsole_End(1) -EndIf - -Topic = ProgramParameter(0) -Node = ProgramParameter(1) -If Not BakaShrot_IsValidRef(Topic) Or Not BakaShrot_IsValidRef(Node) - PrintN("Invalid topic or node, expected names or ids 0-65535") - ToolConsole_End(1) -EndIf -MessageText = ProgramParameter(2) -MessageId = Val(MessageText) -If MessageId < 1 Or Str(MessageId) <> MessageText - PrintN("Invalid message id '" + MessageText + "'") - ToolConsole_End(1) -EndIf -OutFile = ProgramParameter(3) - -IniPath = "client.ini" -If CountProgramParameters() > 4 - IniPath = ProgramParameter(4) -EndIf - -If Not ToolClient_Connect(IniPath) - ToolConsole_End(1) -EndIf - -StartTime = ElapsedMilliseconds() -Size = BakaShrot_SaveAttachment(Topic, Node, MessageId, OutFile) -If Size < 0 - ToolClient_PrintFailure() - ToolClient_Close() - ToolConsole_End(1) -EndIf - -PrintN("Saved " + Str(Size) + " bytes to '" + OutFile + "' in " + Str(ElapsedMilliseconds() - StartTime) + " ms") - -ToolClient_Close() -ToolConsole_End(0) diff --git a/Tools/BakaShrotGetLatestMessage/BakaShrotGetLatestMessage.pb b/Tools/BakaShrotGetLatestMessage/BakaShrotGetLatestMessage.pb deleted file mode 100644 index 0ddb5dc..0000000 --- a/Tools/BakaShrotGetLatestMessage/BakaShrotGetLatestMessage.pb +++ /dev/null @@ -1,88 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: BakaShrotGetLatestMessage.pb -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; BakaShrotGetLatestMessage -; -; Usage: BakaShrotGetLatestMessage [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, and when it was -; pushed (UTC), its attachment if it has one (BakaShrotGetAttachment saves it), then -; its data. 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: BakaShrotGetLatestMessage [ClientIni]") - PrintN(" Topic and Node are names or ids.") - ToolConsole_End(1) -EndIf - -Topic = ProgramParameter(0) -If Not BakaShrot_IsValidRef(Topic) - PrintN("Invalid topic '" + Topic + "', expected a name or an id 0-65535") - ToolConsole_End(1) -EndIf - -Node = ProgramParameter(1) -If Not BakaShrot_IsValidRef(Node) - PrintN("Invalid node '" + Node + "', expected a name or an id 0-65535") - ToolConsole_End(1) -EndIf - -IniPath = "client.ini" -If CountProgramParameters() > 2 - IniPath = ProgramParameter(2) -EndIf - -If Not ToolClient_Connect(IniPath) - ToolConsole_End(1) -EndIf - -If Not BakaShrot_GetLatestMessageOf(Topic, Node) - ToolClient_PrintFailure() - ToolClient_Close() - ToolConsole_End(1) -EndIf - -PrintN("Message " + BakaShrot_GetMessageTopicString() + ":" + BakaShrot_GetMessageNodeString() + "#" + Str(BakaShrot_GetMessageId()) + - " (ids " + Str(BakaShrot_GetMessageTopicId()) + ":" + Str(BakaShrot_GetMessageNodeId()) + "), pushed " + ToolClient_FormatUtc(BakaShrot_GetMessagePushedAt())) -If BakaShrot_GetMessageAttachmentSize() > 0 - If BakaShrot_IsMessageAttachmentReady() - PrintN("Attachment: " + Str(BakaShrot_GetMessageAttachmentSize()) + " bytes") - Else - PrintN("Attachment: " + Str(BakaShrot_GetMessageAttachmentSize()) + " bytes, not on this server yet") - EndIf -EndIf -PrintN(BakaShrot_GetMessageDataString()) - -ToolClient_Close() -ToolConsole_End(0) diff --git a/Tools/BakaShrotGetMessages/BakaShrotGetMessages.pb b/Tools/BakaShrotGetMessages/BakaShrotGetMessages.pb deleted file mode 100644 index 4bb1afa..0000000 --- a/Tools/BakaShrotGetMessages/BakaShrotGetMessages.pb +++ /dev/null @@ -1,207 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: BakaShrotGetMessages.pb -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; BakaShrotGetMessages -; -; Usage: BakaShrotGetMessages [options] [ClientIni] -; Topic, Node Whose messages to get, each a name or an id. -; --after Starts after that message id, defaults to 0: from the -; first one. "latest" starts after the latest one, -; only new messages then (with --follow). -; --limit Stops after N messages, defaults to 100, or to no -; limit with --follow. 0 is no limit. -; --follow, -f Keeps going once caught up: checks for new messages -; every --interval ms, until stopped (Ctrl+C) or the -; connection fails. -; --interval How often --follow checks, defaults to 500. -; --time, -t Also prints when each message was pushed, in UTC. -; 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 (with --time: when it was pushed, "2026-11-08T14:03:59.123Z", and -; another 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, ShowTime.i = #False -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: BakaShrotGetMessages [--after ] [--limit ] [--follow] [--interval ] [--time] [ClientIni]") - PrintN(" Topic and Node are names or ids. Prints each message as its id, a tab, and its data.") - PrintN(" --time also prints when it was pushed (UTC) between them.") - ToolConsole_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) - ToolConsole_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'") - ToolConsole_End(1) - EndIf - AfterText = LCase(Value) - Case "--limit" - If Not IsNumber(Value) - PrintN("Invalid --limit '" + Value + "', expected a number") - ToolConsole_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") - ToolConsole_End(1) - EndIf - IntervalMs = Val(Value) - EndSelect - Case "--time", "-t" - ShowTime = #True - 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") - ToolConsole_End(1) -EndIf -If Not BakaShrot_IsValidRef(Node) - PrintN("Invalid node '" + Node + "', expected a name or an id 0-65535") - ToolConsole_End(1) -EndIf -If Limit < 0 - If Follow - Limit = 0 - Else - Limit = 100 - EndIf -EndIf - -If Not ToolClient_Connect(IniPath) - ToolConsole_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 BakaShrot_GetLastError() <> #BakaShrot_Refused_NotFound - ; Only "no message yet" starts from the start, anything else is told. - ToolClient_PrintFailure() - ToolClient_Close() - ToolConsole_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() - ToolConsole_End(1) - EndIf - - For n = 0 To Count - 1 - BakaShrot_SelectMessage(n) - AfterMessageId = BakaShrot_GetMessageId() - If ShowTime - PrintN(Str(AfterMessageId) + #TAB$ + ToolClient_FormatUtc(BakaShrot_GetMessagePushedAt()) + #TAB$ + BakaShrot_GetMessageDataString()) - Else - PrintN(Str(AfterMessageId) + #TAB$ + BakaShrot_GetMessageDataString()) - EndIf - 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() -ToolConsole_End(0) diff --git a/Tools/BakaShrotList/BakaShrotList.pb b/Tools/BakaShrotList/BakaShrotList.pb deleted file mode 100644 index d33a286..0000000 --- a/Tools/BakaShrotList/BakaShrotList.pb +++ /dev/null @@ -1,113 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: BakaShrotList.pb -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; BakaShrotList -; -; Usage: BakaShrotList [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) - ToolConsole_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 - ToolConsole_End(1) -EndIf -ToolConsole_End(0) diff --git a/Tools/BakaShrotList/BakaShrotList.pb.cfg b/Tools/BakaShrotList/BakaShrotList.pb.cfg deleted file mode 100644 index 4a6f50c..0000000 --- a/Tools/BakaShrotList/BakaShrotList.pb.cfg +++ /dev/null @@ -1,6 +0,0 @@ -IDE Options = PureBasic 6.41 (Windows - x64) -CursorPosition = 7 -Folding = - -EnableXP -DPIAware -CompileSourceDirectory diff --git a/Tools/BakaShrotPushMessage/BakaShrotPushMessage.pb b/Tools/BakaShrotPushMessage/BakaShrotPushMessage.pb deleted file mode 100644 index 5303a42..0000000 --- a/Tools/BakaShrotPushMessage/BakaShrotPushMessage.pb +++ /dev/null @@ -1,115 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: BakaShrotPushMessage.pb -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; BakaShrotPushMessage -; -; Usage: BakaShrotPushMessage [-t ] [-a ] [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. -; -a File Attaches File to the message (any size up to the server's -; MaxAttachmentSize): uploaded first, the message is only -; stored once all of it is. See Design/Attachments.md. -; 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, AttachPath.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") - ToolConsole_End(1) - EndIf - ElseIf (Argument = "-a" Or Argument = "--attach") And i < CountProgramParameters() - 1 - i + 1 - AttachPath = ProgramParameter(i) - If FileSize(AttachPath) < 1 - PrintN("Can't attach '" + AttachPath + "': no such file, or empty") - ToolConsole_End(1) - EndIf - Else - AddElement(Arguments()) - Arguments() = Argument - EndIf -Next - -If ListSize(Arguments()) < 1 - PrintN("Usage: BakaShrotPushMessage [-t ] [-a ] [ClientIni]") - PrintN(" Command-line arguments lose their double quotes, so use @JsonFile for JSON with strings.") - ToolConsole_End(1) -EndIf - -FirstElement(Arguments()) -JsonData = Arguments() -If Left(JsonData, 1) = "@" - If Not ToolClient_ReadTextFile(Mid(JsonData, 2), @FileText) - ToolConsole_End(1) - EndIf - JsonData = FileText\s -EndIf - -IniPath = "client.ini" -If NextElement(Arguments()) - IniPath = Arguments() -EndIf - -If Not ToolClient_Connect(IniPath) - ToolConsole_End(1) -EndIf - -If AttachPath <> "" - MessageId = BakaShrot_PushMessageWithFile(Topic, JsonData, AttachPath) -Else - MessageId = BakaShrot_PushMessageTo(Topic, JsonData) -EndIf -If MessageId < 1 - ToolClient_PrintFailure() - ToolClient_Close() - ToolConsole_End(1) -EndIf - -If AttachPath <> "" - PrintN("Pushed as message #" + Str(MessageId) + ", with an attachment of " + Str(FileSize(AttachPath)) + " bytes") -Else - PrintN("Pushed as message #" + Str(MessageId)) -EndIf - -ToolClient_Close() -ToolConsole_End(0) diff --git a/Tools/BakaShrotQuery/BakaShrotQuery.pb b/Tools/BakaShrotQuery/BakaShrotQuery.pb deleted file mode 100644 index 1bf5dc4..0000000 --- a/Tools/BakaShrotQuery/BakaShrotQuery.pb +++ /dev/null @@ -1,75 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: BakaShrotQuery.pb -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; BakaShrotQuery -; -; Usage: BakaShrotQuery [ClientIni] -; Sql A single read-only SELECT (or WITH ... SELECT), or @ followed -; by a file holding it. Command-line arguments lose their -; double quotes, use single quotes or @SqlFile. -; ClientIni Identity and server to use, defaults to "client.ini". -; -; Runs a raw SQL query on the server and prints its result as JSON: -; {"columns": ["name", ...], "rows": [["value", ...], ...]} -; The client must be allowed to query: AllowQuery = 1 in its server-side -; [BakaShrot.Client.]. -; Compile as a console program, exits with 0 on success, 1 on failure. -; ============================================================================ - -EnableExplicit - -XIncludeFile "../Common/ToolClient.pbi" - - -Define Sql.s, IniPath.s, FileText.String - -OpenConsole() - -If CountProgramParameters() < 1 - PrintN("Usage: BakaShrotQuery [ClientIni]") - PrintN(" Command-line arguments lose their double quotes, use single quotes or @SqlFile.") - ToolConsole_End(1) -EndIf - -Sql = ProgramParameter(0) -If Left(Sql, 1) = "@" - If Not ToolClient_ReadTextFile(Mid(Sql, 2), @FileText) - ToolConsole_End(1) - EndIf - Sql = FileText\s -EndIf - -IniPath = "client.ini" -If CountProgramParameters() > 1 - IniPath = ProgramParameter(1) -EndIf - -If Not ToolClient_Connect(IniPath) - ToolConsole_End(1) -EndIf - -If Not BakaShrot_Query(Sql) - ToolClient_PrintFailure() - ToolClient_Close() - ToolConsole_End(1) -EndIf - -PrintN(BakaShrot_GetQueryResultString()) - -ToolClient_Close() -ToolConsole_End(0) diff --git a/Tools/BakaShrotResolveIds/BakaShrotResolveIds.pb b/Tools/BakaShrotResolveIds/BakaShrotResolveIds.pb deleted file mode 100644 index 9d237f2..0000000 --- a/Tools/BakaShrotResolveIds/BakaShrotResolveIds.pb +++ /dev/null @@ -1,86 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: BakaShrotResolveIds.pb -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; BakaShrotResolveIds -; -; Usage: BakaShrotResolveIds [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: BakaShrotResolveIds [ClientIni]") - ToolConsole_End(1) -EndIf - -Kind = LCase(ProgramParameter(0)) -If Kind <> "topic" And Kind <> "node" - PrintN("Expected 'topic' or 'node', not '" + ProgramParameter(0) + "'") - ToolConsole_End(1) -EndIf - -Ref = ProgramParameter(1) -If Not BakaShrot_IsValidRef(Ref) - PrintN("Invalid " + Kind + " '" + Ref + "', expected a name or an id 0-65535") - ToolConsole_End(1) -EndIf - -IniPath = "client.ini" -If CountProgramParameters() > 2 - IniPath = ProgramParameter(2) -EndIf - -If Not ToolClient_Connect(IniPath) - ToolConsole_End(1) -EndIf - -If Kind = "topic" - Id = BakaShrot_ResolveTopic(Ref) -Else - Id = BakaShrot_ResolveNode(Ref) -EndIf -If Id < 0 - ToolClient_PrintFailure() - ToolClient_Close() - ToolConsole_End(1) -EndIf - -Name = BakaShrot_GetResolvedNameString() -If Name = "" - Name = "(unnamed)" -EndIf -PrintN(Kind + " " + Name + " = " + Str(Id)) - -ToolClient_Close() -ToolConsole_End(0) diff --git a/Tools/BakaShrotResolveIds/BakaShrotResolveIds.pb.cfg b/Tools/BakaShrotResolveIds/BakaShrotResolveIds.pb.cfg deleted file mode 100644 index 7683a01..0000000 --- a/Tools/BakaShrotResolveIds/BakaShrotResolveIds.pb.cfg +++ /dev/null @@ -1,5 +0,0 @@ -IDE Options = PureBasic 6.41 (Windows - x64) -CursorPosition = 7 -EnableXP -DPIAware -CompileSourceDirectory diff --git a/Tools/Common/ToolClient.pbi b/Tools/Common/ToolClient.pbi deleted file mode 100644 index b2e51a6..0000000 --- a/Tools/Common/ToolClient.pbi +++ /dev/null @@ -1,178 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: ToolClient.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; BakaShrot 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, Node, ServerHost, ServerPort, -; ServerPublicKey (the server's, it logs it when it starts) -; Node is the node the client writes as, a name or an id -; (Commons/Networking/Names.pbi); NodeId before, still read when Node is -; missing. A Topic (TopicId) left in it is ignored: the client's default -; topic is in the server's config (DefaultTopic). -; ============================================================================ - -XIncludeFile "../../Client/BakaShrot_Client_Prototypes.pbi" -XIncludeFile "ToolConsole.pbi" - - -; What a client error code (100+, BakaShrot_ErrorCodes.pbi) means, for the -; tools' messages. -Procedure.s ToolClient_Explain(Code.l) - Select Code - Case #BakaShrot_Error_NotConnected : ProcedureReturn "not connected" - Case #BakaShrot_Error_ConnectFailed : ProcedureReturn "nothing answers there" - Case #BakaShrot_Error_AuthRejected : ProcedureReturn "the server closed the connection: wrong ServerPublicKey, a key or node it doesn't allow, or another version (its log says which)" - Case #BakaShrot_Error_ServerNotVerified : ProcedureReturn "the server couldn't prove it holds ServerPublicKey's private key" - Case #BakaShrot_Error_ConnectionLost : ProcedureReturn "the connection to the server failed" - Case #BakaShrot_Error_ProtocolError : ProcedureReturn "the server answered something unexpected, the connection is closed" - Case #BakaShrot_Error_InvalidArgument : ProcedureReturn "an invalid argument" - Case #BakaShrot_Error_FileError : ProcedureReturn "a file couldn't be opened, read or written" - Case #BakaShrot_Error_AttachmentMismatch : ProcedureReturn "the attachment doesn't match its SHA-256" - Case #BakaShrot_Error_Internal : ProcedureReturn "out of memory, or another failure in the client" - EndSelect - ProcedureReturn BakaShrot_ErrorName(Code) -EndProcedure - - -; 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, 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", "") - 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_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_ErrorName(BakaShrot_GetLastError()) + "): " + ToolClient_Explain(BakaShrot_GetLastError())) - BakaShrot_UnloadClient() - ProcedureReturn #False - EndIf - - ProcedureReturn #True -EndProcedure - - -; Ms (milliseconds since 1970 UTC, as BakaShrot_GetMessagePushedAt() gives -; it) as "2026-11-08T14:03:59.123Z". -Procedure.s ToolClient_FormatUtc(Ms.q) - ProcedureReturn FormatDate("%yyyy-%mm-%ddT%hh:%ii:%ss", Ms / 1000) + "." + RSet(Str(Ms % 1000), 3, "0") + "Z" -EndProcedure - - -; Disconnects and unloads the DLL. -Procedure ToolClient_Close() - BakaShrot_Disconnect() - BakaShrot_UnloadClient() -EndProcedure - - -; Prints why the last request failed. -; With its code's name (BakaShrot_ErrorCodes.pbi), for scripts to match on. -Procedure ToolClient_PrintFailure() - Protected Code.l = BakaShrot_GetLastError() - - If BakaShrot_IsRefusalCode(Code) - PrintN("Refused by the server (" + BakaShrot_ErrorName(Code) + "): " + BakaShrot_GetRefusalReasonString()) - ElseIf BakaShrot_GetRefusalReasonString() <> "" - ; The client's own refusals: a message or attachment over the limits... - PrintN("Failed (" + BakaShrot_ErrorName(Code) + "): " + BakaShrot_GetRefusalReasonString()) - Else - PrintN("Failed (" + BakaShrot_ErrorName(Code) + "): " + ToolClient_Explain(Code)) - EndIf -EndProcedure - - -; Reads a whole UTF-8 text file (a byte order mark is skipped) into *Text. -; In one go: ReadString() with #PB_File_IgnoreEOL takes seconds on a 16 MB -; line. Prints why and returns #False if it can't be read. -Procedure.i ToolClient_ReadTextFile(Path.s, *Text.String) - Protected FileId.i, Size.q, *Data, Offset.i - - FileId = ReadFile(#PB_Any, Path) - If Not FileId - PrintN("Failed to open '" + Path + "'") - ProcedureReturn #False - EndIf - Size = Lof(FileId) - *Data = AllocateMemory(Size + 1) - If Not *Data - CloseFile(FileId) - PrintN("'" + Path + "' is too big to read") - ProcedureReturn #False - EndIf - If ReadData(FileId, *Data, Size) <> Size - FreeMemory(*Data) - CloseFile(FileId) - PrintN("Failed to read '" + Path + "'") - ProcedureReturn #False - EndIf - CloseFile(FileId) - - If Size >= 3 And PeekA(*Data) = $EF And PeekA(*Data + 1) = $BB And PeekA(*Data + 2) = $BF - Offset = 3 - EndIf - *Text\s = "" - If Size > Offset - *Text\s = PeekS(*Data + Offset, Size - Offset, #PB_UTF8 | #PB_ByteLength) - EndIf - FreeMemory(*Data) - ProcedureReturn #True -EndProcedure diff --git a/Tools/Common/ToolConsole.pbi b/Tools/Common/ToolConsole.pbi deleted file mode 100644 index 922a50f..0000000 --- a/Tools/Common/ToolConsole.pbi +++ /dev/null @@ -1,73 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: ToolConsole.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; BakaShrot Tools - Console -; -; Shared by every tool. Started from Explorer (a double-click, a shortcut), -; a console program gets a console of its own that closes as soon as it -; ends, before what it printed can be read: ToolConsole_End() waits for -; Enter then, and ends at once otherwise. -; As https://github.com/aziascreations/PB-Template-Win32-CliApp does it: a -; program started from a shell shares the shell's console, one started -; directly is alone in its own. -; ============================================================================ - -CompilerIf #PB_Compiler_OS = #PB_OS_Windows - ; Not in PureBasic 5.73's API functions, named so it can't clash with a - ; compiler that has it. - Import "kernel32.lib" - CompilerIf #PB_Compiler_Processor = #PB_Processor_x86 - ToolConsole_GetConsoleProcessList.l(*ProcessList, ProcessCount.l) As "_GetConsoleProcessList@8" - CompilerElse - ToolConsole_GetConsoleProcessList.l(*ProcessList, ProcessCount.l) As "GetConsoleProcessList" - CompilerEndIf - EndImport -CompilerEndIf - - -; #True if the tool was started directly rather than from a shell: it is the -; only process on its console. Input or output redirected is #False, someone -; else reads it (a test starting it with Start-Process gets a new hidden -; console too, alone on it). Always #False outside of Windows. -Procedure.i ToolConsole_IsRunDirectly() - CompilerIf #PB_Compiler_OS = #PB_OS_Windows - Protected Mode.l, ProcessList.q ; ProcessList: room for 2 process ids - - If Not GetConsoleMode_(GetStdHandle_(#STD_INPUT_HANDLE), @Mode) - ProcedureReturn #False - EndIf - If Not GetConsoleMode_(GetStdHandle_(#STD_OUTPUT_HANDLE), @Mode) - ProcedureReturn #False - EndIf - ProcedureReturn Bool(ToolConsole_GetConsoleProcessList(@ProcessList, 2) <= 1) - CompilerElse - ProcedureReturn #False - CompilerEndIf -EndProcedure - - -; Ends the tool with ExitCode, after waiting for Enter if it was started -; directly (ToolConsole_IsRunDirectly()). -Procedure ToolConsole_End(ExitCode.i) - If ToolConsole_IsRunDirectly() - PrintN("") - Print("Press Enter to close...") - Input() - EndIf - End ExitCode -EndProcedure diff --git a/bindings/c/bakashrot.h b/bindings/c/bakashrot.h new file mode 100644 index 0000000..bdb2727 --- /dev/null +++ b/bindings/c/bakashrot.h @@ -0,0 +1,355 @@ +/* + * BakaShrot's client DLL: bakashrot.dll (Windows), libbakashrot.so (Linux). + * Generated by cbindgen from crates/bakashrot-capi: don't edit. + * docs/client.md has the conventions and the whole API. + */ + +#ifndef BAKASHROT_H +#define BAKASHROT_H + +#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + +/** + * Why the last call failed: a protocol error code (1-99 a server's + * refusal, the connection still open; 100 and up the client's own), 0 if + * it succeeded. Getters don't change it. + */ +int32_t BakaShrot_GetLastError(void); + +/** + * Why the last call failed, in words: the server's reason for a refusal, + * the client's otherwise. Empty if it succeeded. + */ +ptrdiff_t BakaShrot_GetRefusalReasonA(char *buffer, ptrdiff_t size); + +/** + * The same as `BakaShrot_GetRefusalReasonA`, in UTF-16. + */ +ptrdiff_t BakaShrot_GetRefusalReasonW(uint16_t *buffer, ptrdiff_t size); + +/** + * Sets the CA's certificate, which the server's must be issued by: PEM + * text, or the path of a file holding it. Before connecting. + */ +ptrdiff_t BakaShrot_SetCaCertificateA(const char *certificate); + +/** + * The same as `BakaShrot_SetCaCertificateA`, in UTF-16. + */ +ptrdiff_t BakaShrot_SetCaCertificateW(const uint16_t *certificate); + +/** + * Sets this client's certificate, which says its node and its roles: PEM + * text, or the path of a file holding it. Before connecting. + */ +ptrdiff_t BakaShrot_SetCertificateA(const char *certificate); + +/** + * The same as `BakaShrot_SetCertificateA`, in UTF-16. + */ +ptrdiff_t BakaShrot_SetCertificateW(const uint16_t *certificate); + +/** + * Sets this client's private key, its certificate's: PEM text, or the path + * of a file holding it. Before connecting. + */ +ptrdiff_t BakaShrot_SetPrivateKeyA(const char *key); + +/** + * The same as `BakaShrot_SetPrivateKeyA`, in UTF-16. + */ +ptrdiff_t BakaShrot_SetPrivateKeyW(const uint16_t *key); + +/** + * Sets the CA's CRL, optional: servers it revokes are refused. PEM text, + * or the path of a file holding it; null or empty for none. Before + * connecting. + */ +ptrdiff_t BakaShrot_SetCrlA(const char *crl); + +/** + * The same as `BakaShrot_SetCrlA`, in UTF-16. + */ +ptrdiff_t BakaShrot_SetCrlW(const uint16_t *crl); + +/** + * Connects to the server at `host` (a name or an address) and `port`: + * TLS with the certificates set, then the server says who this client is + * (`BakaShrot_GetNode()`). Refused: the code says by whom (`AuthRejected` + * the server refused the certificate, `ServerNotVerified` this client + * refused the server's, `NotAllowed` none of its roles is the server's). + */ +ptrdiff_t BakaShrot_ConnectA(const char *host, int32_t port); + +/** + * The same as `BakaShrot_ConnectA`, in UTF-16. + */ +ptrdiff_t BakaShrot_ConnectW(const uint16_t *host, int32_t port); + +/** + * 1 while connected: notices when the server closed the connection + * (forgotten then: connect again). + */ +ptrdiff_t BakaShrot_IsConnected(void); + +/** + * Closes the connection: 0 if there was none. The settings stay. + */ +ptrdiff_t BakaShrot_Disconnect(void); + +/** + * The node this client is, as the server said when connecting: its + * certificate's name. Empty when not connected. + */ +ptrdiff_t BakaShrot_GetNodeA(char *buffer, ptrdiff_t size); + +/** + * The same as `BakaShrot_GetNodeA`, in UTF-16. + */ +ptrdiff_t BakaShrot_GetNodeW(uint16_t *buffer, ptrdiff_t size); + +/** + * Pushes a message (JSON or not) to `topic`, as this client's node: its + * id (1 and up), -1 on failure. A push whose answer was lost + * (`ConnectionLost`) may have been stored all the same. + */ +int64_t BakaShrot_PushMessageToA(const char *topic, const char *data); + +/** + * The same as `BakaShrot_PushMessageToA`, in UTF-16. + */ +int64_t BakaShrot_PushMessageToW(const uint16_t *topic, const uint16_t *data); + +/** + * Gets the latest message of `topic` and `node`, then read with the + * `BakaShrot_GetMessage*()` getters. `NotFound` if there's none yet. + */ +ptrdiff_t BakaShrot_GetLatestMessageOfA(const char *topic, const char *node); + +/** + * The same as `BakaShrot_GetLatestMessageOfA`, in UTF-16. + */ +ptrdiff_t BakaShrot_GetLatestMessageOfW(const uint16_t *topic, const uint16_t *node); + +/** + * Gets the messages of `topic` and `node` after id `after` (0 for the + * first ones), in order: `limit` at most (1-10000), fewer past about + * 1 MB. Returns how many came (none isn't a failure), -1 on failure. The + * first is selected; `BakaShrot_SelectMessage()` selects the others, + * `BakaShrot_HasMoreMessages()` says whether more follow the last one. + */ +int32_t BakaShrot_GetMessagesA(const char *topic, const char *node, int64_t after, int32_t limit); + +/** + * The same as `BakaShrot_GetMessagesA`, in UTF-16. + */ +int32_t BakaShrot_GetMessagesW(const uint16_t *topic, + const uint16_t *node, + int64_t after, + int32_t limit); + +/** + * How many messages the last `GetMessages` or `GetLatestMessageOf` got. + */ +int32_t BakaShrot_GetMessageCount(void); + +/** + * Selects the message at `index` (0 to the count - 1) for the getters: 0 + * if there's none there (`InvalidArgument`), the selection unchanged. + */ +ptrdiff_t BakaShrot_SelectMessage(int32_t index); + +/** + * 1 if more messages follow the last one the last `GetMessages` got: ask + * again after its id. + */ +ptrdiff_t BakaShrot_HasMoreMessages(void); + +/** + * The selected message's id, 0 if none. + */ +int64_t BakaShrot_GetMessageId(void); + +/** + * When the selected message was pushed, by the server it was pushed to: + * milliseconds since 1970-01-01 UTC, 0 if none. + */ +int64_t BakaShrot_GetMessagePushedAt(void); + +/** + * The selected message's attachment's size, 0 without one. + */ +int64_t BakaShrot_GetMessageAttachmentSize(void); + +/** + * 1 if the selected message's attachment is all on this server (a + * replicated one may still be on its way). + */ +ptrdiff_t BakaShrot_IsMessageAttachmentReady(void); + +/** + * The selected message's data, as pushed (JSON or not). + */ +ptrdiff_t BakaShrot_GetMessageDataA(char *buffer, ptrdiff_t size); + +/** + * The same as `BakaShrot_GetMessageDataA`, in UTF-16. + */ +ptrdiff_t BakaShrot_GetMessageDataW(uint16_t *buffer, ptrdiff_t size); + +/** + * The topic the last `GetMessages` or `GetLatestMessageOf` asked for. + */ +ptrdiff_t BakaShrot_GetMessageTopicA(char *buffer, ptrdiff_t size); + +/** + * The same as `BakaShrot_GetMessageTopicA`, in UTF-16. + */ +ptrdiff_t BakaShrot_GetMessageTopicW(uint16_t *buffer, ptrdiff_t size); + +/** + * The node the last `GetMessages` or `GetLatestMessageOf` asked for. + */ +ptrdiff_t BakaShrot_GetMessageNodeA(char *buffer, ptrdiff_t size); + +/** + * The same as `BakaShrot_GetMessageNodeA`, in UTF-16. + */ +ptrdiff_t BakaShrot_GetMessageNodeW(uint16_t *buffer, ptrdiff_t size); + +/** + * Lists the topics this client may push to or read (every one if it may + * query): how many, -1 on failure. Then `BakaShrot_GetNamesList()`. + */ +int32_t BakaShrot_ListTopics(void); + +/** + * Lists every node with messages: how many, -1 on failure. Then + * `BakaShrot_GetNamesList()`. + */ +int32_t BakaShrot_ListNodes(void); + +/** + * The last list, as JSON: + * `{"kind":"topic","truncated":false,"names":["logs",...]}`, `truncated` + * if some didn't fit. + */ +ptrdiff_t BakaShrot_GetNamesListA(char *buffer, ptrdiff_t size); + +/** + * The same as `BakaShrot_GetNamesListA`, in UTF-16. + */ +ptrdiff_t BakaShrot_GetNamesListW(uint16_t *buffer, ptrdiff_t size); + +/** + * Runs read-only SQL on the server (one SELECT or WITH), if this client + * may query. Then `BakaShrot_GetQueryResult()`. + */ +ptrdiff_t BakaShrot_QueryA(const char *sql); + +/** + * The same as `BakaShrot_QueryA`, in UTF-16. + */ +ptrdiff_t BakaShrot_QueryW(const uint16_t *sql); + +/** + * The last query's result, as JSON: + * `{"columns":[...],"rows":[[...],...]}`, every value a string or null. + */ +ptrdiff_t BakaShrot_GetQueryResultA(char *buffer, ptrdiff_t size); + +/** + * The same as `BakaShrot_GetQueryResultA`, in UTF-16. + */ +ptrdiff_t BakaShrot_GetQueryResultW(uint16_t *buffer, ptrdiff_t size); + +/** + * Pushes a message with the file at `FilePath` as its attachment (1 byte + * to 1 TiB, the server may take less: `TooBig`): uploaded with it, the + * message stored once all of it came. Its id, -1 on failure. The file is + * read twice (its SHA-256 first): one changed in between is refused + * (`DataMismatch`). + */ +int64_t BakaShrot_PushMessageWithFileA(const char *topic, const char *data, const char *file_path); + +/** + * The same as `BakaShrot_PushMessageWithFileA`, in UTF-16. + */ +int64_t BakaShrot_PushMessageWithFileW(const uint16_t *topic, + const uint16_t *data, + const uint16_t *file_path); + +/** + * Pushes a message with the `Size` bytes at `Data` as its attachment, as + * `BakaShrot_PushMessageWithFileA` does. + */ +int64_t BakaShrot_PushMessageWithDataA(const char *topic, + const char *data, + const void *attachment, + int64_t size); + +/** + * The same as `BakaShrot_PushMessageWithDataA`, in UTF-16. + */ +int64_t BakaShrot_PushMessageWithDataW(const uint16_t *topic, + const uint16_t *data, + const void *attachment, + int64_t size); + +/** + * Saves the attachment of `Topic`, `Node`'s message `MessageId` as the + * file at `FilePath` (replaced), read a part at a time and checked with + * its SHA-256: its size, -1 on failure (`NotFound` without one, + * `NotReady` if it isn't on this server yet, `AttachmentMismatch`). A + * failed one leaves no file. + */ +int64_t BakaShrot_SaveAttachmentA(const char *topic, + const char *node, + int64_t message_id, + const char *file_path); + +/** + * The same as `BakaShrot_SaveAttachmentA`, in UTF-16. + */ +int64_t BakaShrot_SaveAttachmentW(const uint16_t *topic, + const uint16_t *node, + int64_t message_id, + const uint16_t *file_path); + +/** + * Reads the attachment of `Topic`, `Node`'s message `MessageId` into + * memory, checked with its SHA-256 (`BakaShrot_SaveAttachmentA` for big + * ones): its size, -1 on failure. Then `BakaShrot_GetAttachmentData()`. + */ +int64_t BakaShrot_LoadAttachmentA(const char *topic, const char *node, int64_t message_id); + +/** + * The same as `BakaShrot_LoadAttachmentA`, in UTF-16. + */ +int64_t BakaShrot_LoadAttachmentW(const uint16_t *topic, const uint16_t *node, int64_t message_id); + +/** + * Copies what the last `BakaShrot_LoadAttachment()` read into `Buffer`, if + * `BufferSize` is enough: returns its size (0 if none), copies nothing if + * it doesn't fit (a null `Buffer` asks for the size). + */ +int64_t BakaShrot_GetAttachmentData(void *buffer, int64_t buffer_size); + +/** + * Frees what `BakaShrot_LoadAttachment()` read: 1. + */ +ptrdiff_t BakaShrot_FreeAttachmentData(void); + +#ifdef __cplusplus +} // extern "C" +#endif // __cplusplus + +#endif /* BAKASHROT_H */ diff --git a/bindings/purebasic/BakaShrot_Client_Prototypes.pbi b/bindings/purebasic/BakaShrot_Client_Prototypes.pbi new file mode 100644 index 0000000..9b48eb2 --- /dev/null +++ b/bindings/purebasic/BakaShrot_Client_Prototypes.pbi @@ -0,0 +1,322 @@ +;{- Code Header +; ==- Basic Info -================================ +; Name: BakaShrot_Client_Prototypes.pbi +; Version: 0.0.1 +; Author: Herwin Bozet (NibblePoker) +; +; ==- Compatibility -============================= +; Tested compiler versions: +; * PureBasic 5.73 LTS (Windows x64) +; +; ==- Links -===================================== +; GitHub: https://github.com/aziascreations/BakaShrot +;} + +; ============================================================================ +; BakaShrot client DLL - Prototypes +; +; Include this in an app to use bakashrot.dll (libbakashrot.so on Linux): +; XIncludeFile "BakaShrot_Client_Prototypes.pbi" +; If BakaShrot_LoadClient("bakashrot.dll") +; BakaShrot_SetCaCertificate("ca.crt") ; a file, or PEM text +; BakaShrot_SetCertificate("kitchen.crt") +; BakaShrot_SetPrivateKey("kitchen.key") +; If BakaShrot_Connect("10.0.0.2", 7000) +; BakaShrot_PushMessageTo("logs", ~"{\"temp\": 21}") +; ... +; EndIf +; BakaShrot_UnloadClient() +; EndIf +; +; docs/client.md has what each function does (and +; bindings/c/bakashrot.h, generated from the DLL). The string +; functions are mapped to the DLL's W (UTF-16) variants. After a failed +; call, BakaShrot_GetLastError() tells why: the codes and what to do about +; each are in BakaShrot_ErrorCodes.pbi, next to this file (included below), +; BakaShrot_ErrorName() names them; BakaShrot_GetRefusalReasonString() says +; why in words. +; +; Changed from the PureBasic DLL (protocol 6): certificates instead of keys +; and a node (BakaShrot_SetCaCertificate(), _SetCertificate(), +; _SetPrivateKey() now a PEM key, _SetCrl()); a push always names its topic +; (BakaShrot_PushMessage() is gone); no ids (_GetLatestMessage(TopicId, +; NodeId), _SetNodeId(), _GetMessageTopicId/NodeId(), _ResolveTopic/Node(), +; _GetResolvedName() are gone); _GetNamesList() is +; {"kind":"topic","names":[...],"truncated":false}. New: _GetNode(). +; Attachments: the same six as before, by names. +; ============================================================================ + +XIncludeFile "BakaShrot_ErrorCodes.pbi" + + +PrototypeC.l BakaShrot_GetLastError_Prototype() +PrototypeC.i BakaShrot_GetRefusalReason_Prototype(*Buffer, BufferSize.i) +PrototypeC.i BakaShrot_SetCaCertificate_Prototype(Certificate.p-unicode) +PrototypeC.i BakaShrot_SetCertificate_Prototype(Certificate.p-unicode) +PrototypeC.i BakaShrot_SetPrivateKey_Prototype(PrivateKey.p-unicode) +PrototypeC.i BakaShrot_SetCrl_Prototype(Crl.p-unicode) +PrototypeC.i BakaShrot_Connect_Prototype(Host.p-unicode, Port.l) +PrototypeC.i BakaShrot_IsConnected_Prototype() +PrototypeC.i BakaShrot_Disconnect_Prototype() +PrototypeC.i BakaShrot_GetNode_Prototype(*Buffer, BufferSize.i) +PrototypeC.q BakaShrot_PushMessageTo_Prototype(Topic.p-unicode, JsonData.p-unicode) +PrototypeC.i BakaShrot_GetLatestMessageOf_Prototype(Topic.p-unicode, Node.p-unicode) +PrototypeC.l BakaShrot_GetMessages_Prototype(Topic.p-unicode, Node.p-unicode, AfterMessageId.q, Limit.l) +PrototypeC.l BakaShrot_GetMessageCount_Prototype() +PrototypeC.i BakaShrot_SelectMessage_Prototype(Index.l) +PrototypeC.i BakaShrot_HasMoreMessages_Prototype() +PrototypeC.q BakaShrot_GetMessageId_Prototype() +PrototypeC.q BakaShrot_GetMessagePushedAt_Prototype() +PrototypeC.q BakaShrot_GetMessageAttachmentSize_Prototype() +PrototypeC.i BakaShrot_IsMessageAttachmentReady_Prototype() +PrototypeC.i BakaShrot_GetMessageData_Prototype(*Buffer, BufferSize.i) +PrototypeC.i BakaShrot_GetMessageTopic_Prototype(*Buffer, BufferSize.i) +PrototypeC.i BakaShrot_GetMessageNode_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_Query_Prototype(Sql.p-unicode) +PrototypeC.i BakaShrot_GetQueryResult_Prototype(*Buffer, BufferSize.i) +PrototypeC.q BakaShrot_PushMessageWithFile_Prototype(Topic.p-unicode, JsonData.p-unicode, FilePath.p-unicode) +PrototypeC.q BakaShrot_PushMessageWithData_Prototype(Topic.p-unicode, JsonData.p-unicode, *Data, Size.q) +PrototypeC.q BakaShrot_SaveAttachment_Prototype(Topic.p-unicode, Node.p-unicode, MessageId.q, FilePath.p-unicode) +PrototypeC.q BakaShrot_LoadAttachment_Prototype(Topic.p-unicode, Node.p-unicode, MessageId.q) +PrototypeC.q BakaShrot_GetAttachmentData_Prototype(*Buffer, BufferSize.q) +PrototypeC.i BakaShrot_FreeAttachmentData_Prototype() + + +Global BakaShrot_GetLastError.BakaShrot_GetLastError_Prototype +Global BakaShrot_GetRefusalReason.BakaShrot_GetRefusalReason_Prototype +Global BakaShrot_SetCaCertificate.BakaShrot_SetCaCertificate_Prototype +Global BakaShrot_SetCertificate.BakaShrot_SetCertificate_Prototype +Global BakaShrot_SetPrivateKey.BakaShrot_SetPrivateKey_Prototype +Global BakaShrot_SetCrl.BakaShrot_SetCrl_Prototype +Global BakaShrot_Connect.BakaShrot_Connect_Prototype +Global BakaShrot_IsConnected.BakaShrot_IsConnected_Prototype +Global BakaShrot_Disconnect.BakaShrot_Disconnect_Prototype +Global BakaShrot_GetNode.BakaShrot_GetNode_Prototype +Global BakaShrot_PushMessageTo.BakaShrot_PushMessageTo_Prototype +Global BakaShrot_GetLatestMessageOf.BakaShrot_GetLatestMessageOf_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_GetMessageId.BakaShrot_GetMessageId_Prototype +Global BakaShrot_GetMessagePushedAt.BakaShrot_GetMessagePushedAt_Prototype +Global BakaShrot_GetMessageAttachmentSize.BakaShrot_GetMessageAttachmentSize_Prototype +Global BakaShrot_IsMessageAttachmentReady.BakaShrot_IsMessageAttachmentReady_Prototype +Global BakaShrot_GetMessageData.BakaShrot_GetMessageData_Prototype +Global BakaShrot_GetMessageTopic.BakaShrot_GetMessageTopic_Prototype +Global BakaShrot_GetMessageNode.BakaShrot_GetMessageNode_Prototype +Global BakaShrot_ListTopics.BakaShrot_ListTopics_Prototype +Global BakaShrot_ListNodes.BakaShrot_ListNodes_Prototype +Global BakaShrot_GetNamesList.BakaShrot_GetNamesList_Prototype +Global BakaShrot_Query.BakaShrot_Query_Prototype +Global BakaShrot_GetQueryResult.BakaShrot_GetQueryResult_Prototype +Global BakaShrot_PushMessageWithFile.BakaShrot_PushMessageWithFile_Prototype +Global BakaShrot_PushMessageWithData.BakaShrot_PushMessageWithData_Prototype +Global BakaShrot_SaveAttachment.BakaShrot_SaveAttachment_Prototype +Global BakaShrot_LoadAttachment.BakaShrot_LoadAttachment_Prototype +Global BakaShrot_GetAttachmentData.BakaShrot_GetAttachmentData_Prototype +Global BakaShrot_FreeAttachmentData.BakaShrot_FreeAttachmentData_Prototype + +Global BakaShrot_ClientLibrary.i = 0 +; The first export BakaShrot_LoadClient() didn't find, "" if none. +Global BakaShrot_ClientMissing.s = "" + + +; Unloads the DLL loaded by BakaShrot_LoadClient(). +Procedure BakaShrot_UnloadClient() + If BakaShrot_ClientLibrary + CloseLibrary(BakaShrot_ClientLibrary) + BakaShrot_ClientLibrary = 0 + EndIf +EndProcedure + + +; An export of the DLL, noted in BakaShrot_ClientMissing if it has none. +Procedure.i BakaShrot_ClientFunction(Name.s) + Protected *Function = GetFunction(BakaShrot_ClientLibrary, Name) + If Not *Function And BakaShrot_ClientMissing = "" + BakaShrot_ClientMissing = Name + EndIf + ProcedureReturn *Function +EndProcedure + + +; Loads the DLL at DllPath and fills the function pointers above. +; Returns #False if the DLL can't be loaded or an export is missing (an +; older DLL: BakaShrot_ClientMissing says which). +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 + BakaShrot_ClientMissing = "" + + ; PureBasic strings are UTF-16, so the W variants are used. + BakaShrot_GetLastError = BakaShrot_ClientFunction("BakaShrot_GetLastError") + BakaShrot_GetRefusalReason = BakaShrot_ClientFunction("BakaShrot_GetRefusalReasonW") + BakaShrot_SetCaCertificate = BakaShrot_ClientFunction("BakaShrot_SetCaCertificateW") + BakaShrot_SetCertificate = BakaShrot_ClientFunction("BakaShrot_SetCertificateW") + BakaShrot_SetPrivateKey = BakaShrot_ClientFunction("BakaShrot_SetPrivateKeyW") + BakaShrot_SetCrl = BakaShrot_ClientFunction("BakaShrot_SetCrlW") + BakaShrot_Connect = BakaShrot_ClientFunction("BakaShrot_ConnectW") + BakaShrot_IsConnected = BakaShrot_ClientFunction("BakaShrot_IsConnected") + BakaShrot_Disconnect = BakaShrot_ClientFunction("BakaShrot_Disconnect") + BakaShrot_GetNode = BakaShrot_ClientFunction("BakaShrot_GetNodeW") + BakaShrot_PushMessageTo = BakaShrot_ClientFunction("BakaShrot_PushMessageToW") + BakaShrot_GetLatestMessageOf = BakaShrot_ClientFunction("BakaShrot_GetLatestMessageOfW") + BakaShrot_GetMessages = BakaShrot_ClientFunction("BakaShrot_GetMessagesW") + BakaShrot_GetMessageCount = BakaShrot_ClientFunction("BakaShrot_GetMessageCount") + BakaShrot_SelectMessage = BakaShrot_ClientFunction("BakaShrot_SelectMessage") + BakaShrot_HasMoreMessages = BakaShrot_ClientFunction("BakaShrot_HasMoreMessages") + BakaShrot_GetMessageId = BakaShrot_ClientFunction("BakaShrot_GetMessageId") + BakaShrot_GetMessagePushedAt = BakaShrot_ClientFunction("BakaShrot_GetMessagePushedAt") + BakaShrot_GetMessageAttachmentSize = BakaShrot_ClientFunction("BakaShrot_GetMessageAttachmentSize") + BakaShrot_IsMessageAttachmentReady = BakaShrot_ClientFunction("BakaShrot_IsMessageAttachmentReady") + BakaShrot_GetMessageData = BakaShrot_ClientFunction("BakaShrot_GetMessageDataW") + BakaShrot_GetMessageTopic = BakaShrot_ClientFunction("BakaShrot_GetMessageTopicW") + BakaShrot_GetMessageNode = BakaShrot_ClientFunction("BakaShrot_GetMessageNodeW") + BakaShrot_ListTopics = BakaShrot_ClientFunction("BakaShrot_ListTopics") + BakaShrot_ListNodes = BakaShrot_ClientFunction("BakaShrot_ListNodes") + BakaShrot_GetNamesList = BakaShrot_ClientFunction("BakaShrot_GetNamesListW") + BakaShrot_Query = BakaShrot_ClientFunction("BakaShrot_QueryW") + BakaShrot_GetQueryResult = BakaShrot_ClientFunction("BakaShrot_GetQueryResultW") + BakaShrot_PushMessageWithFile = BakaShrot_ClientFunction("BakaShrot_PushMessageWithFileW") + BakaShrot_PushMessageWithData = BakaShrot_ClientFunction("BakaShrot_PushMessageWithDataW") + BakaShrot_SaveAttachment = BakaShrot_ClientFunction("BakaShrot_SaveAttachmentW") + BakaShrot_LoadAttachment = BakaShrot_ClientFunction("BakaShrot_LoadAttachmentW") + BakaShrot_GetAttachmentData = BakaShrot_ClientFunction("BakaShrot_GetAttachmentData") + BakaShrot_FreeAttachmentData = BakaShrot_ClientFunction("BakaShrot_FreeAttachmentData") + + If BakaShrot_ClientMissing <> "" + BakaShrot_UnloadClient() + ProcedureReturn #False + EndIf + ProcedureReturn #True +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 + +; The string getters, as strings. +Procedure.s BakaShrot_GetRefusalReasonString() + ProcedureReturn BakaShrot_GetString(BakaShrot_GetRefusalReason) +EndProcedure + +Procedure.s BakaShrot_GetNodeString() + ProcedureReturn BakaShrot_GetString(BakaShrot_GetNode) +EndProcedure + +Procedure.s BakaShrot_GetMessageDataString() + ProcedureReturn BakaShrot_GetString(BakaShrot_GetMessageData) +EndProcedure + +Procedure.s BakaShrot_GetMessageTopicString() + ProcedureReturn BakaShrot_GetString(BakaShrot_GetMessageTopic) +EndProcedure + +Procedure.s BakaShrot_GetMessageNodeString() + ProcedureReturn BakaShrot_GetString(BakaShrot_GetMessageNode) +EndProcedure + +Procedure.s BakaShrot_GetNamesListString() + ProcedureReturn BakaShrot_GetString(BakaShrot_GetNamesList) +EndProcedure + +Procedure.s BakaShrot_GetQueryResultString() + ProcedureReturn BakaShrot_GetString(BakaShrot_GetQueryResult) +EndProcedure + + +; Usage example. Only compiled when this file is run directly (F5 in the +; IDE), not when it's included by an app. +; ClientExample +; Pushes a message to "logs", reads it back, pushes one with an +; attachment and reads that back, lists the topics. +CompilerIf #PB_Compiler_IsMainFile + + Define Id.q, Size.q, *Attachment, *Copy + + ; Prints why the last call failed, then ends. + Procedure Failed(What.s) + PrintN(What + " failed: " + BakaShrot_ErrorName(BakaShrot_GetLastError()) + ", " + BakaShrot_GetRefusalReasonString()) + BakaShrot_UnloadClient() + End 1 + EndProcedure + + OpenConsole() + If CountProgramParameters() < 6 + PrintN("Usage: ClientExample ") + End 2 + EndIf + + If Not BakaShrot_LoadClient(ProgramParameter(0)) + PrintN("Failed to load " + ProgramParameter(0) + " " + BakaShrot_ClientMissing) + End 1 + EndIf + + If Not BakaShrot_SetCaCertificate(ProgramParameter(1)) : Failed("Setting the CA's certificate") : EndIf + If Not BakaShrot_SetCertificate(ProgramParameter(2)) : Failed("Setting the certificate") : EndIf + If Not BakaShrot_SetPrivateKey(ProgramParameter(3)) : Failed("Setting the private key") : EndIf + If Not BakaShrot_Connect(ProgramParameter(4), Val(ProgramParameter(5))) : Failed("Connecting") : EndIf + PrintN("Connected as " + BakaShrot_GetNodeString()) + + Id = BakaShrot_PushMessageTo("logs", ~"{\"from\": \"PureBasic\", \"text\": \"hello\"}") + If Id < 1 : Failed("Pushing") : EndIf + PrintN("Pushed #" + Str(Id)) + + If Not BakaShrot_GetLatestMessageOf("logs", BakaShrot_GetNodeString()) : Failed("Reading") : EndIf + PrintN("Latest: #" + Str(BakaShrot_GetMessageId()) + " " + BakaShrot_GetMessageDataString()) + + *Attachment = AllocateMemory(3000) + FillMemory(*Attachment, 3000, 42, #PB_Byte) + Id = BakaShrot_PushMessageWithData("logs", ~"{\"photo\": 1}", *Attachment, 3000) + If Id < 1 : Failed("Pushing an attachment") : EndIf + Size = BakaShrot_LoadAttachment("logs", BakaShrot_GetNodeString(), Id) + If Size < 0 : Failed("Reading the attachment") : EndIf + *Copy = AllocateMemory(Size) + BakaShrot_GetAttachmentData(*Copy, Size) + BakaShrot_FreeAttachmentData() + If CompareMemory(*Attachment, *Copy, 3000) + PrintN("Pushed #" + Str(Id) + " with " + Str(Size) + " bytes, read back the same") + Else + PrintN("The attachment read back differs") + End 1 + EndIf + FreeMemory(*Attachment) : FreeMemory(*Copy) + + If BakaShrot_ListTopics() < 0 : Failed("Listing") : EndIf + PrintN("Topics: " + BakaShrot_GetNamesListString()) + + If BakaShrot_PushMessageTo("nothing", "{}") < 0 + PrintN("A push to an unknown topic: " + BakaShrot_ErrorName(BakaShrot_GetLastError()) + ", " + BakaShrot_GetRefusalReasonString()) + EndIf + + BakaShrot_Disconnect() + PrintN("IsConnected after disconnecting: " + Str(BakaShrot_IsConnected())) + BakaShrot_UnloadClient() + End 0 + +CompilerEndIf diff --git a/Client/BakaShrot_ErrorCodes.pbi b/bindings/purebasic/BakaShrot_ErrorCodes.pbi similarity index 76% rename from Client/BakaShrot_ErrorCodes.pbi rename to bindings/purebasic/BakaShrot_ErrorCodes.pbi index 0ec758e..a3b9acf 100644 --- a/Client/BakaShrot_ErrorCodes.pbi +++ b/bindings/purebasic/BakaShrot_ErrorCodes.pbi @@ -6,10 +6,7 @@ ; ; ==- Compatibility -============================= ; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) +; * PureBasic 5.73 LTS (Windows x64) ; ; ==- Links -===================================== ; GitHub: https://github.com/aziascreations/BakaShrot @@ -19,10 +16,10 @@ ; BakaShrot error codes ; ; What BakaShrot_GetLastError() returns after a failed call of the client DLL -; (BakaShrot_Client.pbi), and the code a server sends with each refusal -; (RequestRefused, protocol 6). The Python client has the same numbers in -; bakashrot.ErrorCode. Shipped next to BakaShrot_Client_Prototypes.pbi, -; which includes it. +; (bakashrot.dll), and the code a server sends with each refusal (protocol 7, +; crates/bakashrot-proto/src/error.rs, the same numbers as protocol 6). +; The Python client has them in bakashrot.ErrorCode. Shipped next to +; BakaShrot_Client_Prototypes.pbi, which includes it. ; ; 0 no error (the last call succeeded) ; 1-99 refused by the server: the connection is still open, see @@ -34,38 +31,37 @@ ; ProtocolError (the connection is closed) ; retry later: NotReady (an attachment still on its way), ; ServerError (the server's storage failed) -; fix the config: AuthRejected, ServerNotVerified, NotAllowed, -; UnknownName, NoDefaultTopic +; fix the certificates or +; the server's config: AuthRejected, ServerNotVerified, NotAllowed, +; UnknownName, VersionMismatch ; fix the call: InvalidArgument, InvalidRequest, TooBig, ; QueryFailed, FileError ; gone, or not yet there: NotFound -; sent again by itself: DataMismatch (an upload that doesn't match its -; SHA-256: upload it again), AttachmentMismatch (a -; downloaded one that doesn't: read it again) +; sent again by itself: DataMismatch, AttachmentMismatch ; ; A push whose answer was lost (ConnectionLost) may still have been stored: ; pushing it again can store it twice, under the next id. Delivery is at ; least once; check the latest message first if a duplicate matters. ; ============================================================================ -; --- Refused by the server (RequestRefused's Code) ---------------------------- +; --- Refused by the server (RequestRefused's code) ---------------------------- -; Not allowed to this client: AllowRead / AllowWrite / AllowQuery, its -; PushTopics / ReadTopics, or a request only peers may make. +; Not allowed to this client: its roles' permissions (or, when connecting, +; none of its roles is the server's). #BakaShrot_Refused_NotAllowed = 1 -; A topic or node name (or id) this server doesn't know. +; A topic or node this server doesn't know. #BakaShrot_Refused_UnknownName = 2 -; No such message, attachment or upload. +; No such message or attachment. #BakaShrot_Refused_NotFound = 3 ; The attachment isn't on this server yet (still being replicated). #BakaShrot_Refused_NotReady = 4 ; A message, attachment or query result over a limit, or an attachment ; bigger than this server keeps. #BakaShrot_Refused_TooBig = 5 -; A push without a topic, and no DefaultTopic for this client. +; Protocol 6's (a push without a topic): never sent any more. #BakaShrot_Refused_NoDefaultTopic = 6 -; A request that doesn't fit: parts out of order, an upload for another -; topic or already attached, a part that doesn't exist... +; A request that doesn't fit: an attachment's parts not matching its size, +; a part that doesn't exist... #BakaShrot_Refused_InvalidRequest = 7 ; An uploaded attachment that doesn't match its SHA-256: dropped. #BakaShrot_Refused_DataMismatch = 8 @@ -84,11 +80,10 @@ #BakaShrot_Error_NotConnected = 100 ; The server couldn't be reached at that host and port. #BakaShrot_Error_ConnectFailed = 101 -; The server closed the connection during the handshake: wrong -; ServerPublicKey, a key or node it doesn't allow, or another protocol -; version (its log says which). +; The server refused this client's certificate: another CA's, revoked, +; expired. #BakaShrot_Error_AuthRejected = 102 -; The server couldn't prove it holds ServerPublicKey's private key. +; This client refused the server's certificate: not the CA's, or revoked. #BakaShrot_Error_ServerNotVerified = 103 ; The connection broke during a request (it's closed now). A push may ; still have been stored. @@ -96,8 +91,8 @@ ; The server answered something unexpected or malformed: the connection is ; closed. #BakaShrot_Error_ProtocolError = 105 -; A bad argument: a ref that's neither a name nor an id, a null pointer, a -; message or attachment over the limits, a setting missing before connecting. +; A bad argument: a topic or node that isn't a name, a null pointer, a +; message over the limit, a certificate missing before connecting. #BakaShrot_Error_InvalidArgument = 106 ; A file couldn't be opened, read or written. #BakaShrot_Error_FileError = 107 @@ -105,8 +100,11 @@ #BakaShrot_Error_AttachmentMismatch = 108 ; Already connected: disconnect first. #BakaShrot_Error_AlreadyConnected = 109 -; Out of memory, or another failure inside the client. +; A failure inside the DLL. #BakaShrot_Error_Internal = 110 +; The server speaks another version of the protocol: update one or the +; other. +#BakaShrot_Error_VersionMismatch = 111 ; The name of an error code, as the constants have it ("NotFound"), or @@ -135,6 +133,7 @@ Procedure.s BakaShrot_ErrorName(Code.l) Case #BakaShrot_Error_AttachmentMismatch : ProcedureReturn "AttachmentMismatch" Case #BakaShrot_Error_AlreadyConnected : ProcedureReturn "AlreadyConnected" Case #BakaShrot_Error_Internal : ProcedureReturn "Internal" + Case #BakaShrot_Error_VersionMismatch : ProcedureReturn "VersionMismatch" EndSelect ProcedureReturn "Error " + Str(Code) EndProcedure diff --git a/Interactors/Python/bakashrot.py b/bindings/python/bakashrot.py similarity index 56% rename from Interactors/Python/bakashrot.py rename to bindings/python/bakashrot.py index 28b1b37..1cc62f0 100644 --- a/Interactors/Python/bakashrot.py +++ b/bindings/python/bakashrot.py @@ -1,40 +1,38 @@ -"""BakaShrot client for Python, over BakaShrot_Client.dll. +"""BakaShrot client for Python, over the client DLL (bakashrot.dll, +libbakashrot.so). 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). +and does the connecting 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: + with Client.from_file("client.toml") as client: + message_id = client.push({"temperature": 21.5}, "sensors") + for message in client.get_messages("sensors", client.node, after=0): print(message.id, message.data) for message in client.follow("logs", "kitchen"): # until stopped print(message.id, message.json()) - photo_id = client.push({"kind": "photo"}, attachment="photo.jpg") - client.save_attachment("logs", "kitchen", photo_id, "copy.jpg") -Topics and nodes are "refs": a name ("logs") or an id (12, or "12"), ids -being the server's own. +Who the client is comes from its certificate, issued by the CA the server +trusts (bakashrot-cert): its name is its node, its roles say what it may +do. client.toml says where the server is and where the certificates are +(docs/client.md): -A message can have one attachment (a file, or bytes), of any size the -server takes: uploaded in parts before the message is stored, read back in -parts, checked with its SHA-256 (Design/Attachments.md). - -The connection only goes through to the server holding the private key of -server_public_key (client.ini's ServerPublicKey, the server logs it when it -starts), and everything on it is encrypted. + server = "10.0.0.2:7000" + ca = "ca.crt" + certificate = "kitchen.crt" + key = "kitchen.key" + # crl = "ca.crl" Errors are exceptions with a code (`error.code`, an ErrorCode, the same -numbers as the DLL's BakaShrot_GetLastError(), see -Client/BakaShrot_ErrorCodes.pbi): +numbers as the DLL's BakaShrot_GetLastError()): RefusedError the server refused (codes 1-99), still connected ConnectionLostError not connected, unreachable, the connection lost or broken: connect() again (nothing reconnects by itself) - AuthError the server rejected the handshake or couldn't prove - its key: fix the config, retrying won't help + AuthError a certificate refused, either way, or none of its + roles allowed: fix the certificates, retrying won't help BakaShrotError the rest: a bad argument, a file, the DLL itself A push whose answer was lost (ConnectionLostError) may have been stored all the same: pushed again, it's stored twice. Delivery is at least once. @@ -43,70 +41,66 @@ The DLL holds a single connection per process: only one Client may be connected at a time. Calls are serialized with a lock, so a Client can be shared between threads, one request at a time. -The DLL is 64-bit, so is the Python running this. It's looked for, in order: -the dll_path given, the BAKASHROT_DLL environment variable, next to this -file, then in the current directory. libsodium.dll must be next to it. -The wheel (make_wheel.py, `pip install bakashrot`) has them all next to -this file: nothing else to install or build. +The DLL is looked for, in order: the dll_path given, the BAKASHROT_DLL +environment variable, next to this file, then in the current directory. """ from __future__ import annotations -import configparser import ctypes import enum import json import os +import sys import threading import time from dataclasses import dataclass, field from datetime import datetime, timezone from typing import Any, Iterator, Optional, Union -# The release's, and the wheel's (make_wheel.py reads it from here). -__version__ = "0.0.1" +__version__ = "0.2.0" __all__ = [ - "Client", "Message", "MessagesPage", "NameEntry", "NamesList", + "Client", "Message", "MessagesPage", "NamesList", "BakaShrotError", "RefusedError", "ConnectionLostError", "AuthError", "ErrorCode", "MAX_GET_MESSAGES", "MAX_MESSAGE_SIZE", ] -# Same as the server: Commons/Networking/Packets.pbi, GetMessagesPacket.pbi. +# The protocol's: crates/bakashrot-proto/src/limits.rs. MAX_GET_MESSAGES = 10000 MAX_MESSAGE_SIZE = 16 * 1024 * 1024 - 4096 -Ref = Union[str, int] +DLL_NAME = "bakashrot.dll" if sys.platform == "win32" else "libbakashrot.so" class ErrorCode(enum.IntEnum): - """What failed: Client/BakaShrot_ErrorCodes.pbi, the same numbers. + """What failed: the protocol's codes (crates/bakashrot-proto/src/error.rs). 1-99: refused by the server, 100+: the client's own.""" NONE = 0 # Refused by the server, the connection still open. - NOT_ALLOWED = 1 # AllowRead/Write/Query, PushTopics/ReadTopics + NOT_ALLOWED = 1 # its roles don't allow it (or none is the server's, when connecting) UNKNOWN_NAME = 2 # a topic or node this server doesn't know - NOT_FOUND = 3 # no such message, attachment or upload + NOT_FOUND = 3 # no such message or attachment NOT_READY = 4 # the attachment isn't on this server yet: retry later TOO_BIG = 5 # over a limit, or more than this server keeps - NO_DEFAULT_TOPIC = 6 # a push without a topic, and no DefaultTopic - INVALID_REQUEST = 7 # parts out of order, an upload for another topic... + NO_DEFAULT_TOPIC = 6 # protocol 6's, never sent any more + INVALID_REQUEST = 7 # a request that doesn't fit (parts out of order...) DATA_MISMATCH = 8 # an upload that doesn't match its SHA-256 QUERY_FAILED = 9 # the SQL failed SERVER_ERROR = 10 # the server's database failed: retry later # The client's own. NOT_CONNECTED = 100 # never connected, or closed or lost before CONNECT_FAILED = 101 # nothing answers at that host and port - AUTH_REJECTED = 102 # the server closed the handshake: wrong ServerPublicKey, - # a key or node it doesn't allow, another version - SERVER_NOT_VERIFIED = 103 # the server couldn't prove its key + AUTH_REJECTED = 102 # the server refused this client's certificate + SERVER_NOT_VERIFIED = 103 # this client refused the server's certificate CONNECTION_LOST = 104 # broke during a request (a push may still be stored) PROTOCOL_ERROR = 105 # an unexpected answer, the connection is closed INVALID_ARGUMENT = 106 FILE_ERROR = 107 ATTACHMENT_MISMATCH = 108 # a downloaded attachment that doesn't match its SHA-256 ALREADY_CONNECTED = 109 - INTERNAL = 110 # out of memory, the DLL missing or too old... + INTERNAL = 110 # a failure inside the DLL, or the DLL missing or too old + VERSION_MISMATCH = 111 # the server speaks another protocol version @property def is_refusal(self) -> bool: @@ -145,26 +139,23 @@ class ConnectionLostError(BakaShrotError): class AuthError(BakaShrotError): - """The server rejected the handshake (AUTH_REJECTED) or couldn't prove it - holds server_public_key's private key (SERVER_NOT_VERIFIED): a config to - fix, connecting again won't help.""" + """Connecting was refused for good: the server refused this client's + certificate (AUTH_REJECTED), this client the server's + (SERVER_NOT_VERIFIED), none of its roles is allowed (NOT_ALLOWED), or + another protocol version (VERSION_MISMATCH). Retrying won't help.""" @dataclass(frozen=True) class Message: - """A stored message. data is as stored: JSON or not (the server's - is_json column tells which, json() parses it). pushed_at: when it was - pushed, to whichever server it was pushed to, in milliseconds since - 1970-01-01 UTC (pushed is the same as a datetime). attachment_size: its - attachment's, 0 for none; attachment_ready: whether all of it is on - this server (a replicated one comes after its message), see - Client.get_attachment() and save_attachment().""" + """A stored message. data is as stored: JSON or not (json() parses it). + pushed_at: when it was pushed, to whichever server it was pushed to, in + milliseconds since 1970-01-01 UTC (pushed is the same as a datetime). + attachment_size: its attachment's, 0 for none; attachment_ready: + whether all of it is on this server.""" id: int topic: str node: str - topic_id: int - node_id: int data: str pushed_at: int = 0 attachment_size: int = 0 @@ -199,26 +190,17 @@ class MessagesPage: 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 + names: 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 _name(value: str) -> bytes: + if not isinstance(value, str): + raise TypeError(f"a topic or node is a name, not {value!r}") + return value.encode("utf-8") def _find_dll(dll_path: Optional[str]) -> str: @@ -227,12 +209,12 @@ def _find_dll(dll_path: Optional[str]) -> str: 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")) + candidates.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), DLL_NAME)) + candidates.append(os.path.join(os.getcwd(), DLL_NAME)) 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)) + raise BakaShrotError(f"{DLL_NAME} not found, looked at: " + ", ".join(candidates)) class _Dll: @@ -249,24 +231,24 @@ class _Dll: 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 + raise BakaShrotError(f"Failed to load {path}: {error}") from error self.path = path I, L, Q, P, S = ctypes.c_ssize_t, ctypes.c_int32, ctypes.c_int64, ctypes.c_char_p, ctypes.c_void_p signatures = { "BakaShrot_GetLastError": (L, []), + "BakaShrot_GetRefusalReasonA": (I, [S, I]), + "BakaShrot_SetCaCertificateA": (I, [P]), + "BakaShrot_SetCertificateA": (I, [P]), "BakaShrot_SetPrivateKeyA": (I, [P]), - "BakaShrot_SetPublicKeyA": (I, [P]), - "BakaShrot_SetServerPublicKeyA": (I, [P]), - "BakaShrot_SetNodeA": (I, [P]), + "BakaShrot_SetCrlA": (I, [P]), "BakaShrot_ConnectA": (I, [P, L]), "BakaShrot_IsConnected": (I, []), "BakaShrot_Disconnect": (I, []), + "BakaShrot_GetNodeA": (I, [S, I]), "BakaShrot_PushMessageToA": (Q, [P, P]), "BakaShrot_GetLatestMessageOfA": (I, [P, P]), "BakaShrot_GetMessagesA": (L, [P, P, Q, L]), @@ -277,26 +259,20 @@ class _Dll: "BakaShrot_GetMessagePushedAt": (Q, []), "BakaShrot_GetMessageAttachmentSize": (Q, []), "BakaShrot_IsMessageAttachmentReady": (I, []), - "BakaShrot_PushMessageWithFileA": (Q, [P, P, P]), - "BakaShrot_PushMessageWithDataA": (Q, [P, P, S, Q]), - "BakaShrot_SaveAttachmentA": (Q, [P, P, Q, P]), - "BakaShrot_LoadAttachmentA": (Q, [P, P, Q]), - "BakaShrot_GetAttachmentData": (Q, [S, Q]), - "BakaShrot_FreeAttachmentData": (I, []), - "BakaShrot_GetMessageTopicId": (L, []), - "BakaShrot_GetMessageNodeId": (L, []), "BakaShrot_GetMessageTopicA": (I, [S, I]), "BakaShrot_GetMessageNodeA": (I, [S, I]), "BakaShrot_GetMessageDataA": (I, [S, I]), - "BakaShrot_ResolveTopicA": (L, [P]), - "BakaShrot_ResolveNodeA": (L, [P]), - "BakaShrot_GetResolvedNameA": (I, [S, I]), "BakaShrot_ListTopics": (L, []), "BakaShrot_ListNodes": (L, []), "BakaShrot_GetNamesListA": (I, [S, I]), "BakaShrot_QueryA": (I, [P]), "BakaShrot_GetQueryResultA": (I, [S, I]), - "BakaShrot_GetRefusalReasonA": (I, [S, I]), + "BakaShrot_PushMessageWithFileA": (Q, [P, P, P]), + "BakaShrot_PushMessageWithDataA": (Q, [P, P, P, Q]), + "BakaShrot_SaveAttachmentA": (Q, [P, P, Q, P]), + "BakaShrot_LoadAttachmentA": (Q, [P, P, Q]), + "BakaShrot_GetAttachmentData": (Q, [S, Q]), + "BakaShrot_FreeAttachmentData": (I, []), } for name, (restype, argtypes) in signatures.items(): try: @@ -317,59 +293,73 @@ class _Dll: return buffer.raw[: size - 1].decode("utf-8") +def _split_server(server: str) -> tuple: + """"host:port" (an IPv6 address in brackets) as (host, port).""" + host, _, port = server.rpartition(":") + if not host or not port.isdigit(): + raise BakaShrotError(f"server is host:port, not {server!r}", ErrorCode.INVALID_ARGUMENT) + return host.strip("[]"), int(port) + + class Client: """A connection to a BakaShrot server, through the DLL. - private_key, public_key: the client's Ed25519 keys in Base64 (BakaShrotGenerateKeyPairs.exe). - server_public_key: the server's Ed25519 public key in Base64, it must - prove it holds the matching private key. - node: the node the client writes as, a name or an id, which the - server's [BakaShrot.Client.] must give its key (Node). Its - default topic, for pushes that don't name one, is the server's to say - (that section's DefaultTopic). + server: "host:port". ca, certificate, key, crl (optional): PEM text, or + the paths of files holding it: the CA's certificate (the server's must + be issued by it), this client's certificate (its node, its roles) and + its private key, the CA's CRL (servers it revokes are refused). """ _connected_client: Optional["Client"] = None - def __init__(self, private_key: str, public_key: str, server_public_key: str, node: Ref, - host: str = "127.0.0.1", port: int = 12345, dll_path: Optional[str] = None): + def __init__(self, server: str, ca: str, certificate: str, key: str, crl: Optional[str] = None, + dll_path: Optional[str] = None): self._dll = _Dll.get(dll_path) self._lock = threading.RLock() - self.private_key = private_key - self.public_key = public_key - self.server_public_key = server_public_key - self.node = node - self.host = host - self.port = int(port) + self.host, self.port = _split_server(server) + self.ca = os.fspath(ca) + self.certificate = os.fspath(certificate) + self.key = os.fspath(key) + self.crl = os.fspath(crl) if crl else None + self.node = "" @classmethod - def from_ini(cls, path: str, dll_path: Optional[str] = None) -> "Client": - """From a client.ini as the tools read it: [BakaShrot] PrivateKey, - PublicKey, ServerPublicKey, Node, ServerHost, ServerPort (a Topic - left in it is ignored).""" - parser = configparser.ConfigParser(interpolation=None) - if not parser.read(path, encoding="utf-8-sig"): - raise BakaShrotError(f"Failed to open '{path}'", ErrorCode.FILE_ERROR) - section = parser["BakaShrot"] if parser.has_section("BakaShrot") else {} + def from_file(cls, path: Union[str, os.PathLike], dll_path: Optional[str] = None) -> "Client": + """From a client.toml (server, ca, certificate, key, crl), the tools' + too; paths in it are relative to its folder. Needs Python 3.11+ + (tomllib).""" + import tomllib - def get(key, fallback=None): - value = section.get(key, fallback) - if value is None: - raise BakaShrotError(f"'{path}' has no [BakaShrot] {key}", ErrorCode.INVALID_ARGUMENT) - return value.strip() + try: + with open(path, "rb") as file: + settings = tomllib.load(file) + except OSError as error: + raise BakaShrotError(f"Failed to open '{path}': {error}", ErrorCode.FILE_ERROR) from error + except tomllib.TOMLDecodeError as error: + raise BakaShrotError(f"'{path}': {error}", ErrorCode.INVALID_ARGUMENT) from error + folder = os.path.dirname(os.path.abspath(path)) - return cls(get("PrivateKey"), get("PublicKey"), get("ServerPublicKey"), - get("Node", section.get("NodeId")), - get("ServerHost"), int(get("ServerPort")), dll_path) + def get(key, required=True): + value = settings.get(key) + if value is None and required: + raise BakaShrotError(f"'{path}' has no {key}", ErrorCode.INVALID_ARGUMENT) + if not isinstance(value, (str, type(None))): + raise BakaShrotError(f"'{path}': {key} is a string", ErrorCode.INVALID_ARGUMENT) + return value + + def file(key, required=True): + value = get(key, required) + return os.path.join(folder, value) if value else None + + return cls(get("server"), file("ca"), file("certificate"), file("key"), file("crl", False), dll_path) # --- Connection -------------------------------------------------------- def connect(self) -> "Client": - """Connects and authenticates. Raises ConnectionLostError when the - server can't be reached (CONNECT_FAILED), AuthError when it rejects - the handshake or can't prove its key, BakaShrotError on a bad setting - (INVALID_ARGUMENT) or another Client holding the DLL's connection - (ALREADY_CONNECTED).""" + """Connects. Raises ConnectionLostError when the server can't be + reached (CONNECT_FAILED), AuthError when a certificate is refused, + BakaShrotError on a bad setting (INVALID_ARGUMENT, FILE_ERROR) or + another Client holding the DLL's connection (ALREADY_CONNECTED).""" with self._lock: owner = Client._connected_client if owner is not None and owner is not self and owner.connected: @@ -377,16 +367,13 @@ class Client: if self.connected: return self dll = self._dll - if not dll.SetPrivateKeyA(self.private_key.encode("ascii")): - raise BakaShrotError("Invalid private key", dll.GetLastError()) - if not dll.SetPublicKeyA(self.public_key.encode("ascii")): - raise BakaShrotError("Invalid public key", dll.GetLastError()) - if not dll.SetServerPublicKeyA(self.server_public_key.encode("ascii")): - raise BakaShrotError("Invalid server public key", dll.GetLastError()) - if not dll.SetNodeA(_ref(self.node)): - raise BakaShrotError(f"Invalid node {self.node!r}", dll.GetLastError()) + for setter, value in ((dll.SetCaCertificateA, self.ca), (dll.SetCertificateA, self.certificate), + (dll.SetPrivateKeyA, self.key), (dll.SetCrlA, self.crl or "")): + if not setter(value.encode("utf-8")): + raise self._failed("Certificates") if not dll.ConnectA(self.host.encode("utf-8"), self.port): - raise self._failed(f"Connect to {self.host}:{self.port}") + raise self._failed(f"Connect to {self.host}:{self.port}", connecting=True) + self.node = dll.string(dll.GetNodeA) Client._connected_client = self return self @@ -410,92 +397,77 @@ class Client: if not self.connected: raise ConnectionLostError("Not connected", ErrorCode.NOT_CONNECTED) - _MESSAGES = { - ErrorCode.NOT_CONNECTED: "not connected", - ErrorCode.CONNECT_FAILED: "nothing answers there", - ErrorCode.AUTH_REJECTED: "the server closed the connection during the handshake: wrong server public key, " - "a key or node it doesn't allow, or another version (its log says which)", - ErrorCode.SERVER_NOT_VERIFIED: "the server couldn't prove it holds the server public key's private key", - ErrorCode.CONNECTION_LOST: "the connection to the server failed", - ErrorCode.PROTOCOL_ERROR: "the server answered something unexpected, the connection is closed", - } - - def _failed(self, what: str) -> BakaShrotError: + def _failed(self, what: str, connecting: bool = False) -> BakaShrotError: """The error for a failed call, by the DLL's BakaShrot_GetLastError().""" code = _error_code(self._dll.GetLastError()) reason = self._dll.string(self._dll.GetRefusalReasonA) + if connecting and code in (ErrorCode.AUTH_REJECTED, ErrorCode.SERVER_NOT_VERIFIED, + ErrorCode.NOT_ALLOWED, ErrorCode.VERSION_MISMATCH): + return AuthError(f"{what}: {reason}", code) if isinstance(code, int) and 1 <= int(code) <= 99: return RefusedError(reason, code) if not self._dll.IsConnected() and Client._connected_client is self: Client._connected_client = None name = code.name if isinstance(code, ErrorCode) else str(code) - message = f"{what} ({name}): {reason or self._MESSAGES.get(code, 'failed')}" + message = f"{what} ({name}): {reason or 'failed'}" if code in (ErrorCode.NOT_CONNECTED, ErrorCode.CONNECT_FAILED, ErrorCode.CONNECTION_LOST, ErrorCode.PROTOCOL_ERROR): return ConnectionLostError(message, code) - if code in (ErrorCode.AUTH_REJECTED, ErrorCode.SERVER_NOT_VERIFIED): - return AuthError(message, code) return BakaShrotError(message, code if code else ErrorCode.INTERNAL) # --- Requests ---------------------------------------------------------- - def push(self, data: Any, topic: Optional[Ref] = None, + def push(self, data: Any, topic: str, attachment: Union[None, bytes, bytearray, memoryview, str, os.PathLike] = None) -> int: - """Pushes a message into topic (default: the client's default one, its server's DefaultTopic), under - the client's node. data is stored as is if it's a str (JSON or not), - anything else is turned into JSON first. Returns its message id. + """Pushes a message into topic, under the client's node. data is + stored as is if it's a str (JSON or not), anything else is turned + into JSON first. Returns its message id. - attachment: bytes, or the path of a file, uploaded first (in parts, - any size the server's MaxAttachmentSize allows): the message is only - stored once all of it is.""" + attachment: bytes, or the path of a file, uploaded with it (1 byte + and up, as much as the server's max_attachment_size takes): the + message is only stored once all of it came.""" if not isinstance(data, str): data = json.dumps(data, separators=(",", ":"), ensure_ascii=False) encoded = data.encode("utf-8") if len(encoded) > MAX_MESSAGE_SIZE: raise BakaShrotError(f"The message is too big: {len(encoded)} bytes, at most {MAX_MESSAGE_SIZE}", ErrorCode.INVALID_ARGUMENT) - topic_ref = b"" if topic is None else _ref(topic) with self._lock: self._check_connected() if attachment is None: - message_id = self._dll.PushMessageToA(topic_ref, encoded) + message_id = self._dll.PushMessageToA(_name(topic), encoded) elif isinstance(attachment, (bytes, bytearray, memoryview)): raw = bytes(attachment) - if not raw: - raise BakaShrotError("The attachment is empty", ErrorCode.INVALID_ARGUMENT) - buffer = ctypes.create_string_buffer(raw, len(raw)) - message_id = self._dll.PushMessageWithDataA(topic_ref, encoded, ctypes.cast(buffer, ctypes.c_void_p), len(raw)) + message_id = self._dll.PushMessageWithDataA(_name(topic), encoded, raw, len(raw)) else: - path = os.fspath(attachment) - if not os.path.isfile(path) or os.path.getsize(path) == 0: - raise BakaShrotError(f"Can't attach {path!r}: no such file, or empty", ErrorCode.FILE_ERROR) - message_id = self._dll.PushMessageWithFileA(topic_ref, encoded, path.encode("utf-8")) + path = os.fspath(attachment).encode("utf-8") + message_id = self._dll.PushMessageWithFileA(_name(topic), encoded, path) if message_id < 1: raise self._failed("Push") return message_id - def get_attachment(self, topic: Ref, node: Ref, message_id: int) -> bytes: - """The attachment of topic:node#message_id, all of it in memory - (save_attachment() for big ones), checked with its SHA-256. Raises - RefusedError if the message has none, or it isn't on this server - yet.""" + def get_attachment(self, topic: str, node: str, message_id: int) -> bytes: + """The attachment of a message, all of it in memory (save_attachment() + for big ones), checked with its SHA-256. RefusedError if it has none + (NOT_FOUND) or it isn't on this server yet (NOT_READY).""" with self._lock: self._check_connected() - size = self._dll.LoadAttachmentA(_ref(topic), _ref(node), int(message_id)) + size = self._dll.LoadAttachmentA(_name(topic), _name(node), int(message_id)) if size < 0: raise self._failed("Attachment") try: buffer = ctypes.create_string_buffer(size) - self._dll.GetAttachmentData(ctypes.cast(buffer, ctypes.c_void_p), size) + self._dll.GetAttachmentData(buffer, size) return buffer.raw[:size] finally: self._dll.FreeAttachmentData() - def save_attachment(self, topic: Ref, node: Ref, message_id: int, path: Union[str, os.PathLike]) -> int: - """Saves the attachment of topic:node#message_id to path (replaced), - a part at a time, checked with its SHA-256. Returns its size. A - failed one leaves no file.""" + def save_attachment(self, topic: str, node: str, message_id: int, path: Union[str, os.PathLike]) -> int: + """Saves the attachment of a message as path (replaced), a part at a + time, checked with its SHA-256. Returns its size. A failed one + leaves no file.""" with self._lock: self._check_connected() - size = self._dll.SaveAttachmentA(_ref(topic), _ref(node), int(message_id), os.fspath(path).encode("utf-8")) + size = self._dll.SaveAttachmentA(_name(topic), _name(node), int(message_id), + os.fspath(path).encode("utf-8")) if size < 0: raise self._failed("Attachment") return size @@ -503,21 +475,21 @@ class Client: def _current(self) -> Message: dll = self._dll return Message(dll.GetMessageId(), dll.string(dll.GetMessageTopicA), dll.string(dll.GetMessageNodeA), - dll.GetMessageTopicId(), dll.GetMessageNodeId(), dll.string(dll.GetMessageDataA), - dll.GetMessagePushedAt(), dll.GetMessageAttachmentSize(), bool(dll.IsMessageAttachmentReady())) + dll.string(dll.GetMessageDataA), dll.GetMessagePushedAt(), dll.GetMessageAttachmentSize(), + bool(dll.IsMessageAttachmentReady())) - def latest(self, topic: Ref, node: Ref) -> Optional[Message]: + def latest(self, topic: str, node: str) -> 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)): + if not self._dll.GetLatestMessageOfA(_name(topic), _name(node)): error = self._failed("Latest message") if isinstance(error, RefusedError) and error.code == ErrorCode.NOT_FOUND: return None raise error return self._current() - def get_messages(self, topic: Ref, node: Ref, after: int = 0, limit: int = 1000) -> MessagesPage: + def get_messages(self, topic: str, node: str, 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 @@ -529,7 +501,7 @@ class Client: with self._lock: self._check_connected() dll = self._dll - count = dll.GetMessagesA(_ref(topic), _ref(node), after, limit) + count = dll.GetMessagesA(_name(topic), _name(node), after, limit) if count < 0: raise self._failed("Get messages") messages = [] @@ -538,7 +510,7 @@ class Client: 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]: + def iter_messages(self, topic: str, node: str, 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: @@ -549,7 +521,7 @@ class Client: if not page.more: return - def follow(self, topic: Ref, node: Ref, after: Union[int, str] = "latest", + def follow(self, topic: str, node: str, 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: @@ -569,28 +541,12 @@ class Client: 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.""" + """The topics the client may push to or read (every one if it may query).""" return self._list(self._dll.ListTopics, "List topics") def list_nodes(self) -> NamesList: - """Every node, with this server's ids.""" + """Every node with messages.""" return self._list(self._dll.ListNodes, "List nodes") def _list(self, function, what: str) -> NamesList: @@ -599,16 +555,15 @@ class Client: 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"])) + return NamesList(parsed["kind"], parsed["names"], 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: + """Runs one read-only SELECT on the server (a role with query = + true), 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".""" + query is refused: RefusedError "malformed JSON".""" with self._lock: self._check_connected() if not self._dll.QueryA(sql.encode("utf-8")): diff --git a/Interactors/Python/check_bakashrot.py b/bindings/python/check_bakashrot.py similarity index 66% rename from Interactors/Python/check_bakashrot.py rename to bindings/python/check_bakashrot.py index 81b9722..dcf6636 100644 --- a/Interactors/Python/check_bakashrot.py +++ b/bindings/python/check_bakashrot.py @@ -1,22 +1,24 @@ -"""Checks bakashrot.py against a running server, run by Tests/Python-Test.ps1. +"""Checks bakashrot.py and the DLL against a running server, run by +crates/bakashrot-capi/tests/python.rs (which starts the server and writes +the certificates and client.toml files). -Usage: python check_bakashrot.py - KitchenIni logs:kitchen, may push to logs and secret, read everything, query. - LoungeIni logs:lounge, may read logs only. +Usage: python check_bakashrot.py + Folder/kitchen.toml node kitchen: may push to logs and secret, read everything, query. + Folder/lounge.toml node lounge: may read logs only. + Folder/guest.toml node guest: none of its roles is the server's. Expects an empty database. Prints PASS/FAIL per check, exits 1 if any failed. """ import hashlib import os import sys -import tempfile import threading import time import bakashrot from bakashrot import AuthError, BakaShrotError, Client, ConnectionLostError, ErrorCode, RefusedError -dll_path, kitchen_ini, lounge_ini = sys.argv[1:4] +dll_path, folder = sys.argv[1:3] fails = 0 @@ -38,14 +40,15 @@ def raises(function, error_type, contains="", code=None): return contains in str(error) and (code is None or got == code), f"{type(error).__name__} [{got!r}]: {error}" except Exception as error: # noqa: BLE001 - reported as a failure return False, f"{type(error).__name__}: {error}" - return False, "didn't raise" + return False, "no exception" -kitchen = Client.from_ini(kitchen_ini, dll_path) -lounge = Client.from_ini(lounge_ini, dll_path) +kitchen = Client.from_file(os.path.join(folder, "kitchen.toml"), dll_path) +lounge = Client.from_file(os.path.join(folder, "lounge.toml"), dll_path) with kitchen: - check("Connects from client.ini", kitchen.connected, kitchen._dll.path) + check("Connects from kitchen.toml, the node from its certificate", kitchen.connected and kitchen.node == "kitchen", + f"{kitchen.node!r}, {kitchen._dll.path}") # --- Nothing yet --------------------------------------------------------- check("latest() with no messages: None", kitchen.latest("logs", "kitchen") is None) @@ -54,7 +57,7 @@ with kitchen: # --- Pushes -------------------------------------------------------------- started = time.perf_counter() - ids = [kitchen.push({"i": i}) for i in range(1, 251)] + ids = [kitchen.push({"i": i}, "logs") 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") @@ -68,18 +71,13 @@ with kitchen: latest is not None and latest.pushed.tzinfo is not None and latest.pushed.utcoffset().total_seconds() == 0 and int(latest.pushed.timestamp() * 1000) == latest.pushed_at, latest.pushed if latest else None) - topic_id, topic_name = kitchen.resolve_topic("logs") - node_id, node_name = kitchen.resolve_node("kitchen") - check("resolve_topic/node()", (topic_id, topic_name, node_id, node_name) == (1, "logs", 5, "kitchen"), - (topic_id, topic_name, node_id, node_name)) - # --- Pages --------------------------------------------------------------- page = kitchen.get_messages("logs", "kitchen", after=0, limit=100) check("First page: 1-100, more", [m.id for m in page] == list(range(1, 101)) and page.more and page.last_id == 100, f"{len(page)} messages, more={page.more}") first = page.messages[0] - check("A message's fields", (first.topic, first.node, first.topic_id, first.node_id, first.data, first.json()) - == ("logs", "kitchen", 1, 5, '{"i":1}', {"i": 1}), first) + check("A message's fields", (first.topic, first.node, first.data, first.json(), first.attachment_size) + == ("logs", "kitchen", '{"i":1}', {"i": 1}, 0), first) stamps = [m.pushed_at for m in page] check("Each message of a page has its pushed_at, in push order", all(stamps) and stamps == sorted(stamps), f"{stamps[0]} .. {stamps[-1]}") @@ -92,16 +90,16 @@ with kitchen: 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) + page = kitchen.get_messages("LOGS", "Kitchen", after=250) + check("After the last one, names in another case: 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("") + text_id = kitchen.push("plain text, not JSON", "logs") + unicode_id = kitchen.push("héllo wörld, 🌍, 日本語", "logs") + empty_id = kitchen.push("", "logs") 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", @@ -117,7 +115,7 @@ with kitchen: # --- Answers split at ~1 MB ---------------------------------------------- big = "x" * (700 * 1024) - big_ids = [kitchen.push(big) for _ in range(3)] + big_ids = [kitchen.push(big, "logs") 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}") @@ -126,22 +124,29 @@ with kitchen: [len(m.data) for m in every]) # --- Refusals ------------------------------------------------------------ - ok, detail = raises(lambda: kitchen.get_messages("logs", "nobody"), RefusedError, "Unknown node 'nobody'", ErrorCode.UNKNOWN_NAME) + ok, detail = raises(lambda: kitchen.get_messages("logs", "nobody"), RefusedError, "unknown node 'nobody'", ErrorCode.UNKNOWN_NAME) check("Unknown node: RefusedError, UNKNOWN_NAME", ok, detail) check("Still connected after a refusal", kitchen.connected and kitchen.latest("logs", "kitchen").id == big_ids[-1]) ok, detail = raises(lambda: kitchen.get_messages("logs", "kitchen", limit=0), ValueError) check("limit 0: ValueError, before asking", ok, detail) ok, detail = raises(lambda: kitchen.get_messages("logs", "kitchen", after=-1), ValueError) check("after -1: ValueError", ok, detail) - ok, detail = raises(lambda: kitchen.push("x", topic="nothing"), RefusedError, "Unknown topic", ErrorCode.UNKNOWN_NAME) + ok, detail = raises(lambda: kitchen.push("x", "nothing"), RefusedError, "unknown topic", ErrorCode.UNKNOWN_NAME) check("Push to an unknown topic: RefusedError, UNKNOWN_NAME", ok, detail) - secret_id = kitchen.push({"s": 1}, topic="secret") + ok, detail = raises(lambda: kitchen.push("x", "a b"), BakaShrotError, "isn't a topic name", ErrorCode.INVALID_ARGUMENT) + check("A topic that isn't a name: refused before sending", ok, detail) + ok, detail = raises(lambda: kitchen.push("x" * (bakashrot.MAX_MESSAGE_SIZE + 1), "logs"), BakaShrotError, "too big", + ErrorCode.INVALID_ARGUMENT) + check("A message over the limit: refused before sending", ok, detail) + secret_id = kitchen.push({"s": 1}, "secret") check("Push to another allowed topic", secret_id == 1, secret_id) ok, detail = raises(lambda: lounge.connect(), BakaShrotError, "one connection", ErrorCode.ALREADY_CONNECTED) check("A second Client can't connect while one is", ok and not lounge.connected, detail) topics = kitchen.list_topics() - check("list_topics()", topics.kind == "topic" and {"logs", "secret"} <= {t.name for t in topics.items}, topics) + check("list_topics()", topics.kind == "topic" and topics.names == ["logs", "secret"] and not topics.truncated, topics) + nodes = kitchen.list_nodes() + check("list_nodes()", nodes.kind == "node" and nodes.names == ["kitchen"], nodes) # --- follow() ------------------------------------------------------------ followed = [] @@ -159,16 +164,16 @@ with kitchen: thread = threading.Thread(target=follower, daemon=True) thread.start() time.sleep(0.5) - new_ids = [kitchen.push({"f": i}) for i in range(5)] + new_ids = [kitchen.push({"f": i}, "logs") for i in range(5)] thread.join(10) check("follow(after='latest') from another thread: only the 5 new ones", not thread.is_alive() and not errors and [m.id for m in followed] == new_ids, f"{[m.id for m in followed]} vs {new_ids}, errors {errors}") - # --- Attachments (in secret, the other checks count logs) ------------------- + # --- Attachments (in secret, the other checks count logs) ---------------- blob = os.urandom(3 * 1024 * 1024 + 7) started = time.perf_counter() - blob_id = kitchen.push({"kind": "blob"}, topic="secret", attachment=blob) + blob_id = kitchen.push({"kind": "blob"}, "secret", attachment=blob) up = time.perf_counter() - started message = kitchen.latest("secret", "kitchen") check("push(attachment=bytes): the message has it, ready", @@ -179,50 +184,63 @@ with kitchen: down = time.perf_counter() - started check("get_attachment(): the same bytes", data == blob, f"{len(data)} bytes, {up * 1000:.0f} ms up, {down * 1000:.0f} ms down") - folder = tempfile.mkdtemp() source = os.path.join(folder, "source.bin") with open(source, "wb") as file: file.write(os.urandom(1500 * 1024)) - file_id = kitchen.push("from a file", topic="secret", attachment=source) + file_id = kitchen.push("from a file", "secret", attachment=source) copy = os.path.join(folder, "copy.bin") size = kitchen.save_attachment("secret", "kitchen", file_id, copy) with open(source, "rb") as a, open(copy, "rb") as b: same = hashlib.sha256(a.read()).digest() == hashlib.sha256(b.read()).digest() check("push(attachment=path), save_attachment(): the same file", size == os.path.getsize(source) and same, size) - plain_id = kitchen.push("no attachment", topic="secret") + plain_id = kitchen.push("no attachment", "secret") page = kitchen.get_messages("secret", "kitchen", after=blob_id - 1) sizes = [(m.id, m.attachment_size, m.attachment_ready) for m in page] check("get_messages(): each message's attachment", sizes == [(blob_id, len(blob), True), (file_id, os.path.getsize(source), True), (plain_id, 0, False)], sizes) - ok, detail = raises(lambda: kitchen.get_attachment("secret", "kitchen", plain_id), RefusedError, "No attachment", ErrorCode.NOT_FOUND) + ok, detail = raises(lambda: kitchen.get_attachment("secret", "kitchen", plain_id), RefusedError, "no attachment", ErrorCode.NOT_FOUND) check("get_attachment() of a message without: RefusedError, NOT_FOUND", ok, detail) - ok, detail = raises(lambda: kitchen.push("x", topic="secret", attachment=b""), BakaShrotError, "empty", ErrorCode.INVALID_ARGUMENT) + none = os.path.join(folder, "none.bin") + ok, detail = raises(lambda: kitchen.save_attachment("secret", "kitchen", plain_id, none), RefusedError, code=ErrorCode.NOT_FOUND) + check("save_attachment() refused: no file left", ok and not os.path.exists(none), detail) + ok, detail = raises(lambda: kitchen.push("x", "secret", attachment=b""), BakaShrotError, "0 bytes", ErrorCode.INVALID_ARGUMENT) check("An empty attachment: refused before sending", ok, detail) - ok, detail = raises(lambda: kitchen.push("x", topic="secret", attachment=os.path.join(folder, "missing.bin")), BakaShrotError, "no such file", ErrorCode.FILE_ERROR) + ok, detail = raises(lambda: kitchen.push("x", "secret", attachment=os.path.join(folder, "missing.bin")), BakaShrotError, + "missing.bin", ErrorCode.FILE_ERROR) check("A missing file: refused before sending", ok, detail) check("Still connected", kitchen.connected) check("close(): disconnected", not kitchen.connected) -ok, detail = raises(lambda: kitchen.push("x"), ConnectionLostError, code=ErrorCode.NOT_CONNECTED) +ok, detail = raises(lambda: kitchen.push("x", "logs"), ConnectionLostError, code=ErrorCode.NOT_CONNECTED) check("A request once closed: ConnectionLostError, NOT_CONNECTED", ok, detail) -# --- Connecting: unreachable, rejected --------------------------------------- -nowhere = Client(kitchen.private_key, kitchen.public_key, kitchen.server_public_key, kitchen.node, "127.0.0.1", 1, dll_path) +# --- Connecting: unreachable, refused, PEM text ---------------------------------- +with open(kitchen.ca) as ca, open(kitchen.certificate) as certificate, open(kitchen.key) as key: + pem = (ca.read(), certificate.read(), key.read()) +nowhere = Client("127.0.0.1:1", *pem, dll_path=dll_path) ok, detail = raises(nowhere.connect, ConnectionLostError, code=ErrorCode.CONNECT_FAILED) check("Nothing listening: ConnectionLostError, CONNECT_FAILED", ok, detail) -stranger = Client(kitchen.private_key, kitchen.public_key, kitchen.server_public_key, "nobody", kitchen.host, kitchen.port, dll_path) -ok, detail = raises(stranger.connect, AuthError, code=ErrorCode.AUTH_REJECTED) -check("A node the server doesn't give this key: AuthError, AUTH_REJECTED", ok, detail) +guest = Client.from_file(os.path.join(folder, "guest.toml"), dll_path) +ok, detail = raises(guest.connect, AuthError, "guest", ErrorCode.NOT_ALLOWED) +check("None of its roles allowed: AuthError, NOT_ALLOWED", ok, detail) +missing = Client(f"{kitchen.host}:{kitchen.port}", os.path.join(folder, "missing.crt"), *pem[1:], dll_path=dll_path) +ok, detail = raises(missing.connect, BakaShrotError, "missing.crt", ErrorCode.FILE_ERROR) +check("A certificate file that isn't there: FILE_ERROR", ok, detail) +with Client(f"{kitchen.host}:{kitchen.port}", *pem, dll_path=dll_path) as again: + check("The same identity from PEM text: connected", again.connected and again.node == "kitchen", again.node) with lounge: page = lounge.get_messages("logs", "kitchen", after=245, limit=3) check("Another identity once the first closed: reads logs", [m.id for m in page] == [246, 247, 248] and page.more, f"{[m.id for m in page]}, more={page.more}") - ok, detail = raises(lambda: lounge.get_messages("secret", "kitchen"), RefusedError, "Not allowed to read topic 'secret'", ErrorCode.NOT_ALLOWED) - check("A topic not in its ReadTopics: RefusedError, NOT_ALLOWED", ok, detail) - ok, detail = raises(lambda: lounge.query("SELECT 1"), RefusedError, "Not allowed to query", ErrorCode.NOT_ALLOWED) + ok, detail = raises(lambda: lounge.get_messages("secret", "kitchen"), RefusedError, "may not read 'secret'", ErrorCode.NOT_ALLOWED) + check("A topic not in its read_topics: RefusedError, NOT_ALLOWED", ok, detail) + ok, detail = raises(lambda: lounge.query("SELECT 1"), RefusedError, "may not run queries", ErrorCode.NOT_ALLOWED) check("Not allowed to query: RefusedError, NOT_ALLOWED", ok, detail) + check("list_topics(): only what it may read", lounge.list_topics().names == ["logs"]) + ok, detail = raises(lambda: lounge.get_attachment("secret", "kitchen", blob_id), RefusedError, code=ErrorCode.NOT_ALLOWED) + check("An attachment in a topic it may not read: RefusedError, NOT_ALLOWED", ok, detail) print() print("All checks passed" if fails == 0 else f"{fails} check(s) failed") diff --git a/bindings/python/make_wheel.py b/bindings/python/make_wheel.py new file mode 100644 index 0000000..a9c75b9 --- /dev/null +++ b/bindings/python/make_wheel.py @@ -0,0 +1,147 @@ +"""Builds the bakashrot wheel: bakashrot.py with the client library in it, +so `pip install` is all a Python app needs, nothing to compile. + + python make_wheel.py [license files...] + + is bakashrot.dll (Windows) or libbakashrot.so (Linux), x64 or ARM64, +from `cargo build --release`; the license files go in the wheel's +dist-info/licenses/ (release.py gives LICENSE and THIRD-PARTY.txt). Prints +the wheel's path. + +The wheel is bakashrot--py3-none-.whl, the version +being bakashrot.py's __version__ (release.py checks it's the workspace's): +win_amd64 or win_arm64, or manylinux__ with the glibc it was built +against (a Rust library only needs libc, libm and libgcc_s, which +manylinux allows). Inside, bakashrot.py is bakashrot/__init__.py with the +library next to it, where it looks first. Only the standard library, and +the same inputs give the same wheel (fixed timestamps). +""" + +import base64 +import hashlib +import os +import platform +import re +import sys +import zipfile + +HERE = os.path.dirname(os.path.abspath(__file__)) +NAME = "bakashrot" +# Zip entries' timestamp, so the wheel only changes when its content does. +FIXED_TIME = (2026, 1, 1, 0, 0, 0) + +DESCRIPTION = """\ +# bakashrot + +Python client for [BakaShrot](https://github.com/aziascreations/BakaShrot) +servers: push messages and attachments, read them back, list names, query. + +The client library is included: nothing else to install or build. 64-bit +Python 3.8+ (`Client.from_file()` needs 3.11+). The server must speak the +same protocol: use the release this package comes from. + +```python +from bakashrot import Client + +with Client.from_file("client.toml") as client: + message_id = client.push({"temperature": 21.5}, "logs") + for message in client.get_messages("logs", "kitchen", after=0).messages: + print(message.id, message.data) +``` + +See the module's docstring (`help(bakashrot)`) for the rest. +""" + + +def version(): + with open(os.path.join(HERE, "bakashrot.py"), encoding="utf-8") as file: + match = re.search(r'^__version__ = "([^"]+)"', file.read(), re.MULTILINE) + if not match: + sys.exit("No __version__ in bakashrot.py") + return match.group(1) + + +def platform_tag(library): + """The wheel's platform, from the library's kind and machine (its + header's).""" + with open(library, "rb") as file: + header = file.read(4096) + if header[:2] == b"MZ": + # The PE header's offset at 0x3C, its machine after "PE\0\0". + pe = int.from_bytes(header[0x3C:0x40], "little") + machine = {0x8664: "amd64", 0xAA64: "arm64"}.get(int.from_bytes(header[pe + 4:pe + 6], "little")) + if machine is None or header[pe:pe + 4] != b"PE\0\0": + sys.exit(f"{library}: neither an x64 nor an ARM64 DLL") + return f"win_{machine}", "Operating System :: Microsoft :: Windows" + if header[:4] == b"\x7fELF": + # e_machine, little-endian on both. + machine = {62: "x86_64", 183: "aarch64"}.get(int.from_bytes(header[18:20], "little")) + if machine is None: + sys.exit(f"{library}: neither an x86-64 nor an ARM64 shared object") + libc, glibc = platform.libc_ver() + if libc != "glibc": + sys.exit("Built against another libc than glibc: no manylinux tag") + major, minor = glibc.split(".")[:2] + return f"manylinux_{major}_{minor}_{machine}", "Operating System :: POSIX :: Linux" + sys.exit(f"{library}: neither a Windows DLL nor a Linux shared object") + + +def record_line(path, data): + digest = base64.urlsafe_b64encode(hashlib.sha256(data).digest()).rstrip(b"=").decode("ascii") + return f"{path},sha256={digest},{len(data)}" + + +def main(): + if len(sys.argv) < 3: + sys.exit(__doc__) + library, out_dir, licenses = sys.argv[1], sys.argv[2], sys.argv[3:] + tag, classifier = platform_tag(library) + tag = f"py3-none-{tag}" + dist_info = f"{NAME}-{version()}.dist-info" + + def read(path): + with open(path, "rb") as file: + return file.read() + + files = [ + (f"{NAME}/__init__.py", read(os.path.join(HERE, "bakashrot.py"))), + (f"{NAME}/{os.path.basename(library)}", read(library)), + ] + # Metadata 2.4 (PEP 639): the license files, no expression (the + # library bundles its dependencies' code, THIRD-PARTY.txt lists them). + metadata = "\n".join([ + "Metadata-Version: 2.4", + f"Name: {NAME}", + f"Version: {version()}", + "Summary: Python client for BakaShrot servers, with the client library included", + "Author: Herwin Bozet (NibblePoker)", + ] + [f"License-File: {os.path.basename(path)}" for path in licenses] + [ + "Project-URL: GitHub, https://github.com/aziascreations/BakaShrot", + f"Classifier: {classifier}", + "Classifier: Programming Language :: Python :: 3", + "Requires-Python: >=3.8", + "Description-Content-Type: text/markdown", + "", + DESCRIPTION, + ]) + files.append((f"{dist_info}/METADATA", metadata.encode("utf-8"))) + wheel = f"Wheel-Version: 1.0\nGenerator: BakaShrot make_wheel.py\nRoot-Is-Purelib: false\nTag: {tag}\n" + files.append((f"{dist_info}/WHEEL", wheel.encode("utf-8"))) + for path in licenses: + files.append((f"{dist_info}/licenses/{os.path.basename(path)}", read(path))) + record = [record_line(path, data) for path, data in files] + [f"{dist_info}/RECORD,,", ""] + files.append((f"{dist_info}/RECORD", "\n".join(record).encode("utf-8"))) + + os.makedirs(out_dir, exist_ok=True) + wheel_path = os.path.join(out_dir, f"{NAME}-{version()}-{tag}.whl") + with zipfile.ZipFile(wheel_path, "w", zipfile.ZIP_DEFLATED) as archive: + for path, data in files: + info = zipfile.ZipInfo(path, FIXED_TIME) + info.compress_type = zipfile.ZIP_DEFLATED + info.external_attr = (0o755 if path.endswith(".so") else 0o644) << 16 + archive.writestr(info, data) + print(wheel_path) + + +if __name__ == "__main__": + main() diff --git a/build.ps1 b/build.ps1 new file mode 100644 index 0000000..3505129 --- /dev/null +++ b/build.ps1 @@ -0,0 +1,19 @@ +# Builds everything (the server, the tools, the client library), release +# mode, into target\release\. +# Usage: powershell -ExecutionPolicy Bypass -File build.ps1 +$ErrorActionPreference = "Stop" + +# rustup's folder isn't always on the PATH (it isn't in every shell here). +if (-not (Get-Command cargo -ErrorAction SilentlyContinue)) { + $env:PATH = (Join-Path $env:USERPROFILE ".cargo\bin") + [IO.Path]::PathSeparator + $env:PATH +} + +Push-Location $PSScriptRoot +try { + cargo build --workspace --release --locked + if ($LASTEXITCODE -ne 0) { "FAILED: cargo build"; exit 1 } +} finally { + Pop-Location +} +"Built into $(Join-Path $PSScriptRoot "target\release")" +exit 0 diff --git a/clean.ps1 b/clean.ps1 new file mode 100644 index 0000000..e2e1dd8 --- /dev/null +++ b/clean.ps1 @@ -0,0 +1,20 @@ +# Deletes what the builds and releases made: target\ (cargo's output and +# target\dist\), and Python's __pycache__ folders. +# Usage: powershell -ExecutionPolicy Bypass -File clean.ps1 +$ErrorActionPreference = "Stop" + +# rustup's folder isn't always on the PATH (it isn't in every shell here). +if (-not (Get-Command cargo -ErrorAction SilentlyContinue)) { + $env:PATH = (Join-Path $env:USERPROFILE ".cargo\bin") + [IO.Path]::PathSeparator + $env:PATH +} + +Push-Location $PSScriptRoot +try { + cargo clean + if ($LASTEXITCODE -ne 0) { "FAILED: cargo clean"; exit 1 } + Get-ChildItem -Path bindings -Directory -Recurse -Filter __pycache__ | Remove-Item -Recurse -Force +} finally { + Pop-Location +} +"Cleaned" +exit 0 diff --git a/crates/bakashrot-capi/Cargo.toml b/crates/bakashrot-capi/Cargo.toml new file mode 100644 index 0000000..8a1dff3 --- /dev/null +++ b/crates/bakashrot-capi/Cargo.toml @@ -0,0 +1,30 @@ +[package] +name = "bakashrot-capi" +description = "BakaShrot's C DLL: the BakaShrot_* exports over bakashrot-client, one connection per process." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +authors.workspace = true +repository.workspace = true +publish.workspace = true + +# bakashrot.dll / libbakashrot.so; the rlib for the tests. +[lib] +name = "bakashrot" +crate-type = ["cdylib", "rlib"] + +[dependencies] +bakashrot-client = { path = "../bakashrot-client" } +bakashrot-proto = { path = "../bakashrot-proto" } +serde_json = "1.0.154" + +[dev-dependencies] +bakashrot-config = { path = "../bakashrot-config" } +bakashrot-pki = { path = "../bakashrot-pki" } +bakashrot-server = { path = "../bakashrot-server" } +cbindgen = { version = "0.29.4", default-features = false } +tokio = { version = "1.54.1", features = ["rt-multi-thread", "net"] } + +[lints] +workspace = true diff --git a/crates/bakashrot-capi/cbindgen.toml b/crates/bakashrot-capi/cbindgen.toml new file mode 100644 index 0000000..3ebe5ec --- /dev/null +++ b/crates/bakashrot-capi/cbindgen.toml @@ -0,0 +1,13 @@ +# bindings/c/bakashrot.h, generated from src/lib.rs by tests/header.rs +# (which rewrites it when the exports change: check it in then). +language = "C" +header = """/* + * BakaShrot's client DLL: bakashrot.dll (Windows), libbakashrot.so (Linux). + * Generated by cbindgen from crates/bakashrot-capi: don't edit. + * docs/client.md has the conventions and the whole API. + */""" +include_guard = "BAKASHROT_H" +cpp_compat = true +documentation = true +line_endings = "LF" +usize_is_size_t = true diff --git a/crates/bakashrot-capi/src/lib.rs b/crates/bakashrot-capi/src/lib.rs new file mode 100644 index 0000000..ee13404 --- /dev/null +++ b/crates/bakashrot-capi/src/lib.rs @@ -0,0 +1,928 @@ +//! BakaShrot's C DLL (`bakashrot.dll`, `libbakashrot.so`): the old +//! `BakaShrot_*` exports over [`bakashrot_client`], for C, PureBasic, +//! Python (ctypes) and anything that loads a DLL. `docs/client.md` +//! has the whole API; `bindings/c/bakashrot.h` is generated from this file. +//! +//! The conventions, the old DLL's: +//! +//! - **One connection per process:** set the certificates, connect, send +//! requests, one at a time (calls from several threads wait for each +//! other). +//! - **`A` and `W` exports:** strings in and out as UTF-8 (`char*`) or +//! UTF-16 (`uint16_t*`, `wchar_t*` on Windows), null-terminated. +//! - **Strings out** are copied into the caller's buffer of `BufferSize` +//! bytes: the getter returns the bytes needed, terminator included, and +//! copies nothing if they don't fit (a null buffer asks for the size). +//! - **Failures:** 0 (or -1 where a count or an id is returned), then +//! `BakaShrot_GetLastError()` gives the code (1-99 a server's refusal, the +//! connection still open; 100 and up the client's own) and +//! `BakaShrot_GetRefusalReason()` why, in words. After `ConnectionLost` +//! or `ProtocolError` the connection is closed: connect again. +//! - **Safety:** pointers are null or valid for what's said, strings +//! terminated, buffers writable for their size. A panic inside is caught +//! and reported as `Internal`; nothing allocated here is freed by the +//! caller, or the other way. + +#![allow(unsafe_code, non_snake_case, clippy::missing_safety_doc)] + +mod text; + +use bakashrot_client::{Client, Error, Settings}; +use bakashrot_proto::ErrorCode; +use bakashrot_proto::packets::{MessageEntry, NameKind}; +use std::ffi::{c_char, c_void}; +use std::fs::File; +use std::io::Cursor; +use std::panic::{AssertUnwindSafe, catch_unwind}; +use std::path::Path; +use std::sync::{Mutex, MutexGuard, PoisonError}; +use text::{Text, Utf8, Utf16}; + +type Result = std::result::Result; + +/// Everything the DLL holds: its one connection, its settings, the last +/// answers. +static STATE: Mutex = Mutex::new(State::new()); + +struct State { + ca: Option, + certificate: Option, + key: Option, + crl: Option, + client: Option, + /// The last call's error code, 0 if it succeeded. + last_error: u32, + /// Why it failed. + reason: String, + /// The last `GetMessages` or `GetLatestMessageOf`. + topic: String, + node: String, + messages: Vec, + selected: usize, + more: bool, + /// The last `ListTopics` / `ListNodes`, as JSON. + names: String, + /// The last `Query`'s result. + query: String, + /// The last `LoadAttachment`'s attachment. + attachment: Vec, +} + +impl State { + const fn new() -> State { + State { + ca: None, + certificate: None, + key: None, + crl: None, + client: None, + last_error: 0, + reason: String::new(), + topic: String::new(), + node: String::new(), + messages: Vec::new(), + selected: 0, + more: false, + names: String::new(), + query: String::new(), + attachment: Vec::new(), + } + } + + fn fail(&mut self, error: Error) { + self.last_error = error.code(); + self.reason = error.message().to_owned(); + let closed = [ErrorCode::ConnectionLost, ErrorCode::ProtocolError] + .iter() + .any(|code| code.code() == error.code()); + if closed { + self.client = None; + } + } + + fn client(&mut self) -> Result<&mut Client> { + self.client.as_mut().ok_or_else(|| { + Error::new( + ErrorCode::NotConnected, + "not connected: BakaShrot_Connect() first", + ) + }) + } + + /// The selected message of the last answer. + fn message(&self) -> Option<&MessageEntry> { + self.messages.get(self.selected) + } + + /// Forgets the last answer's messages. + fn clear_messages(&mut self, topic: &str, node: &str) { + self.topic = topic.to_owned(); + self.node = node.to_owned(); + self.messages.clear(); + self.selected = 0; + self.more = false; + } +} + +fn state() -> MutexGuard<'static, State> { + STATE.lock().unwrap_or_else(PoisonError::into_inner) +} + +/// Runs a call that can fail: the last error reset, then set if it fails +/// (or panics), `failed` returned then. +fn call(failed: T, run: impl FnOnce(&mut State) -> Result) -> T { + let outcome = catch_unwind(AssertUnwindSafe(|| { + let mut state = state(); + state.last_error = 0; + state.reason.clear(); + let outcome = run(&mut state); + outcome.map_err(|error| state.fail(error)) + })); + match outcome { + Ok(Ok(value)) => value, + Ok(Err(())) => failed, + Err(_) => { + state().fail(Error::new(ErrorCode::Internal, "the DLL panicked")); + failed + } + } +} + +/// Runs a getter: the last error stays as it is. +fn get(default: T, read: impl FnOnce(&State) -> T) -> T { + catch_unwind(AssertUnwindSafe(|| read(&state()))).unwrap_or(default) +} + +/// Copies a string of the state into the caller's buffer. +unsafe fn get_text(buffer: *mut T::Unit, size: isize, text: fn(&State) -> &str) -> isize { + get(0, |state| unsafe { + text::copy::(text(state), buffer, size) + }) +} + +fn invalid(why: impl Into) -> Error { + Error::new(ErrorCode::InvalidArgument, why) +} + +fn required(value: Option, what: &str) -> Result { + value.ok_or_else(|| invalid(format!("no {what} (a null pointer)"))) +} + +fn bool_result(ok: bool) -> isize { + isize::from(ok) +} + +// --- Errors ------------------------------------------------------------------ + +/// Why the last call failed: a protocol error code (1-99 a server's +/// refusal, the connection still open; 100 and up the client's own), 0 if +/// it succeeded. Getters don't change it. +#[unsafe(no_mangle)] +pub extern "C" fn BakaShrot_GetLastError() -> i32 { + get(ErrorCode::Internal.code() as i32, |state| { + state.last_error as i32 + }) +} + +/// Why the last call failed, in words: the server's reason for a refusal, +/// the client's otherwise. Empty if it succeeded. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_GetRefusalReasonA(buffer: *mut c_char, size: isize) -> isize { + unsafe { get_text::(buffer.cast(), size, |state| &state.reason) } +} + +/// The same as `BakaShrot_GetRefusalReasonA`, in UTF-16. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_GetRefusalReasonW(buffer: *mut u16, size: isize) -> isize { + unsafe { get_text::(buffer, size, |state| &state.reason) } +} + +// --- Settings ---------------------------------------------------------------- + +/// A setting's PEM: the text itself if it starts with `-----BEGIN`, a +/// file's path otherwise. `None` (null or empty) only if `optional`. +fn pem_or_file(value: Option, what: &str, optional: bool) -> Result> { + let Some(value) = value.filter(|value| !value.trim().is_empty()) else { + return match optional { + true => Ok(None), + false => Err(invalid(format!("no {what}"))), + }; + }; + if value.trim_start().starts_with("-----BEGIN") { + return Ok(Some(value)); + } + std::fs::read_to_string(&value) + .map(Some) + .map_err(|error| Error::new(ErrorCode::FileError, format!("{what} '{value}': {error}"))) +} + +/// Sets one of the certificates' settings, before connecting. +unsafe fn set( + value: *const T::Unit, + what: &str, + optional: bool, + slot: fn(&mut State) -> &mut Option, +) -> isize { + call(0, |state| { + if state.client.is_some() { + return Err(Error::new( + ErrorCode::AlreadyConnected, + "already connected: disconnect first", + )); + } + let value = unsafe { text::read::(value, what)? }; + *slot(state) = pem_or_file(value, what, optional)?; + Ok(1) + }) +} + +/// Sets the CA's certificate, which the server's must be issued by: PEM +/// text, or the path of a file holding it. Before connecting. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_SetCaCertificateA(certificate: *const c_char) -> isize { + unsafe { + set::(certificate.cast(), "CA certificate", false, |state| { + &mut state.ca + }) + } +} + +/// The same as `BakaShrot_SetCaCertificateA`, in UTF-16. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_SetCaCertificateW(certificate: *const u16) -> isize { + unsafe { set::(certificate, "CA certificate", false, |state| &mut state.ca) } +} + +/// Sets this client's certificate, which says its node and its roles: PEM +/// text, or the path of a file holding it. Before connecting. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_SetCertificateA(certificate: *const c_char) -> isize { + unsafe { + set::(certificate.cast(), "certificate", false, |state| { + &mut state.certificate + }) + } +} + +/// The same as `BakaShrot_SetCertificateA`, in UTF-16. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_SetCertificateW(certificate: *const u16) -> isize { + unsafe { + set::(certificate, "certificate", false, |state| { + &mut state.certificate + }) + } +} + +/// Sets this client's private key, its certificate's: PEM text, or the path +/// of a file holding it. Before connecting. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_SetPrivateKeyA(key: *const c_char) -> isize { + unsafe { set::(key.cast(), "private key", false, |state| &mut state.key) } +} + +/// The same as `BakaShrot_SetPrivateKeyA`, in UTF-16. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_SetPrivateKeyW(key: *const u16) -> isize { + unsafe { set::(key, "private key", false, |state| &mut state.key) } +} + +/// Sets the CA's CRL, optional: servers it revokes are refused. PEM text, +/// or the path of a file holding it; null or empty for none. Before +/// connecting. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_SetCrlA(crl: *const c_char) -> isize { + unsafe { set::(crl.cast(), "CRL", true, |state| &mut state.crl) } +} + +/// The same as `BakaShrot_SetCrlA`, in UTF-16. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_SetCrlW(crl: *const u16) -> isize { + unsafe { set::(crl, "CRL", true, |state| &mut state.crl) } +} + +// --- The connection ---------------------------------------------------------- + +unsafe fn connect(host: *const T::Unit, port: i32) -> isize { + call(0, |state| { + if state.client.is_some() { + return Err(Error::new( + ErrorCode::AlreadyConnected, + "already connected: disconnect first", + )); + } + let host = required(unsafe { text::read::(host, "host")? }, "host")?; + let port = u16::try_from(port) + .ok() + .filter(|port| *port != 0) + .ok_or_else(|| invalid(format!("port {port}: 1 to 65535")))?; + let missing = |what: &str, setter: &str| invalid(format!("no {what}: {setter}() first")); + let settings = Settings { + ca: state + .ca + .as_deref() + .ok_or_else(|| missing("CA certificate", "BakaShrot_SetCaCertificate"))?, + certificate: state + .certificate + .as_deref() + .ok_or_else(|| missing("certificate", "BakaShrot_SetCertificate"))?, + key: state + .key + .as_deref() + .ok_or_else(|| missing("private key", "BakaShrot_SetPrivateKey"))?, + crl: state.crl.as_deref(), + }; + // An IPv6 address goes in brackets before its port. + let address = match host.contains(':') && !host.starts_with('[') { + true => format!("[{host}]:{port}"), + false => format!("{host}:{port}"), + }; + let client = Client::connect(&address, &settings)?; + state.client = Some(client); + Ok(1) + }) +} + +/// Connects to the server at `host` (a name or an address) and `port`: +/// TLS with the certificates set, then the server says who this client is +/// (`BakaShrot_GetNode()`). Refused: the code says by whom (`AuthRejected` +/// the server refused the certificate, `ServerNotVerified` this client +/// refused the server's, `NotAllowed` none of its roles is the server's). +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_ConnectA(host: *const c_char, port: i32) -> isize { + unsafe { connect::(host.cast(), port) } +} + +/// The same as `BakaShrot_ConnectA`, in UTF-16. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_ConnectW(host: *const u16, port: i32) -> isize { + unsafe { connect::(host, port) } +} + +/// 1 while connected: notices when the server closed the connection +/// (forgotten then: connect again). +#[unsafe(no_mangle)] +pub extern "C" fn BakaShrot_IsConnected() -> isize { + let open = catch_unwind(AssertUnwindSafe(|| { + let mut state = state(); + let open = state.client.as_ref().is_some_and(Client::is_open); + if !open { + state.client = None; + } + open + })); + bool_result(open.unwrap_or(false)) +} + +/// Closes the connection: 0 if there was none. The settings stay. +#[unsafe(no_mangle)] +pub extern "C" fn BakaShrot_Disconnect() -> isize { + let closed = catch_unwind(AssertUnwindSafe(|| state().client.take().is_some())); + bool_result(closed.unwrap_or(false)) +} + +/// The node this client is, as the server said when connecting: its +/// certificate's name. Empty when not connected. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_GetNodeA(buffer: *mut c_char, size: isize) -> isize { + unsafe { + get_text::(buffer.cast(), size, |state| { + state.client.as_ref().map_or("", Client::node) + }) + } +} + +/// The same as `BakaShrot_GetNodeA`, in UTF-16. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_GetNodeW(buffer: *mut u16, size: isize) -> isize { + unsafe { + get_text::(buffer, size, |state| { + state.client.as_ref().map_or("", Client::node) + }) + } +} + +// --- Pushing ----------------------------------------------------------------- + +/// A push's topic and message, as arguments: a null message is an empty +/// one (PureBasic passes "" as null). +unsafe fn topic_and_data( + topic: *const T::Unit, + data: *const T::Unit, +) -> Result<(String, String)> { + let topic = required(unsafe { text::read::(topic, "topic")? }, "topic")?; + let data = unsafe { text::read::(data, "the message")? }.unwrap_or_default(); + Ok((topic, data)) +} + +unsafe fn push_to(topic: *const T::Unit, data: *const T::Unit) -> i64 { + call(-1, |state| { + let (topic, data) = unsafe { topic_and_data::(topic, data)? }; + let id = state.client()?.push(&topic, &data)?; + Ok(id as i64) + }) +} + +/// Pushes a message (JSON or not) to `topic`, as this client's node: its +/// id (1 and up), -1 on failure. A push whose answer was lost +/// (`ConnectionLost`) may have been stored all the same. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_PushMessageToA( + topic: *const c_char, + data: *const c_char, +) -> i64 { + unsafe { push_to::(topic.cast(), data.cast()) } +} + +/// The same as `BakaShrot_PushMessageToA`, in UTF-16. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_PushMessageToW(topic: *const u16, data: *const u16) -> i64 { + unsafe { push_to::(topic, data) } +} + +// --- Reading ----------------------------------------------------------------- + +/// A topic and node, as arguments. +unsafe fn topic_and_node( + topic: *const T::Unit, + node: *const T::Unit, +) -> Result<(String, String)> { + let topic = required(unsafe { text::read::(topic, "topic")? }, "topic")?; + let node = required(unsafe { text::read::(node, "node")? }, "node")?; + Ok((topic, node)) +} + +unsafe fn latest_of(topic: *const T::Unit, node: *const T::Unit) -> isize { + call(0, |state| { + let (topic, node) = unsafe { topic_and_node::(topic, node)? }; + state.clear_messages(&topic, &node); + let answer = state.client()?.get_messages(&topic, &node, None, 1)?; + if answer.messages.is_empty() { + return Err(Error::new( + ErrorCode::NotFound, + format!("no message in {topic}/{node} yet"), + )); + } + state.messages = answer.messages; + Ok(1) + }) +} + +/// Gets the latest message of `topic` and `node`, then read with the +/// `BakaShrot_GetMessage*()` getters. `NotFound` if there's none yet. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_GetLatestMessageOfA( + topic: *const c_char, + node: *const c_char, +) -> isize { + unsafe { latest_of::(topic.cast(), node.cast()) } +} + +/// The same as `BakaShrot_GetLatestMessageOfA`, in UTF-16. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_GetLatestMessageOfW( + topic: *const u16, + node: *const u16, +) -> isize { + unsafe { latest_of::(topic, node) } +} + +unsafe fn messages( + topic: *const T::Unit, + node: *const T::Unit, + after: i64, + limit: i32, +) -> i32 { + call(-1, |state| { + let (topic, node) = unsafe { topic_and_node::(topic, node)? }; + state.clear_messages(&topic, &node); + let after = + u64::try_from(after).map_err(|_| invalid(format!("after {after}: 0 or more")))?; + let limit = u32::try_from(limit).map_err(|_| invalid(format!("a limit of {limit}")))?; + let answer = state + .client()? + .get_messages(&topic, &node, Some(after), limit)?; + state.more = answer.more; + state.messages = answer.messages; + Ok(state.messages.len() as i32) + }) +} + +/// Gets the messages of `topic` and `node` after id `after` (0 for the +/// first ones), in order: `limit` at most (1-10000), fewer past about +/// 1 MB. Returns how many came (none isn't a failure), -1 on failure. The +/// first is selected; `BakaShrot_SelectMessage()` selects the others, +/// `BakaShrot_HasMoreMessages()` says whether more follow the last one. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_GetMessagesA( + topic: *const c_char, + node: *const c_char, + after: i64, + limit: i32, +) -> i32 { + unsafe { messages::(topic.cast(), node.cast(), after, limit) } +} + +/// The same as `BakaShrot_GetMessagesA`, in UTF-16. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_GetMessagesW( + topic: *const u16, + node: *const u16, + after: i64, + limit: i32, +) -> i32 { + unsafe { messages::(topic, node, after, limit) } +} + +/// How many messages the last `GetMessages` or `GetLatestMessageOf` got. +#[unsafe(no_mangle)] +pub extern "C" fn BakaShrot_GetMessageCount() -> i32 { + get(0, |state| state.messages.len() as i32) +} + +/// Selects the message at `index` (0 to the count - 1) for the getters: 0 +/// if there's none there (`InvalidArgument`), the selection unchanged. +#[unsafe(no_mangle)] +pub extern "C" fn BakaShrot_SelectMessage(index: i32) -> isize { + call(0, |state| { + let index = usize::try_from(index) + .ok() + .filter(|index| *index < state.messages.len()) + .ok_or_else(|| invalid(format!("no message at {index}")))?; + state.selected = index; + Ok(1) + }) +} + +/// 1 if more messages follow the last one the last `GetMessages` got: ask +/// again after its id. +#[unsafe(no_mangle)] +pub extern "C" fn BakaShrot_HasMoreMessages() -> isize { + get(0, |state| bool_result(state.more)) +} + +/// The selected message's id, 0 if none. +#[unsafe(no_mangle)] +pub extern "C" fn BakaShrot_GetMessageId() -> i64 { + get(0, |state| { + state.message().map_or(0, |message| message.id as i64) + }) +} + +/// When the selected message was pushed, by the server it was pushed to: +/// milliseconds since 1970-01-01 UTC, 0 if none. +#[unsafe(no_mangle)] +pub extern "C" fn BakaShrot_GetMessagePushedAt() -> i64 { + get(0, |state| { + state + .message() + .map_or(0, |message| message.pushed_at as i64) + }) +} + +/// The selected message's attachment's size, 0 without one. +#[unsafe(no_mangle)] +pub extern "C" fn BakaShrot_GetMessageAttachmentSize() -> i64 { + get(0, |state| { + state + .message() + .and_then(|message| message.attachment.as_ref()) + .map_or(0, |attachment| attachment.size as i64) + }) +} + +/// 1 if the selected message's attachment is all on this server (a +/// replicated one may still be on its way). +#[unsafe(no_mangle)] +pub extern "C" fn BakaShrot_IsMessageAttachmentReady() -> isize { + get(0, |state| { + let attachment = state + .message() + .and_then(|message| message.attachment.as_ref()); + bool_result(attachment.is_some_and(|attachment| attachment.ready)) + }) +} + +/// The selected message's data, as pushed (JSON or not). +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_GetMessageDataA(buffer: *mut c_char, size: isize) -> isize { + unsafe { + get_text::(buffer.cast(), size, |state| { + state.message().map_or("", |message| &message.data) + }) + } +} + +/// The same as `BakaShrot_GetMessageDataA`, in UTF-16. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_GetMessageDataW(buffer: *mut u16, size: isize) -> isize { + unsafe { + get_text::(buffer, size, |state| { + state.message().map_or("", |message| &message.data) + }) + } +} + +/// The topic the last `GetMessages` or `GetLatestMessageOf` asked for. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_GetMessageTopicA(buffer: *mut c_char, size: isize) -> isize { + unsafe { get_text::(buffer.cast(), size, |state| &state.topic) } +} + +/// The same as `BakaShrot_GetMessageTopicA`, in UTF-16. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_GetMessageTopicW(buffer: *mut u16, size: isize) -> isize { + unsafe { get_text::(buffer, size, |state| &state.topic) } +} + +/// The node the last `GetMessages` or `GetLatestMessageOf` asked for. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_GetMessageNodeA(buffer: *mut c_char, size: isize) -> isize { + unsafe { get_text::(buffer.cast(), size, |state| &state.node) } +} + +/// The same as `BakaShrot_GetMessageNodeA`, in UTF-16. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_GetMessageNodeW(buffer: *mut u16, size: isize) -> isize { + unsafe { get_text::(buffer, size, |state| &state.node) } +} + +// --- Names ------------------------------------------------------------------- + +fn list(kind: NameKind) -> i32 { + call(-1, |state| { + state.names.clear(); + let list = state.client()?.list_names(kind)?; + let kind = match kind { + NameKind::Topic => "topic", + NameKind::Node => "node", + }; + let count = list.names.len() as i32; + state.names = serde_json::json!({ + "kind": kind, + "truncated": list.truncated, + "names": list.names, + }) + .to_string(); + Ok(count) + }) +} + +/// Lists the topics this client may push to or read (every one if it may +/// query): how many, -1 on failure. Then `BakaShrot_GetNamesList()`. +#[unsafe(no_mangle)] +pub extern "C" fn BakaShrot_ListTopics() -> i32 { + list(NameKind::Topic) +} + +/// Lists every node with messages: how many, -1 on failure. Then +/// `BakaShrot_GetNamesList()`. +#[unsafe(no_mangle)] +pub extern "C" fn BakaShrot_ListNodes() -> i32 { + list(NameKind::Node) +} + +/// The last list, as JSON: +/// `{"kind":"topic","truncated":false,"names":["logs",...]}`, `truncated` +/// if some didn't fit. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_GetNamesListA(buffer: *mut c_char, size: isize) -> isize { + unsafe { get_text::(buffer.cast(), size, |state| &state.names) } +} + +/// The same as `BakaShrot_GetNamesListA`, in UTF-16. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_GetNamesListW(buffer: *mut u16, size: isize) -> isize { + unsafe { get_text::(buffer, size, |state| &state.names) } +} + +// --- Queries ----------------------------------------------------------------- + +unsafe fn query(sql: *const T::Unit) -> isize { + call(0, |state| { + state.query.clear(); + let sql = required(unsafe { text::read::(sql, "query")? }, "query")?; + state.query = state.client()?.query(&sql)?; + Ok(1) + }) +} + +/// Runs read-only SQL on the server (one SELECT or WITH), if this client +/// may query. Then `BakaShrot_GetQueryResult()`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_QueryA(sql: *const c_char) -> isize { + unsafe { query::(sql.cast()) } +} + +/// The same as `BakaShrot_QueryA`, in UTF-16. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_QueryW(sql: *const u16) -> isize { + unsafe { query::(sql) } +} + +/// The last query's result, as JSON: +/// `{"columns":[...],"rows":[[...],...]}`, every value a string or null. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_GetQueryResultA(buffer: *mut c_char, size: isize) -> isize { + unsafe { get_text::(buffer.cast(), size, |state| &state.query) } +} + +/// The same as `BakaShrot_GetQueryResultA`, in UTF-16. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_GetQueryResultW(buffer: *mut u16, size: isize) -> isize { + unsafe { get_text::(buffer, size, |state| &state.query) } +} + +// --- Attachments ------------------------------------------------------------- + +/// A message id, as arguments. +fn message_id(id: i64) -> Result { + u64::try_from(id).map_err(|_| invalid(format!("message {id}"))) +} + +unsafe fn push_with_file( + topic: *const T::Unit, + data: *const T::Unit, + path: *const T::Unit, +) -> i64 { + call(-1, |state| { + let (topic, data) = unsafe { topic_and_data::(topic, data)? }; + let path = required(unsafe { text::read::(path, "the file")? }, "file")?; + let mut file = File::open(&path) + .map_err(|error| Error::new(ErrorCode::FileError, format!("{path}: {error}")))?; + let id = state + .client()? + .push_with_attachment(&topic, &data, &mut file)?; + Ok(id as i64) + }) +} + +/// Pushes a message with the file at `FilePath` as its attachment (1 byte +/// to 1 TiB, the server may take less: `TooBig`): uploaded with it, the +/// message stored once all of it came. Its id, -1 on failure. The file is +/// read twice (its SHA-256 first): one changed in between is refused +/// (`DataMismatch`). +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_PushMessageWithFileA( + topic: *const c_char, + data: *const c_char, + file_path: *const c_char, +) -> i64 { + unsafe { push_with_file::(topic.cast(), data.cast(), file_path.cast()) } +} + +/// The same as `BakaShrot_PushMessageWithFileA`, in UTF-16. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_PushMessageWithFileW( + topic: *const u16, + data: *const u16, + file_path: *const u16, +) -> i64 { + unsafe { push_with_file::(topic, data, file_path) } +} + +unsafe fn push_with_data( + topic: *const T::Unit, + data: *const T::Unit, + attachment: *const c_void, + size: i64, +) -> i64 { + call(-1, |state| { + let (topic, data) = unsafe { topic_and_data::(topic, data)? }; + if attachment.is_null() { + return Err(invalid("no attachment (a null pointer)")); + } + let size = usize::try_from(size) + .ok() + .filter(|size| *size > 0) + .ok_or_else(|| invalid(format!("an attachment of {size} bytes")))?; + let bytes = unsafe { std::slice::from_raw_parts(attachment.cast::(), size) }; + let id = state + .client()? + .push_with_attachment(&topic, &data, &mut Cursor::new(bytes))?; + Ok(id as i64) + }) +} + +/// Pushes a message with the `Size` bytes at `Data` as its attachment, as +/// `BakaShrot_PushMessageWithFileA` does. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_PushMessageWithDataA( + topic: *const c_char, + data: *const c_char, + attachment: *const c_void, + size: i64, +) -> i64 { + unsafe { push_with_data::(topic.cast(), data.cast(), attachment, size) } +} + +/// The same as `BakaShrot_PushMessageWithDataA`, in UTF-16. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_PushMessageWithDataW( + topic: *const u16, + data: *const u16, + attachment: *const c_void, + size: i64, +) -> i64 { + unsafe { push_with_data::(topic, data, attachment, size) } +} + +unsafe fn save( + topic: *const T::Unit, + node: *const T::Unit, + id: i64, + path: *const T::Unit, +) -> i64 { + call(-1, |state| { + let (topic, node) = unsafe { topic_and_node::(topic, node)? }; + let path = required(unsafe { text::read::(path, "the file")? }, "file")?; + let size = + state + .client()? + .save_attachment(&topic, &node, message_id(id)?, Path::new(&path))?; + Ok(size as i64) + }) +} + +/// Saves the attachment of `Topic`, `Node`'s message `MessageId` as the +/// file at `FilePath` (replaced), read a part at a time and checked with +/// its SHA-256: its size, -1 on failure (`NotFound` without one, +/// `NotReady` if it isn't on this server yet, `AttachmentMismatch`). A +/// failed one leaves no file. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_SaveAttachmentA( + topic: *const c_char, + node: *const c_char, + message_id: i64, + file_path: *const c_char, +) -> i64 { + unsafe { save::(topic.cast(), node.cast(), message_id, file_path.cast()) } +} + +/// The same as `BakaShrot_SaveAttachmentA`, in UTF-16. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_SaveAttachmentW( + topic: *const u16, + node: *const u16, + message_id: i64, + file_path: *const u16, +) -> i64 { + unsafe { save::(topic, node, message_id, file_path) } +} + +unsafe fn load(topic: *const T::Unit, node: *const T::Unit, id: i64) -> i64 { + call(-1, |state| { + state.attachment = Vec::new(); + let (topic, node) = unsafe { topic_and_node::(topic, node)? }; + let mut attachment = Vec::new(); + let size = + state + .client()? + .get_attachment(&topic, &node, message_id(id)?, &mut attachment)?; + state.attachment = attachment; + Ok(size as i64) + }) +} + +/// Reads the attachment of `Topic`, `Node`'s message `MessageId` into +/// memory, checked with its SHA-256 (`BakaShrot_SaveAttachmentA` for big +/// ones): its size, -1 on failure. Then `BakaShrot_GetAttachmentData()`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_LoadAttachmentA( + topic: *const c_char, + node: *const c_char, + message_id: i64, +) -> i64 { + unsafe { load::(topic.cast(), node.cast(), message_id) } +} + +/// The same as `BakaShrot_LoadAttachmentA`, in UTF-16. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_LoadAttachmentW( + topic: *const u16, + node: *const u16, + message_id: i64, +) -> i64 { + unsafe { load::(topic, node, message_id) } +} + +/// Copies what the last `BakaShrot_LoadAttachment()` read into `Buffer`, if +/// `BufferSize` is enough: returns its size (0 if none), copies nothing if +/// it doesn't fit (a null `Buffer` asks for the size). +#[unsafe(no_mangle)] +pub unsafe extern "C" fn BakaShrot_GetAttachmentData(buffer: *mut c_void, buffer_size: i64) -> i64 { + get(0, |state| { + let data = &state.attachment; + if !buffer.is_null() && usize::try_from(buffer_size).is_ok_and(|size| size >= data.len()) { + unsafe { std::ptr::copy_nonoverlapping(data.as_ptr(), buffer.cast(), data.len()) }; + } + data.len() as i64 + }) +} + +/// Frees what `BakaShrot_LoadAttachment()` read: 1. +#[unsafe(no_mangle)] +pub extern "C" fn BakaShrot_FreeAttachmentData() -> isize { + let freed = catch_unwind(AssertUnwindSafe(|| state().attachment = Vec::new())); + bool_result(freed.is_ok()) +} diff --git a/crates/bakashrot-capi/src/text.rs b/crates/bakashrot-capi/src/text.rs new file mode 100644 index 0000000..5dae076 --- /dev/null +++ b/crates/bakashrot-capi/src/text.rs @@ -0,0 +1,95 @@ +//! Strings across the C boundary: arguments read as UTF-8 (`A` exports) or +//! UTF-16 (`W` exports), answers copied into the caller's buffers. + +use bakashrot_client::Error; +use bakashrot_proto::ErrorCode; + +/// An encoding of the exports' strings. +pub(crate) trait Text { + /// One code unit: `u8` or `u16`. + type Unit: Copy + Default + PartialEq; + /// Its name, for errors. + const NAME: &'static str; + fn decode(units: &[Self::Unit]) -> Option; + fn encode(text: &str) -> Vec; +} + +/// UTF-8, `char*`: the `A` exports. +pub(crate) struct Utf8; + +impl Text for Utf8 { + type Unit = u8; + const NAME: &'static str = "UTF-8"; + + fn decode(units: &[u8]) -> Option { + String::from_utf8(units.to_vec()).ok() + } + + fn encode(text: &str) -> Vec { + text.as_bytes().to_vec() + } +} + +/// UTF-16, `uint16_t*` (`wchar_t*` on Windows): the `W` exports. +pub(crate) struct Utf16; + +impl Text for Utf16 { + type Unit = u16; + const NAME: &'static str = "UTF-16"; + + fn decode(units: &[u16]) -> Option { + String::from_utf16(units).ok() + } + + fn encode(text: &str) -> Vec { + text.encode_utf16().collect() + } +} + +/// A null-terminated string argument; `None` for a null pointer (what +/// PureBasic passes for an empty string). +/// +/// # Safety +/// +/// `pointer` is null, or points to a string ending with a zero unit. +pub(crate) unsafe fn read( + pointer: *const T::Unit, + what: &str, +) -> Result, Error> { + if pointer.is_null() { + return Ok(None); + } + let mut units = Vec::new(); + loop { + // Unaligned: callers' buffers may be byte arrays. + let unit = unsafe { pointer.add(units.len()).read_unaligned() }; + if unit == T::Unit::default() { + break; + } + units.push(unit); + } + T::decode(&units).map(Some).ok_or_else(|| { + Error::new( + ErrorCode::InvalidArgument, + format!("{what}: not valid {}", T::NAME), + ) + }) +} + +/// Copies `text`, terminated, into `buffer` of `size` bytes if it fits +/// (nothing otherwise, or with a null `buffer`): the bytes it needs. +/// +/// # Safety +/// +/// `buffer` is null, or writable for `size` bytes. +pub(crate) unsafe fn copy(text: &str, buffer: *mut T::Unit, size: isize) -> isize { + let mut units = T::encode(text); + units.push(T::Unit::default()); + let needed = std::mem::size_of_val(units.as_slice()); + if !buffer.is_null() && size >= needed as isize { + unsafe { + std::ptr::copy_nonoverlapping(units.as_ptr().cast::(), buffer.cast::(), needed); + } + } + needed as isize +} diff --git a/crates/bakashrot-capi/tests/common/mod.rs b/crates/bakashrot-capi/tests/common/mod.rs new file mode 100644 index 0000000..6ba2f44 --- /dev/null +++ b/crates/bakashrot-capi/tests/common/mod.rs @@ -0,0 +1,95 @@ +//! A server on a free port, in a folder of its own with its CA and the +//! clients' certificates. + +use bakashrot_config::Config; +use bakashrot_pki::{Ca, Identity, Usage}; +use bakashrot_server::Server; +use std::path::PathBuf; + +const CONFIG: &str = r#" +[server] +listen = "127.0.0.1:0" +ca = "ca.crt" +certificate = "server.crt" +key = "server.key" +topics = ["logs", "secret"] + +[roles.home] +push_topics = ["logs", "secret"] +read_topics = ["*"] +query = true + +[roles.lounge] +read_topics = ["logs"] +"#; + +pub struct Running { + pub folder: PathBuf, + pub port: u16, + ca: Ca, + // Kept for the server's tasks to run. + _runtime: tokio::runtime::Runtime, +} + +impl Running { + pub fn start(name: &str) -> Running { + let folder = PathBuf::from(env!("CARGO_TARGET_TMPDIR")) + .join(format!("capi-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&folder); + std::fs::create_dir_all(&folder).unwrap(); + let issued = Ca::create("Test CA", 10).unwrap(); + let ca = Ca::load(&issued.certificate, &issued.key).unwrap(); + let server = ca + .issue( + &Identity::new("server-1", &["peer"]).unwrap(), + Usage::Server, + 10, + ) + .unwrap(); + std::fs::write(folder.join("ca.crt"), &issued.certificate).unwrap(); + std::fs::write(folder.join("server.crt"), &server.certificate).unwrap(); + std::fs::write(folder.join("server.key"), &server.key).unwrap(); + // `SYNC=normal` to measure without a disk flush per push. + let sync = std::env::var("SYNC").unwrap_or_else(|_| "full".into()); + let config = CONFIG.replace( + "[roles.home]", + &format!( + "synchronous = \"{sync}\" + +[roles.home]" + ), + ); + std::fs::write(folder.join("server.toml"), config).unwrap(); + let config = Config::load(&folder.join("server.toml")).unwrap(); + let server = Server::start(config).unwrap(); + + let runtime = tokio::runtime::Runtime::new().unwrap(); + let listener = runtime + .block_on(tokio::net::TcpListener::bind("127.0.0.1:0")) + .unwrap(); + let port = listener.local_addr().unwrap().port(); + runtime.spawn(async move { server.serve(listener).await }); + Running { + folder, + port, + ca, + _runtime: runtime, + } + } + + /// Issues a client's certificate, written as `.crt` and + /// `.key`, with a `.toml` to connect with. + pub fn issue(&self, name: &str, roles: &[&str]) { + let issued = self + .ca + .issue(&Identity::new(name, roles).unwrap(), Usage::Client, 10) + .unwrap(); + std::fs::write(self.folder.join(format!("{name}.crt")), &issued.certificate).unwrap(); + std::fs::write(self.folder.join(format!("{name}.key")), &issued.key).unwrap(); + let toml = format!( + "server = \"127.0.0.1:{}\"\nca = \"ca.crt\"\ncertificate = \"{name}.crt\"\nkey = \"{name}.key\"\n", + self.port + ); + std::fs::write(self.folder.join(format!("{name}.toml")), toml).unwrap(); + } +} diff --git a/crates/bakashrot-capi/tests/exports.rs b/crates/bakashrot-capi/tests/exports.rs new file mode 100644 index 0000000..1bdfd82 --- /dev/null +++ b/crates/bakashrot-capi/tests/exports.rs @@ -0,0 +1,341 @@ +//! The exports called as C would, against a server: the `W` ones (what +//! PureBasic uses; Python's check covers the `A` ones), the buffers, the +//! errors. One test: the DLL holds one connection per process. + +#![allow(unsafe_code)] + +mod common; + +use bakashrot::*; +use bakashrot_proto::ErrorCode; +use std::ffi::{CString, c_char}; + +fn w(text: &str) -> Vec { + text.encode_utf16().chain([0]).collect() +} + +fn a(text: &str) -> CString { + CString::new(text).unwrap() +} + +/// A `W` getter's string: asks for the size, then copies. +fn get_w(getter: unsafe extern "C" fn(*mut u16, isize) -> isize) -> String { + let size = unsafe { getter(std::ptr::null_mut(), 0) }; + let mut buffer = vec![0u16; size as usize / 2]; + unsafe { getter(buffer.as_mut_ptr(), size) }; + String::from_utf16(&buffer[..buffer.len() - 1]).unwrap() +} + +fn get_a(getter: unsafe extern "C" fn(*mut c_char, isize) -> isize) -> String { + let size = unsafe { getter(std::ptr::null_mut(), 0) }; + let mut buffer = vec![0u8; size as usize]; + unsafe { getter(buffer.as_mut_ptr().cast(), size) }; + String::from_utf8(buffer[..buffer.len() - 1].to_vec()).unwrap() +} + +/// The last error's code and reason. +fn error() -> (u32, String) { + ( + BakaShrot_GetLastError() as u32, + get_w(BakaShrot_GetRefusalReasonW), + ) +} + +fn code(code: ErrorCode) -> u32 { + code.code() +} + +#[test] +fn exports() { + let running = common::Running::start("exports"); + running.issue("kitchen", &["home"]); + running.issue("lounge", &["lounge"]); + let file = |name: &str| running.folder.join(name).display().to_string(); + let pem = |name: &str| std::fs::read_to_string(running.folder.join(name)).unwrap(); + let localhost = w("127.0.0.1"); + let port = i32::from(running.port); + + unsafe { + // Nothing set, not connected. + assert_eq!( + BakaShrot_PushMessageToW(w("logs").as_ptr(), w("{}").as_ptr()), + -1 + ); + assert_eq!(error().0, code(ErrorCode::NotConnected)); + assert_eq!(BakaShrot_ConnectW(localhost.as_ptr(), port), 0); + let (failed, why) = error(); + assert_eq!(failed, code(ErrorCode::InvalidArgument)); + assert!(why.contains("BakaShrot_SetCaCertificate"), "{why}"); + + // Files or PEM text; a missing file, an empty setting. + assert_eq!( + BakaShrot_SetCaCertificateW(w(&file("missing.crt")).as_ptr()), + 0 + ); + assert_eq!(error().0, code(ErrorCode::FileError)); + assert_eq!(BakaShrot_SetCertificateW(std::ptr::null()), 0); + assert_eq!(error().0, code(ErrorCode::InvalidArgument)); + assert_eq!(BakaShrot_SetCaCertificateW(w(&file("ca.crt")).as_ptr()), 1); + assert_eq!(BakaShrot_GetLastError(), 0); + assert_eq!( + BakaShrot_SetCertificateW(w(&pem("kitchen.crt")).as_ptr()), + 1 + ); + assert_eq!( + BakaShrot_SetPrivateKeyA(a(&file("kitchen.key")).as_ptr()), + 1 + ); + assert_eq!(BakaShrot_SetCrlW(std::ptr::null()), 1); + assert_eq!(BakaShrot_ConnectW(localhost.as_ptr(), 0), 0); + assert_eq!(error().0, code(ErrorCode::InvalidArgument)); + + assert_eq!( + BakaShrot_ConnectW(localhost.as_ptr(), port), + 1, + "{:?}", + error() + ); + assert_eq!(BakaShrot_IsConnected(), 1); + assert_eq!(get_w(BakaShrot_GetNodeW), "kitchen"); + assert_eq!(BakaShrot_ConnectW(localhost.as_ptr(), port), 0); + assert_eq!(error().0, code(ErrorCode::AlreadyConnected)); + assert_eq!(BakaShrot_SetCaCertificateW(w(&file("ca.crt")).as_ptr()), 0); + assert_eq!(error().0, code(ErrorCode::AlreadyConnected)); + + // Pushes: UTF-16, a null message is an empty one. + assert_eq!( + BakaShrot_PushMessageToW(w("logs").as_ptr(), w(r#"{"i":1}"#).as_ptr()), + 1 + ); + assert_eq!( + BakaShrot_PushMessageToW(w("logs").as_ptr(), w("héllo 🌍").as_ptr()), + 2 + ); + assert_eq!( + BakaShrot_PushMessageToW(w("logs").as_ptr(), std::ptr::null()), + 3 + ); + assert_eq!( + BakaShrot_PushMessageToW(std::ptr::null(), w("{}").as_ptr()), + -1 + ); + assert_eq!(error().0, code(ErrorCode::InvalidArgument)); + assert_eq!( + BakaShrot_PushMessageToW(w("nothing").as_ptr(), w("{}").as_ptr()), + -1 + ); + let (failed, why) = error(); + assert_eq!(failed, code(ErrorCode::UnknownName)); + assert!(why.contains("unknown topic"), "{why}"); + + // The latest; none yet in another topic. + assert_eq!( + BakaShrot_GetLatestMessageOfW(w("logs").as_ptr(), w("kitchen").as_ptr()), + 1 + ); + assert_eq!( + (BakaShrot_GetMessageCount(), BakaShrot_GetMessageId()), + (1, 3) + ); + assert_eq!(get_w(BakaShrot_GetMessageDataW), ""); + assert!(BakaShrot_GetMessagePushedAt() > 1_700_000_000_000); + assert_eq!(BakaShrot_GetMessageAttachmentSize(), 0); + assert_eq!(BakaShrot_IsMessageAttachmentReady(), 0); + assert_eq!( + BakaShrot_GetLatestMessageOfW(w("secret").as_ptr(), w("kitchen").as_ptr()), + 0 + ); + assert_eq!(error().0, code(ErrorCode::NotFound)); + assert_eq!(BakaShrot_GetMessageCount(), 0); + + // A run of messages, selected one by one. + assert_eq!( + BakaShrot_GetMessagesW(w("logs").as_ptr(), w("kitchen").as_ptr(), 0, 2), + 2 + ); + assert_eq!(BakaShrot_HasMoreMessages(), 1); + assert_eq!(get_w(BakaShrot_GetMessageTopicW), "logs"); + assert_eq!(get_w(BakaShrot_GetMessageNodeW), "kitchen"); + assert_eq!(BakaShrot_GetMessageId(), 1); + assert_eq!(BakaShrot_SelectMessage(1), 1); + assert_eq!(get_w(BakaShrot_GetMessageDataW), "héllo 🌍"); + assert_eq!(get_a(BakaShrot_GetMessageDataA), "héllo 🌍"); + assert_eq!(BakaShrot_SelectMessage(2), 0); + assert_eq!(error().0, code(ErrorCode::InvalidArgument)); + assert_eq!(BakaShrot_GetMessageId(), 2, "the selection stays"); + assert_eq!( + BakaShrot_GetMessagesW(w("logs").as_ptr(), w("kitchen").as_ptr(), 3, 10), + 0 + ); + assert_eq!(BakaShrot_HasMoreMessages(), 0); + assert_eq!(BakaShrot_GetMessageId(), 0); + for (after, limit) in [(-1, 10), (0, 0), (0, 10_001)] { + assert_eq!( + BakaShrot_GetMessagesW(w("logs").as_ptr(), w("kitchen").as_ptr(), after, limit), + -1 + ); + assert_eq!(error().0, code(ErrorCode::InvalidArgument)); + } + assert_eq!( + BakaShrot_GetMessagesW(w("logs").as_ptr(), w("nobody").as_ptr(), 0, 10), + -1 + ); + assert_eq!(error().0, code(ErrorCode::UnknownName)); + assert_eq!(BakaShrot_IsConnected(), 1, "a refusal keeps the connection"); + + // The buffers: the size needed, nothing copied if it doesn't fit. + BakaShrot_GetMessagesW(w("logs").as_ptr(), w("kitchen").as_ptr(), 0, 1); + assert_eq!(BakaShrot_GetMessageDataW(std::ptr::null_mut(), 0), 16); + assert_eq!(BakaShrot_GetMessageDataA(std::ptr::null_mut(), 0), 8); + let mut small = [7u16; 7]; + assert_eq!(BakaShrot_GetMessageDataW(small.as_mut_ptr(), 14), 16); + assert_eq!(small, [7; 7]); + // Unaligned: a byte buffer. + let mut bytes = [0u8; 17]; + assert_eq!( + BakaShrot_GetMessageDataW(bytes[1..].as_mut_ptr().cast(), 16), + 16 + ); + assert_eq!(bytes[1..3], [b'{', 0]); + + // Names, queries. + assert_eq!(BakaShrot_ListTopics(), 2); + assert_eq!( + get_w(BakaShrot_GetNamesListW), + r#"{"kind":"topic","names":["logs","secret"],"truncated":false}"# + ); + assert_eq!(BakaShrot_ListNodes(), 1); + assert_eq!( + BakaShrot_QueryW(w("SELECT COUNT(*) AS n FROM data").as_ptr()), + 1 + ); + assert_eq!( + get_w(BakaShrot_GetQueryResultW), + r#"{"columns":["n"],"rows":[["3"]]}"# + ); + assert_eq!(BakaShrot_QueryW(w("SELECT nope").as_ptr()), 0); + assert_eq!(error().0, code(ErrorCode::QueryFailed)); + assert_eq!(get_w(BakaShrot_GetQueryResultW), ""); + + // Attachments: from a file or memory, saved or loaded back. + let (logs, kitchen) = (w("logs"), w("kitchen")); + let photo: Vec = (0..1_500_000u32).map(|i| (i % 251) as u8).collect(); + std::fs::write(running.folder.join("photo.bin"), &photo).unwrap(); + let photo_file = w(&file("photo.bin")); + let pushed = BakaShrot_PushMessageWithFileW( + logs.as_ptr(), + w(r#"{"photo":1}"#).as_ptr(), + photo_file.as_ptr(), + ); + assert_eq!(pushed, 4, "{:?}", error()); + let tiny = b"tiny"; + let pushed = BakaShrot_PushMessageWithDataW( + logs.as_ptr(), + std::ptr::null(), + tiny.as_ptr().cast(), + 4, + ); + assert_eq!(pushed, 5, "{:?}", error()); + assert_eq!( + BakaShrot_GetLatestMessageOfW(logs.as_ptr(), kitchen.as_ptr()), + 1 + ); + assert_eq!( + ( + BakaShrot_GetMessageId(), + BakaShrot_GetMessageAttachmentSize(), + BakaShrot_IsMessageAttachmentReady() + ), + (5, 4, 1) + ); + let saved = w(&file("saved.bin")); + assert_eq!( + BakaShrot_SaveAttachmentW(logs.as_ptr(), kitchen.as_ptr(), 4, saved.as_ptr()), + 1_500_000 + ); + assert_eq!( + std::fs::read(running.folder.join("saved.bin")).unwrap(), + photo + ); + assert_eq!( + BakaShrot_LoadAttachmentW(logs.as_ptr(), kitchen.as_ptr(), 5), + 4 + ); + assert_eq!(BakaShrot_GetAttachmentData(std::ptr::null_mut(), 0), 4); + let mut small = [9u8; 3]; + assert_eq!(BakaShrot_GetAttachmentData(small.as_mut_ptr().cast(), 3), 4); + assert_eq!(small, [9; 3], "nothing copied if it doesn't fit"); + let mut data = [0u8; 4]; + assert_eq!(BakaShrot_GetAttachmentData(data.as_mut_ptr().cast(), 4), 4); + assert_eq!(&data, tiny); + assert_eq!(BakaShrot_FreeAttachmentData(), 1); + assert_eq!(BakaShrot_GetAttachmentData(std::ptr::null_mut(), 0), 0); + assert_eq!( + BakaShrot_LoadAttachmentA(a("logs").as_ptr(), a("kitchen").as_ptr(), 4), + 1_500_000 + ); + BakaShrot_FreeAttachmentData(); + + // Refused, or the client's own failures: -1, no file. + let none = w(&file("none.bin")); + assert_eq!( + BakaShrot_SaveAttachmentW(logs.as_ptr(), kitchen.as_ptr(), 1, none.as_ptr()), + -1 + ); + assert_eq!(error().0, code(ErrorCode::NotFound)); + assert!(!running.folder.join("none.bin").exists()); + assert_eq!( + BakaShrot_SaveAttachmentW(logs.as_ptr(), kitchen.as_ptr(), -1, none.as_ptr()), + -1 + ); + assert_eq!(error().0, code(ErrorCode::InvalidArgument)); + let missing = w(&file("missing.bin")); + assert_eq!( + BakaShrot_PushMessageWithFileW(logs.as_ptr(), std::ptr::null(), missing.as_ptr()), + -1 + ); + assert_eq!(error().0, code(ErrorCode::FileError)); + for (pointer, size) in [(std::ptr::null(), 4), (tiny.as_ptr(), 0)] { + let pushed = BakaShrot_PushMessageWithDataW( + logs.as_ptr(), + std::ptr::null(), + pointer.cast(), + size, + ); + assert_eq!(pushed, -1); + assert_eq!(error().0, code(ErrorCode::InvalidArgument)); + } + assert_eq!(BakaShrot_IsConnected(), 1); + + // Closed: requests refused, the settings kept. + assert_eq!(BakaShrot_Disconnect(), 1); + assert_eq!(BakaShrot_Disconnect(), 0); + assert_eq!(BakaShrot_IsConnected(), 0); + assert_eq!(get_w(BakaShrot_GetNodeW), ""); + assert_eq!(BakaShrot_QueryW(w("SELECT 1").as_ptr()), 0); + assert_eq!(error().0, code(ErrorCode::NotConnected)); + + // Another identity, by the A exports: not allowed to query. + assert_eq!( + BakaShrot_SetCertificateA(a(&file("lounge.crt")).as_ptr()), + 1 + ); + assert_eq!(BakaShrot_SetPrivateKeyA(a(&pem("lounge.key")).as_ptr()), 1); + assert_eq!( + BakaShrot_ConnectA(a("localhost").as_ptr(), port), + 1, + "{:?}", + error() + ); + assert_eq!(get_a(BakaShrot_GetNodeA), "lounge"); + assert_eq!(BakaShrot_QueryA(a("SELECT 1").as_ptr()), 0); + let (failed, why) = error(); + assert_eq!(failed, code(ErrorCode::NotAllowed)); + assert_eq!(get_a(BakaShrot_GetRefusalReasonA), why); + BakaShrot_Disconnect(); + + // Nothing listening there. + assert_eq!(BakaShrot_ConnectA(a("127.0.0.1").as_ptr(), 1), 0); + assert_eq!(error().0, code(ErrorCode::ConnectFailed)); + } +} diff --git a/crates/bakashrot-capi/tests/header.rs b/crates/bakashrot-capi/tests/header.rs new file mode 100644 index 0000000..420c40d --- /dev/null +++ b/crates/bakashrot-capi/tests/header.rs @@ -0,0 +1,20 @@ +//! `bindings/c/bakashrot.h` matches the exports: rewritten when it doesn't +//! (the test fails then, check the new one in). + +use std::path::Path; + +#[test] +fn the_header_is_current() { + let crate_dir = env!("CARGO_MANIFEST_DIR"); + let path = Path::new(crate_dir).join("../../bindings/c/bakashrot.h"); + let mut generated = Vec::new(); + cbindgen::generate(crate_dir) + .expect("cbindgen reads the crate") + .write(&mut generated); + let current = std::fs::read(&path).unwrap_or_default(); + if current != generated { + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, &generated).unwrap(); + panic!("{} was out of date: rewritten, check it in", path.display()); + } +} diff --git a/crates/bakashrot-capi/tests/python.rs b/crates/bakashrot-capi/tests/python.rs new file mode 100644 index 0000000..13009af --- /dev/null +++ b/crates/bakashrot-capi/tests/python.rs @@ -0,0 +1,66 @@ +//! `bindings/python/check_bakashrot.py` on the DLL against a server: the +//! Python module and the DLL as an app loads it. Skipped (said so) without +//! a Python 3.11+ on the PATH. + +mod common; + +use std::path::{Path, PathBuf}; +use std::process::Command; + +#[test] +fn check_bakashrot_py() { + let Some(python) = ["python3", "python"].into_iter().find(|python| { + Command::new(python) + .args(["-c", "import sys, tomllib; sys.exit(0)"]) + .output() + .is_ok_and(|output| output.status.success()) + }) else { + eprintln!("SKIPPED: no Python 3.11+ on the PATH"); + return; + }; + + let dll = built_dll(); + + let running = common::Running::start("python"); + running.issue("kitchen", &["home"]); + running.issue("lounge", &["lounge"]); + running.issue("guest", &["guest"]); + + let bindings = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../bindings/python"); + let output = Command::new(python) + .arg(bindings.join("check_bakashrot.py")) + .arg(&dll) + .arg(&running.folder) + .env("PYTHONPATH", &bindings) + .env("PYTHONIOENCODING", "utf-8") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + println!("{stdout}"); + eprintln!("{}", String::from_utf8_lossy(&output.stderr)); + assert!(output.status.success(), "check_bakashrot.py failed"); + assert!(stdout.contains("All checks passed")); +} + +/// The DLL cargo built with this test: next to it (cargo's older layout), +/// or the newest in this crate's build folders (`build/bakashrot-capi/*/out/`). +fn built_dll() -> PathBuf { + let name = format!( + "{}bakashrot{}", + std::env::consts::DLL_PREFIX, + std::env::consts::DLL_SUFFIX + ); + let exe = std::env::current_exe().unwrap(); + let here = exe.parent().unwrap(); + if here.join(&name).exists() { + return here.join(name); + } + let builds = here.ancestors().nth(2).unwrap(); + std::fs::read_dir(builds) + .unwrap() + .filter_map(|entry| Some(entry.ok()?.path().join("out").join(&name))) + .filter_map(|dll| Some((dll.metadata().ok()?.modified().ok()?, dll))) + .max() + .map(|(_, dll)| dll) + .unwrap_or_else(|| panic!("no {name} built near {}", here.display())) +} diff --git a/crates/bakashrot-client/Cargo.toml b/crates/bakashrot-client/Cargo.toml new file mode 100644 index 0000000..3f567bf --- /dev/null +++ b/crates/bakashrot-client/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "bakashrot-client" +description = "BakaShrot's client library: blocking, TLS with the CA's certificates, the requests of protocol 7." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +authors.workspace = true +repository.workspace = true +publish.workspace = true + +[dependencies] +# The attachments' SHA-256: the TLS one's (aws-lc), no other crate. +aws-lc-rs = "1.19.0" +bakashrot-proto = { path = "../bakashrot-proto" } +bakashrot-pki = { path = "../bakashrot-pki" } +# The same as bakashrot-pki's: TLS 1.3 through aws-lc. +rustls = { version = "0.23.46", default-features = false, features = ["aws_lc_rs", "std"] } + +[lints] +workspace = true diff --git a/crates/bakashrot-client/src/lib.rs b/crates/bakashrot-client/src/lib.rs new file mode 100644 index 0000000..53cbe25 --- /dev/null +++ b/crates/bakashrot-client/src/lib.rs @@ -0,0 +1,543 @@ +//! BakaShrot's client: one connection to a server, blocking, one request +//! at a time (no async runtime: the C DLL wraps this as it is). +//! +//! ```no_run +//! # fn main() -> Result<(), bakashrot_client::Error> { +//! use bakashrot_client::{Client, Settings}; +//! let (ca, certificate, key) = (String::new(), String::new(), String::new()); // PEM +//! let settings = Settings { ca: &ca, certificate: &certificate, key: &key, crl: None }; +//! let mut client = Client::connect("10.0.0.2:7000", &settings)?; +//! let id = client.push("logs", r#"{"temp": 21}"#)?; +//! let node = client.node().to_owned(); +//! let latest = client.get_messages("logs", &node, None, 1)?; +//! # Ok(()) } +//! ``` +//! +//! The connection: TLS 1.3 with the CA's certificates (`bakashrot-pki`), +//! ALPN `bakashrot`, both ends' protocol versions, then the server's +//! `Welcome` (`docs/protocol.md`). Errors carry the protocol's codes +//! (`bakashrot_proto::ErrorCode`): a server's refusal keeps its own. + +use aws_lc_rs::digest; +use bakashrot_pki::{Revocations, tls}; +use bakashrot_proto::limits::{ + ALPN, ATTACHMENT_PART_SIZE, MAX_ATTACHMENT_SIZE, MAX_MESSAGE_ID, MAX_MESSAGE_SIZE, + MAX_MESSAGES_PER_PACKET, MAX_PACKET_SIZE, +}; +use bakashrot_proto::names::is_valid_name; +use bakashrot_proto::packets::{ + Attachment, AttachmentPart, GetAttachment, GetMessages, ListNames, Messages, NameKind, + NamesList, PushMessage, Query, +}; +use bakashrot_proto::{ErrorCode, Packet, frame}; +use rustls::{ClientConnection, StreamOwned}; +use std::fmt; +use std::fs::{self, File}; +use std::io::{self, Read, Seek, Write}; +use std::net::{Shutdown, TcpStream, ToSocketAddrs}; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +/// How long connecting may take: TCP, TLS, the versions, the welcome. +pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(10); + +/// How long an answer may take. +pub const ANSWER_TIMEOUT: Duration = Duration::from_secs(30); + +/// What a client connects with, PEM text as files hold it. +#[derive(Debug, Clone, Copy)] +pub struct Settings<'a> { + /// The CA's certificate: servers are taken if it issued theirs. + pub ca: &'a str, + /// This client's certificate: its node, its roles. + pub certificate: &'a str, + /// Its key. + pub key: &'a str, + /// The CA's CRL, if given: servers it revokes are refused. + pub crl: Option<&'a str>, +} + +/// What went wrong: a protocol error code (a server's refusal, 1-99, or +/// the client's own, 100 and up) and why. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Error { + code: u32, + message: String, +} + +impl Error { + /// An error of `code`, saying why. + pub fn new(code: ErrorCode, message: impl Into) -> Error { + Error { + code: code.code(), + message: message.into(), + } + } + + /// Its code (`bakashrot_proto::error`). + pub fn code(&self) -> u32 { + self.code + } + + /// Why, in words. + pub fn message(&self) -> &str { + &self.message + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let name = bakashrot_proto::error::code_name(self.code); + write!(f, "{} ({}): {}", name, self.code, self.message) + } +} + +impl std::error::Error for Error {} + +/// A result of this crate. +pub type Result = std::result::Result; + +/// A connection to a server. +pub struct Client { + stream: StreamOwned, + server: String, + node: String, +} + +impl fmt::Debug for Client { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Client") + .field("server", &self.server) + .field("node", &self.node) + .finish_non_exhaustive() + } +} + +impl Client { + /// Connects to the server at `address` (`host:port`): any of the CA's + /// servers, whatever its address. + pub fn connect(address: &str, settings: &Settings<'_>) -> Result { + let invalid = |what: &str| { + let what = what.to_owned(); + move |error: bakashrot_pki::Error| { + Error::new(ErrorCode::InvalidArgument, format!("{what}: {error}")) + } + }; + let revocations = match settings.crl { + Some(crl) => Revocations::load(crl, settings.ca).map_err(invalid("the CRL"))?, + None => Revocations::none(), + }; + let config = tls::client_config( + settings.ca, + settings.certificate, + settings.key, + revocations.shared(), + ) + .map_err(invalid("the certificates"))?; + + let tcp = connect_tcp(address)?; + let connection = ClientConnection::new(config, tls::server_name()) + .map_err(|error| Error::new(ErrorCode::InvalidArgument, error.to_string()))?; + let mut stream = StreamOwned::new(connection, tcp); + while stream.conn.is_handshaking() { + stream.conn.complete_io(&mut stream.sock).map_err(lost)?; + } + if stream.conn.alpn_protocol() != Some(ALPN) { + return Err(Error::new( + ErrorCode::AuthRejected, + "the server doesn't speak BakaShrot", + )); + } + + frame::write_version(&mut stream).map_err(lost)?; + stream.flush().map_err(lost)?; + let theirs = frame::read_version(&mut stream).map_err(lost)?; + if let Err(version) = frame::check_version(theirs) { + return Err(Error::new( + ErrorCode::VersionMismatch, + format!( + "the server speaks protocol {version}, this client {}", + bakashrot_proto::limits::PROTOCOL_VERSION + ), + )); + } + + let mut client = Client { + stream, + server: String::new(), + node: String::new(), + }; + match client.answer()? { + Packet::Welcome(welcome) => { + client.server = welcome.server; + client.node = welcome.node; + } + other => return Err(unexpected(&other)), + } + let tcp = &client.stream.sock; + tcp.set_read_timeout(Some(ANSWER_TIMEOUT)).map_err(lost)?; + tcp.set_write_timeout(Some(ANSWER_TIMEOUT)).map_err(lost)?; + Ok(client) + } + + /// The server's name. + pub fn server(&self) -> &str { + &self.server + } + + /// The node this client writes as: its certificate's name. + pub fn node(&self) -> &str { + &self.node + } + + /// Whether the connection still looks open: the server hasn't closed + /// it (after its idle timeout, say). Only a request tells for sure. + pub fn is_open(&self) -> bool { + let tcp = &self.stream.sock; + if tcp.set_nonblocking(true).is_err() { + return false; + } + let open = match tcp.peek(&mut [0]) { + Ok(read) => read > 0, + Err(error) => error.kind() == io::ErrorKind::WouldBlock, + }; + open && tcp.set_nonblocking(false).is_ok() + } + + /// Pushes a message to `topic`, as this client's node: its id. + pub fn push(&mut self, topic: &str, data: &str) -> Result { + check_name(topic, "topic")?; + check_size(data, "a message")?; + let push = PushMessage { + topic: topic.to_owned(), + data: data.to_owned(), + attachment: None, + }; + match self.request(push.into())? { + Packet::MessagePushed(pushed) => Ok(pushed.message_id), + other => Err(unexpected(&other)), + } + } + + /// Pushes a message with an attachment read from `source` (a `File`, a + /// `Cursor` over bytes), from its start to its end: twice, for its + /// SHA-256, then to send it (a source changed in between is refused, + /// `DataMismatch`). 1 byte to `MAX_ATTACHMENT_SIZE` (servers may take + /// less, `TooBig`). A source failing while it's sent closes the + /// connection (`FileError`). + pub fn push_with_attachment( + &mut self, + topic: &str, + data: &str, + source: &mut (impl Read + Seek), + ) -> Result { + check_name(topic, "topic")?; + check_size(data, "a message")?; + source.rewind().map_err(file_error)?; + let mut sha256 = digest::Context::new(&digest::SHA256); + let mut buffer = vec![0; ATTACHMENT_PART_SIZE as usize]; + let mut size = 0; + loop { + let read = source.read(&mut buffer).map_err(file_error)?; + if read == 0 { + break; + } + sha256.update(&buffer[..read]); + size += read as u64; + } + if !(1..=MAX_ATTACHMENT_SIZE).contains(&size) { + return Err(Error::new( + ErrorCode::InvalidArgument, + format!("an attachment of {size} bytes: 1 to {MAX_ATTACHMENT_SIZE}"), + )); + } + source.rewind().map_err(file_error)?; + let mut digest = [0; 32]; + digest.copy_from_slice(sha256.finish().as_ref()); + let attachment = Attachment { + size, + sha256: digest, + }; + let push = PushMessage { + topic: topic.to_owned(), + data: data.to_owned(), + attachment: Some(attachment.clone()), + }; + match self.request(push.into())? { + Packet::Continue(_) => {} + other => return Err(unexpected(&other)), + } + for part in 0..attachment.part_count() { + let part = &mut buffer[..attachment.part_len(part) as usize]; + if let Err(error) = source.read_exact(part) { + self.close(); + return Err(file_error(error)); + } + let packet = Packet::from(AttachmentPart { + data: part.to_vec(), + }); + frame::write(&mut self.stream, &packet.encode()).map_err(lost)?; + } + self.stream.flush().map_err(lost)?; + match self.answer()? { + Packet::MessagePushed(pushed) => Ok(pushed.message_id), + other => Err(unexpected(&other)), + } + } + + /// Writes a message's attachment into `out`, a part at a time, checked + /// with its SHA-256 once all came (`AttachmentMismatch`): its size. + /// What `out` has when it fails is to be thrown away. + pub fn get_attachment( + &mut self, + topic: &str, + node: &str, + message_id: u64, + out: &mut impl Write, + ) -> Result { + check_name(topic, "topic")?; + check_name(node, "node")?; + if !(1..=MAX_MESSAGE_ID).contains(&message_id) { + return Err(Error::new( + ErrorCode::InvalidArgument, + format!("message {message_id}: 1 to {MAX_MESSAGE_ID}"), + )); + } + let get = GetAttachment { + topic: topic.to_owned(), + node: node.to_owned(), + message_id, + from_part: 0, + }; + let attachment = match self.request(get.into())? { + Packet::Attachment(attachment) => attachment, + other => return Err(unexpected(&other)), + }; + let mut sha256 = digest::Context::new(&digest::SHA256); + // A failing `out`: the parts are still all read, the connection + // stays usable. + let mut failed = None; + for part in 0..attachment.part_count() { + let data = match self.answer()? { + Packet::AttachmentPart(part) => part.data, + other => { + self.close(); + return Err(unexpected(&other)); + } + }; + let expected = attachment.part_len(part); + if data.len() as u64 != expected { + self.close(); + return Err(Error::new( + ErrorCode::ProtocolError, + format!("part {part}: {} bytes, {expected} expected", data.len()), + )); + } + sha256.update(&data); + if failed.is_none() { + failed = out.write_all(&data).err(); + } + } + if let Some(error) = failed { + return Err(file_error(error)); + } + out.flush().map_err(file_error)?; + if sha256.finish().as_ref() != attachment.sha256 { + return Err(Error::new( + ErrorCode::AttachmentMismatch, + "the attachment doesn't match its SHA-256", + )); + } + Ok(attachment.size) + } + + /// Saves a message's attachment as `path` ([`Client::get_attachment`]): + /// written aside (`path` and `.download`), then moved over it, so a + /// failed one leaves no file. + pub fn save_attachment( + &mut self, + topic: &str, + node: &str, + message_id: u64, + path: &Path, + ) -> Result { + let mut aside = path.as_os_str().to_owned(); + aside.push(".download"); + let aside = PathBuf::from(aside); + let mut file = File::create(&aside).map_err(file_error)?; + let saved = self.get_attachment(topic, node, message_id, &mut file); + drop(file); + let saved = saved.and_then(|size| { + fs::rename(&aside, path).map_err(file_error)?; + Ok(size) + }); + if saved.is_err() { + let _ = fs::remove_file(&aside); + } + saved + } + + /// A topic and node's messages: `after` an id (0 for the first ones), + /// or the last ones (`None`); `limit` at most (1-10000). `more` if + /// others follow. + pub fn get_messages( + &mut self, + topic: &str, + node: &str, + after: Option, + limit: u32, + ) -> Result { + check_name(topic, "topic")?; + check_name(node, "node")?; + if !(1..=MAX_MESSAGES_PER_PACKET).contains(&limit) { + return Err(Error::new( + ErrorCode::InvalidArgument, + format!("a limit of {limit}: 1 to {MAX_MESSAGES_PER_PACKET}"), + )); + } + if after.is_some_and(|after| after > MAX_MESSAGE_ID) { + return Err(Error::new( + ErrorCode::InvalidArgument, + format!("after {}: {MAX_MESSAGE_ID} at most", after.unwrap_or(0)), + )); + } + let get = GetMessages { + topic: topic.to_owned(), + node: node.to_owned(), + after, + limit, + }; + match self.request(get.into())? { + Packet::Messages(messages) => Ok(messages), + other => Err(unexpected(&other)), + } + } + + /// The topics this client may push to or read (every one if it may + /// query), or every node with messages. `truncated` if some didn't fit. + pub fn list_names(&mut self, kind: NameKind) -> Result { + match self.request(ListNames { kind }.into())? { + Packet::NamesList(names) => Ok(names), + other => Err(unexpected(&other)), + } + } + + /// Runs read-only SQL: `{"columns":[...],"rows":[[...],...]}`, every + /// value a string or null (`docs/storage.md`, "The query surface"). + pub fn query(&mut self, sql: &str) -> Result { + check_size(sql, "a query")?; + let query = Query { + sql: sql.to_owned(), + }; + match self.request(query.into())? { + Packet::QueryResult(result) => Ok(result.json), + other => Err(unexpected(&other)), + } + } + + /// Closes the connection: it's out of step (a part not sent, or not + /// as expected). Every request fails then (`ConnectionLost`). + fn close(&mut self) { + let _ = self.stream.sock.shutdown(Shutdown::Both); + } + + /// Sends a request, reads its answer. + fn request(&mut self, packet: Packet) -> Result { + frame::write(&mut self.stream, &packet.encode()).map_err(lost)?; + self.stream.flush().map_err(lost)?; + self.answer() + } + + /// Reads the server's next packet: a refusal is an error. + fn answer(&mut self) -> Result { + let bytes = frame::read(&mut self.stream, MAX_PACKET_SIZE) + .map_err(lost)? + .ok_or_else(|| { + Error::new( + ErrorCode::ConnectionLost, + "the server closed the connection", + ) + })?; + match Packet::decode(&bytes) { + Ok(Packet::RequestRefused(refused)) => Err(Error { + code: refused.code, + message: refused.reason, + }), + Ok(packet) => Ok(packet), + Err(error) => Err(Error::new(ErrorCode::ProtocolError, error.to_string())), + } + } +} + +/// A TCP connection to the first of `address`'s addresses that answers. +fn connect_tcp(address: &str) -> Result { + let failed = |why: String| Error::new(ErrorCode::ConnectFailed, format!("{address}: {why}")); + let addresses = address + .to_socket_addrs() + .map_err(|error| failed(error.to_string()))?; + let mut last = String::from("no address"); + for socket in addresses { + match TcpStream::connect_timeout(&socket, CONNECT_TIMEOUT) { + Ok(tcp) => { + tcp.set_nodelay(true).map_err(lost)?; + tcp.set_read_timeout(Some(CONNECT_TIMEOUT)).map_err(lost)?; + tcp.set_write_timeout(Some(CONNECT_TIMEOUT)).map_err(lost)?; + return Ok(tcp); + } + Err(error) => last = error.to_string(), + } + } + Err(failed(last)) +} + +/// An I/O error's code: the TLS ones say who refused whom. +fn lost(error: io::Error) -> Error { + let tls = error + .get_ref() + .and_then(|inner| inner.downcast_ref::()); + match tls { + Some(rustls::Error::InvalidCertificate(why)) => Error::new( + ErrorCode::ServerNotVerified, + format!("the server's certificate: {why:?}"), + ), + Some(rustls::Error::AlertReceived(alert)) => Error::new( + ErrorCode::AuthRejected, + format!("the server refused this client's certificate ({alert:?})"), + ), + Some(other) => Error::new(ErrorCode::AuthRejected, other.to_string()), + None => Error::new(ErrorCode::ConnectionLost, error.to_string()), + } +} + +fn check_name(name: &str, what: &str) -> Result<()> { + if is_valid_name(name) { + Ok(()) + } else { + Err(Error::new( + ErrorCode::InvalidArgument, + format!("'{name}' isn't a {what} name"), + )) + } +} + +fn check_size(text: &str, what: &str) -> Result<()> { + if text.len() <= MAX_MESSAGE_SIZE { + Ok(()) + } else { + Err(Error::new( + ErrorCode::InvalidArgument, + format!("{what} of {} bytes: {MAX_MESSAGE_SIZE} at most", text.len()), + )) + } +} + +fn file_error(error: io::Error) -> Error { + Error::new(ErrorCode::FileError, format!("the attachment: {error}")) +} + +fn unexpected(packet: &Packet) -> Error { + Error::new( + ErrorCode::ProtocolError, + format!("the server answered {}", packet.packet_type().name()), + ) +} diff --git a/crates/bakashrot-config/Cargo.toml b/crates/bakashrot-config/Cargo.toml new file mode 100644 index 0000000..c5b8985 --- /dev/null +++ b/crates/bakashrot-config/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "bakashrot-config" +description = "BakaShrot's server config: topics, retention, replication, roles and what they may do." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +authors.workspace = true +repository.workspace = true +publish.workspace = true + +[dependencies] +# The name rules, the limits. +bakashrot-proto = { path = "../bakashrot-proto" } +# Sections kept in the file's order ([retention]'s first matching pattern +# wins): toml's `preserve_order` reads them in order, IndexMap keeps it. +indexmap = { version = "2.14.2", features = ["serde"] } +serde = { version = "1.0.229", features = ["derive"] } +# Reading only (`display`: values quoted back in errors). +toml = { version = "1.2.1", default-features = false, features = ["std", "parse", "serde", "display", "preserve_order"] } + +[lints] +workspace = true diff --git a/crates/bakashrot-config/example.toml b/crates/bakashrot-config/example.toml new file mode 100644 index 0000000..a2243ff --- /dev/null +++ b/crates/bakashrot-config/example.toml @@ -0,0 +1,70 @@ +# A BakaShrot server's config, every key with its default where it has +# one. Read by bakashrot-config, explained in docs/config.md. +# +# Names (topics, nodes, roles): 1-64 of A-Z a-z 0-9 _ . -, not only digits, +# case doesn't matter. Lists of topics or nodes also take patterns: * any +# characters, ? one ("sensors.*"), or "*" for all. +# Names with dots are quoted when they're keys: "sensors.kitchen" = "12h", +# [roles."site.reader"]. Durations: numbers with a unit (s m h d w), like +# "30s" or "1d12h". Relative paths are from this file's folder. + +[server] +listen = "0.0.0.0:7000" # required: address and port + +# The certificates (bakashrot-cert), required. The node this server is, +# for its peers, is its certificate's name. +ca = "ca.crt" +certificate = "server-1.crt" +key = "server-1.key" +# crl = "ca.crl" # the CA's CRL, watched: optional + +database = "bakashrot.sqlite" + +# The topics clients push to. Peers may bring others (accept_topics). +topics = ["logs", "sensors.kitchen", "sensors.garage"] + +# "full": every push flushed to disk before it's answered, it survives a +# power loss. "normal": about twice the pushes, a power loss loses the last +# second or so. ("off" isn't allowed.) +synchronous = "full" + +max_attachment_size = "1G" # bytes, or K M G T (1024-based); 0: none +retention_interval = "1m" # how often old messages are deleted + +# How long each topic's messages are kept, from when they were first +# pushed. A topic takes its name's line, else the first pattern matching +# it, else "*"'s; without any, it's kept forever. +[retention] +logs = "30d" +"sensors.*" = "12h" +"*" = "forever" + +# Who this server replicates with, by address. A link carries messages +# one way: the server that dials sends, the one dialed takes them. +[replication] +push_to = [] # dialed and sent to: ["10.0.0.2:7000", "server-2.lan:7000"] +accept_from = [] # taken from: ["10.0.0.2", "server-2.lan"], or ["*"] +# The only topics replicated at all, whatever the roles say: a filter for +# edge nodes. Without it, no filter; [] replicates nothing. +# replicated_topics = ["logs", "alerts.*"] +retry_delay = "10s" +sync_interval = "5s" +batch_size = 1000 # messages per packet, 1-10000 + +# What certificates with a role may do. A certificate gets everything its +# roles allow; one without any role listed here is refused. Every key is +# optional: an empty list allows nothing. +[roles.sensor] +push_topics = ["sensors.*"] # always as its own node (its name) + +[roles.dashboard] +read_topics = ["*"] +query = true # read-only SQL, reads every topic + +# Peers are roles too: what's replicated with a server whose certificate +# has this role, whichever end dials. +[roles.peer] +send_topics = ["logs", "sensors.*"] +accept_topics = ["logs"] +send_nodes = ["*"] # the default +accept_nodes = ["*"] # the default diff --git a/crates/bakashrot-config/src/lib.rs b/crates/bakashrot-config/src/lib.rs new file mode 100644 index 0000000..8f6ee89 --- /dev/null +++ b/crates/bakashrot-config/src/lib.rs @@ -0,0 +1,325 @@ +//! The server's config: a TOML file, read and checked in one go. +//! +//! - [`Server`]: where it listens, its files, its topics, its database. +//! - [`Retention`]: how long each topic's messages are kept. +//! - [`Replication`]: the servers it sends to and takes from, what it +//! replicates, how often. +//! - [`Role`]: what certificates with a role may do; [`Permissions`]: what +//! a certificate's roles allow together. +//! +//! Who connects is the certificate's (`bakashrot-pki`): its name is its +//! node, its roles are looked up here. Peers too: what's replicated with a +//! peer is its roles'. The file, every key and its default: +//! `docs/config.md`. +//! +//! Every value is checked as serde reads it, so a wrong one is refused with +//! its line. + +mod roles; +mod values; + +pub use roles::{NameList, Permissions, Role}; + +use bakashrot_proto::names::{is_valid_name, is_valid_pattern, names_equal, pattern_matches}; +use indexmap::IndexMap; +use serde::{Deserialize, Deserializer, de::Error as _}; +use std::fmt; +use std::net::SocketAddr; +use std::path::{Path, PathBuf}; +use std::time::Duration; +use values::{DURATION_HELP, NAME_HELP, parse_age}; + +/// What's wrong with a config, in words: where (the file, the line) and why. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Error(String); + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +impl std::error::Error for Error {} + +/// A result of this crate. +pub type Result = std::result::Result; + +/// A server's config. +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Config { + /// `[server]`. + pub server: Server, + /// `[retention]`. + #[serde(default)] + pub retention: Retention, + /// `[replication]`. + #[serde(default)] + pub replication: Replication, + /// `[roles.]`, in the file's order. + #[serde(default, deserialize_with = "roles")] + pub roles: Vec, +} + +/// `[server]`. +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Server { + /// The address and port it listens on. + #[serde(deserialize_with = "values::listen")] + pub listen: SocketAddr, + /// The CA's certificate. + pub ca: PathBuf, + /// The server's certificate. + pub certificate: PathBuf, + /// The server's key. + pub key: PathBuf, + /// The CA's CRL, watched; none: nothing revoked. + #[serde(default)] + pub crl: Option, + /// The SQLite database; `bakashrot.sqlite` by default. + #[serde(default = "defaults::database")] + pub database: PathBuf, + /// The topics clients push to, by name. + #[serde(default, deserialize_with = "values::topic_names")] + pub topics: Vec, + /// How hard a push is made sure to be on disk. + #[serde(default)] + pub synchronous: Synchronous, + /// The biggest attachment taken, in bytes; 0: none. 1G by default. + #[serde( + default = "defaults::max_attachment_size", + deserialize_with = "values::size" + )] + pub max_attachment_size: u64, + /// How often messages past their age are deleted; 1m by default. + #[serde( + default = "defaults::retention_interval", + deserialize_with = "values::duration" + )] + pub retention_interval: Duration, +} + +impl Server { + /// Whether `topic` is one of its topics. + pub fn has_topic(&self, topic: &str) -> bool { + self.topics.iter().any(|own| names_equal(own, topic)) + } +} + +/// How hard the database makes sure a push is on disk before answering it +/// (SQLite's `synchronous`). +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)] +#[serde(try_from = "String")] +pub enum Synchronous { + /// Every commit flushed: an answered push survives a power loss. The + /// default. + #[default] + Full, + /// Flushed about once a second: faster, a power loss loses the last + /// second or so of answered pushes. + Normal, +} + +impl TryFrom for Synchronous { + type Error = String; + + fn try_from(text: String) -> std::result::Result { + match text.trim().to_ascii_lowercase().as_str() { + "full" => Ok(Synchronous::Full), + "normal" => Ok(Synchronous::Normal), + "off" => Err( + "\"off\" isn't allowed: a power loss could corrupt the database. \ + \"full\", or \"normal\" to only risk the last second of messages" + .into(), + ), + "extra" => Err("\"extra\" does nothing more than \"full\" here: write \"full\"".into()), + _ => Err(format!("'{text}' isn't \"full\" or \"normal\"")), + } + } +} + +/// `[retention]`: how long each topic's messages are kept, from when they +/// were first pushed. +#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)] +#[serde(try_from = "IndexMap")] +pub struct Retention { + /// Names and patterns with their age (none: forever), in the file's + /// order. + lines: Vec<(String, Option)>, +} + +impl TryFrom> for Retention { + type Error = String; + + fn try_from(table: IndexMap) -> std::result::Result { + let mut lines: Vec<(String, Option)> = Vec::with_capacity(table.len()); + for (key, value) in table { + if !is_valid_pattern(&key) && !is_valid_name(&key) { + return Err(format!( + "'{key}' isn't a topic name or a pattern ({NAME_HELP})" + )); + } + if lines.iter().any(|(before, _)| names_equal(before, &key)) { + return Err(format!("'{key}' is given twice")); + } + let age = match &value { + toml::Value::String(text) => parse_age(text), + toml::Value::Table(_) => { + return Err(format!( + "'{key}' is a table: quote names with dots, \"{key}.x\" = \"30d\"" + )); + } + _ => None, + }; + let age = age.ok_or_else(|| { + format!("{key} = {value} isn't an age: {DURATION_HELP}, or \"forever\"") + })?; + lines.push((key, age)); + } + Ok(Retention { lines }) + } +} + +impl Retention { + /// How long `topic`'s messages are kept, `None` for forever: its name's + /// line, else the first pattern matching it, else `*`'s, else forever. + pub fn age(&self, topic: &str) -> Option { + let line = |found: fn(&str, &str) -> bool| { + self.lines + .iter() + .find(|(key, _)| key != "*" && found(key, topic)) + }; + line(names_equal) + .or_else(|| line(|key, topic| is_valid_pattern(key) && pattern_matches(key, topic))) + .or_else(|| self.lines.iter().find(|(key, _)| key == "*")) + .and_then(|(_, age)| *age) + } +} + +/// `[replication]`. +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct Replication { + /// The servers it dials and sends to (`host:port`). What's sent to + /// each is its roles' `send_*`. + #[serde(deserialize_with = "values::peers")] + pub push_to: Vec, + /// The servers it takes replicated messages from: IP addresses or + /// hostnames, `*` for all; none by default. What's taken is their + /// roles' `accept_*`. + #[serde(deserialize_with = "values::hosts")] + pub accept_from: Vec, + /// The only topics replicated at all, whatever the roles say (an edge + /// node's filter); none: no filter. + pub replicated_topics: Option, + /// How long to wait before dialing a peer again; 10s by default. + #[serde(deserialize_with = "values::duration")] + pub retry_delay: Duration, + /// How long a link waits, once nothing was left to send, before it + /// looks again; 5s by default. + #[serde(deserialize_with = "values::duration")] + pub sync_interval: Duration, + /// The most messages sent to a peer per packet; 1000 by default. + #[serde(deserialize_with = "values::batch_size")] + pub batch_size: u32, +} + +impl Default for Replication { + fn default() -> Self { + Replication { + push_to: Vec::new(), + accept_from: Vec::new(), + replicated_topics: None, + retry_delay: Duration::from_secs(10), + sync_interval: Duration::from_secs(5), + batch_size: 1000, + } + } +} + +/// `[server]`'s defaults. +mod defaults { + use std::path::PathBuf; + use std::time::Duration; + + pub(crate) fn database() -> PathBuf { + "bakashrot.sqlite".into() + } + pub(crate) fn max_attachment_size() -> u64 { + 1 << 30 + } + pub(crate) fn retention_interval() -> Duration { + Duration::from_secs(60) + } +} + +/// `[roles.*]`: each section's name is its role's, none twice. +fn roles<'de, D: Deserializer<'de>>(reader: D) -> std::result::Result, D::Error> { + let table = IndexMap::::deserialize(reader)?; + let mut roles: Vec = Vec::with_capacity(table.len()); + for (name, mut role) in table { + if !is_valid_name(&name) { + return Err(D::Error::custom(format!( + "'{name}' isn't a role name ({NAME_HELP})" + ))); + } + if let Some(before) = roles.iter().find(|role| names_equal(&role.name, &name)) { + return Err(D::Error::custom(format!( + "'{}' and '{name}' are the same role (case doesn't matter)", + before.name + ))); + } + role.name = name; + roles.push(role); + } + Ok(roles) +} + +impl Config { + /// Reads the config file at `path`. Relative paths in it are from its + /// folder. + pub fn load(path: &Path) -> Result { + let in_file = |error: &dyn fmt::Display| Error(format!("{}: {error}", path.display())); + let text = std::fs::read_to_string(path).map_err(|error| in_file(&error))?; + let mut config = Config::parse(&text).map_err(|error| in_file(&error))?; + let folder = path.parent().unwrap_or(Path::new("")); + let server = &mut config.server; + for file in [ + &mut server.ca, + &mut server.certificate, + &mut server.key, + &mut server.database, + ] + .into_iter() + .chain(server.crl.as_mut()) + { + *file = folder.join(&*file); + } + Ok(config) + } + + /// Reads a config, paths as they're written. + pub fn parse(text: &str) -> Result { + toml::from_str(text).map_err(|error| Error(error.to_string().trim_end().to_owned())) + } + + /// What a certificate with these roles may do: everything its roles + /// with a section allow. `None` if none has one: it's refused. + pub fn permissions>(&self, roles: &[S]) -> Option { + let roles: Vec = self + .roles + .iter() + .filter(|role| { + roles + .iter() + .any(|own| names_equal(own.as_ref(), &role.name)) + }) + .cloned() + .collect(); + (!roles.is_empty()).then(|| Permissions { + roles, + replicated_topics: self.replication.replicated_topics.clone(), + }) + } +} diff --git a/crates/bakashrot-config/src/roles.rs b/crates/bakashrot-config/src/roles.rs new file mode 100644 index 0000000..296c29b --- /dev/null +++ b/crates/bakashrot-config/src/roles.rs @@ -0,0 +1,167 @@ +//! Roles, and what a certificate's roles allow together. + +use crate::values::check_names; +use bakashrot_proto::names::{names_equal, pattern_matches}; +use serde::Deserialize; + +/// Topic or node names and patterns (`sensors.*`, `*` for all), none twice. +#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)] +#[serde(try_from = "Vec")] +pub struct NameList(Vec); + +impl TryFrom> for NameList { + type Error = String; + + fn try_from(list: Vec) -> Result { + check_names(&list, true)?; + Ok(NameList(list)) + } +} + +impl NameList { + /// `*`: every name. + pub fn every() -> NameList { + NameList(vec!["*".to_owned()]) + } + + /// Whether `name` is in it: one of its names, or matched by one of its + /// patterns (without case). + pub fn matches(&self, name: &str) -> bool { + self.0 + .iter() + .any(|entry| names_equal(entry, name) || pattern_matches(entry, name)) + } + + /// Whether it has nothing: matches nothing. + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + + /// Its names and patterns, as written. + pub fn entries(&self) -> &[String] { + &self.0 + } +} + +/// A `[roles.]` section: what certificates with this role may do. +/// Every key is optional. +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Role { + /// The role, as certificates say it (compared without case): the + /// section's name. + #[serde(skip)] + pub name: String, + /// The topics it may push to, always as its own node. + #[serde(default)] + pub push_topics: NameList, + /// The topics it may read the messages of. + #[serde(default)] + pub read_topics: NameList, + /// Whether it may run read-only SQL, which reads every topic. + #[serde(default)] + pub query: bool, + /// Replication: the topics sent to it. + #[serde(default)] + pub send_topics: NameList, + /// Replication: the topics taken from it. + #[serde(default)] + pub accept_topics: NameList, + /// Replication: the nodes whose messages are sent to it (all by default). + #[serde(default = "NameList::every")] + pub send_nodes: NameList, + /// Replication: the nodes whose messages are taken from it (all by + /// default). + #[serde(default = "NameList::every")] + pub accept_nodes: NameList, +} + +/// What a certificate may do: everything one of its roles allows, each role +/// on its own (a role's topics go with that role's nodes), replication +/// within the server's `replicated_topics`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Permissions { + pub(crate) roles: Vec, + pub(crate) replicated_topics: Option, +} + +impl Permissions { + /// Its roles that this server has a section for. + pub fn roles(&self) -> impl Iterator { + self.roles.iter().map(|role| role.name.as_str()) + } + + /// Whether it may push to `topic`. + pub fn can_push(&self, topic: &str) -> bool { + self.roles + .iter() + .any(|role| role.push_topics.matches(topic)) + } + + /// Whether it may read `topic`'s messages. + pub fn can_read(&self, topic: &str) -> bool { + self.roles + .iter() + .any(|role| role.read_topics.matches(topic)) + } + + /// Whether it may run read-only SQL. + pub fn can_query(&self) -> bool { + self.roles.iter().any(|role| role.query) + } + + /// Whether `node`'s messages in `topic` are sent to it. + pub fn sends(&self, topic: &str, node: &str) -> bool { + self.replicated(topic) + && self + .roles + .iter() + .any(|role| role.send_topics.matches(topic) && role.send_nodes.matches(node)) + } + + /// Whether `node`'s messages in `topic` are taken from it. + pub fn accepts(&self, topic: &str, node: &str) -> bool { + self.replicated(topic) + && self + .roles + .iter() + .any(|role| role.accept_topics.matches(topic) && role.accept_nodes.matches(node)) + } + + /// The topics and the nodes taken from it, as `SyncState` lists them: + /// its roles' `accept_*` (of those that accept topics), none twice. + /// What's taken is still [`Permissions::accepts`]'. + pub fn accepted(&self) -> (Vec, Vec) { + let (mut topics, mut nodes) = (Vec::::new(), Vec::::new()); + for role in self + .roles + .iter() + .filter(|role| !role.accept_topics.is_empty()) + { + for (list, entries) in [ + (&mut topics, role.accept_topics.entries()), + (&mut nodes, role.accept_nodes.entries()), + ] { + for entry in entries { + if !list.iter().any(|known| names_equal(known, entry)) { + list.push(entry.clone()); + } + } + } + } + (topics, nodes) + } + + /// Whether it replicates at all: a peer. + pub fn replicates(&self) -> bool { + self.roles + .iter() + .any(|role| !role.send_topics.is_empty() || !role.accept_topics.is_empty()) + } + + fn replicated(&self, topic: &str) -> bool { + self.replicated_topics + .as_ref() + .is_none_or(|topics| topics.matches(topic)) + } +} diff --git a/crates/bakashrot-config/src/values.rs b/crates/bakashrot-config/src/values.rs new file mode 100644 index 0000000..d2a4da0 --- /dev/null +++ b/crates/bakashrot-config/src/values.rs @@ -0,0 +1,277 @@ +//! The values that need more than a type: durations, ages, sizes, +//! addresses, names. + +use bakashrot_proto::limits::{MAX_ATTACHMENT_SIZE, MAX_MESSAGES_PER_PACKET}; +use bakashrot_proto::names::{is_valid_name, is_valid_name_or_pattern, names_equal}; +use serde::de::Error as _; +use serde::{Deserialize, Deserializer}; +use std::net::{Ipv6Addr, SocketAddr}; +use std::time::Duration; + +/// What a duration looks like, for errors. +pub(crate) const DURATION_HELP: &str = "numbers with a unit (s m h d w), like 30s or 1d12h"; + +/// What a name looks like, for errors. +pub(crate) const NAME_HELP: &str = "1-64 of A-Z a-z 0-9 _ . -, not only digits; patterns: * and ?"; + +/// A duration: numbers with a unit, added up (`1d12h`). Units `s m h d w`, +/// without case. More than 0. +pub(crate) fn parse_duration(text: &str) -> Option { + let mut seconds: u64 = 0; + let mut number: Option = None; + for c in text.trim().chars() { + if let Some(digit) = c.to_digit(10) { + number = Some( + number + .unwrap_or(0) + .checked_mul(10)? + .checked_add(digit.into())?, + ); + continue; + } + let unit: u64 = match c.to_ascii_lowercase() { + 's' => 1, + 'm' => 60, + 'h' => 3600, + 'd' => 86_400, + 'w' => 604_800, + _ => return None, + }; + seconds = seconds.checked_add(number.take()?.checked_mul(unit)?)?; + } + if number.is_some() || seconds == 0 { + return None; + } + Some(Duration::from_secs(seconds)) +} + +/// A retention age: a duration, or `forever` (`Some(None)`). +pub(crate) fn parse_age(text: &str) -> Option> { + if text.trim().eq_ignore_ascii_case("forever") { + return Some(None); + } + parse_duration(text).map(Some) +} + +/// A size: bytes (a number), or text with K, M, G or T (1024-based, without +/// case), up to `MAX_ATTACHMENT_SIZE`. 0 is a size. +pub(crate) fn parse_size(value: &toml::Value) -> Option { + let size = match value { + toml::Value::Integer(bytes) => u64::try_from(*bytes).ok()?, + toml::Value::String(text) => { + let text = text.trim(); + let (digits, unit) = match text.char_indices().last()? { + (at, c) if c.is_ascii_alphabetic() => (&text[..at], c.to_ascii_uppercase()), + _ => (text, 'B'), + }; + let shift = match unit { + 'B' => 0, + 'K' => 10, + 'M' => 20, + 'G' => 30, + 'T' => 40, + _ => return None, + }; + if digits.is_empty() || !digits.bytes().all(|c| c.is_ascii_digit()) { + return None; + } + digits.parse::().ok()?.checked_mul(1 << shift)? + } + _ => return None, + }; + (size <= MAX_ATTACHMENT_SIZE).then_some(size) +} + +/// Whether `text` is a host and a port: `10.0.0.2:7000`, +/// `server-2.lan:7000`, `[fd00::2]:7000`. The port isn't 0. +pub(crate) fn is_peer_address(text: &str) -> bool { + let Some((host, port)) = text.rsplit_once(':') else { + return false; + }; + let port = port.parse::().is_ok_and(|port| port != 0); + let host = match host.strip_prefix('[').and_then(|h| h.strip_suffix(']')) { + Some(v6) => v6.parse::().is_ok(), + None => is_hostname(host), + }; + port && host +} + +/// A hostname or an IPv4 address: letters, digits, dots and dashes. +fn is_hostname(host: &str) -> bool { + !host.is_empty() + && host + .bytes() + .all(|c| c.is_ascii_alphanumeric() || c == b'.' || c == b'-') +} + +// As serde reads them (`deserialize_with`): a value that's wrong fails +// there, and toml says on which line. + +/// A duration, more than 0. +pub(crate) fn duration<'de, D: Deserializer<'de>>(reader: D) -> Result { + let text = String::deserialize(reader)?; + parse_duration(&text) + .ok_or_else(|| D::Error::custom(format!("'{text}' isn't a duration: {DURATION_HELP}"))) +} + +/// A size up to `MAX_ATTACHMENT_SIZE`. +pub(crate) fn size<'de, D: Deserializer<'de>>(reader: D) -> Result { + let value = toml::Value::deserialize(reader)?; + parse_size(&value).ok_or_else(|| { + D::Error::custom(format!( + "{value} isn't a size up to 1T: bytes, or a number with K, M, G or T, like \"500M\" \ + (0: no attachments)" + )) + }) +} + +/// An address and a port to listen on. +pub(crate) fn listen<'de, D: Deserializer<'de>>(reader: D) -> Result { + let text = String::deserialize(reader)?; + text.parse().map_err(|_| { + D::Error::custom(format!( + "'{text}' isn't an address and a port, like \"0.0.0.0:7000\"" + )) + }) +} + +/// Peer addresses, none twice. +pub(crate) fn peers<'de, D: Deserializer<'de>>(reader: D) -> Result, D::Error> { + let peers = Vec::::deserialize(reader)?; + for (at, peer) in peers.iter().enumerate() { + if !is_peer_address(peer) { + return Err(D::Error::custom(format!( + "'{peer}' isn't a host and a port, like \"10.0.0.2:7000\" or \ + \"server-2.lan:7000\"" + ))); + } + if peers[..at].contains(peer) { + return Err(D::Error::custom(format!("'{peer}' is given twice"))); + } + } + Ok(peers) +} + +/// Hosts without a port: IP addresses or hostnames, or `*` for all; none +/// twice. +pub(crate) fn hosts<'de, D: Deserializer<'de>>(reader: D) -> Result, D::Error> { + let hosts = Vec::::deserialize(reader)?; + for (at, host) in hosts.iter().enumerate() { + if host != "*" && !is_hostname(host) && host.parse::().is_err() { + return Err(D::Error::custom(format!( + "'{host}' isn't an IP address or a hostname (without a port), like \ + \"10.0.0.2\" or \"server-2.lan\", or \"*\" for all" + ))); + } + if hosts[..at] + .iter() + .any(|before| before.eq_ignore_ascii_case(host)) + { + return Err(D::Error::custom(format!("'{host}' is given twice"))); + } + } + Ok(hosts) +} + +/// A batch size, 1 to `MAX_MESSAGES_PER_PACKET`. +pub(crate) fn batch_size<'de, D: Deserializer<'de>>(reader: D) -> Result { + let size = u32::deserialize(reader)?; + if !(1..=MAX_MESSAGES_PER_PACKET).contains(&size) { + return Err(D::Error::custom(format!( + "the batch size must be 1 to {MAX_MESSAGES_PER_PACKET}" + ))); + } + Ok(size) +} + +/// Topic names (no patterns), none twice. +pub(crate) fn topic_names<'de, D: Deserializer<'de>>(reader: D) -> Result, D::Error> { + let names = Vec::::deserialize(reader)?; + check_names(&names, false).map_err(D::Error::custom)?; + Ok(names) +} + +/// Checks a list of names (`patterns`: or patterns), none twice. +pub(crate) fn check_names(list: &[String], patterns: bool) -> Result<(), String> { + for (at, entry) in list.iter().enumerate() { + let (valid, what) = if patterns { + (is_valid_name_or_pattern(entry), "a name or a pattern") + } else { + (is_valid_name(entry), "a name") + }; + if !valid { + return Err(format!("'{entry}' isn't {what} ({NAME_HELP})")); + } + if list[..at].iter().any(|before| names_equal(before, entry)) { + return Err(format!("'{entry}' is given twice")); + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn durations() { + let s = Duration::from_secs; + assert_eq!(parse_duration("30s"), Some(s(30))); + assert_eq!(parse_duration("1d12h"), Some(s(129_600))); + assert_eq!(parse_duration(" 2W "), Some(s(1_209_600))); + assert_eq!(parse_duration("1m30s"), Some(s(90))); + for bad in [ + "", + "30", + "s", + "1x", + "0s", + "1h 30m", + "-1s", + "99999999999999999999w", + ] { + assert_eq!(parse_duration(bad), None, "{bad}"); + } + assert_eq!(parse_age("Forever"), Some(None)); + assert_eq!(parse_age("30d"), Some(Some(s(2_592_000)))); + assert_eq!(parse_age("never"), None); + } + + #[test] + fn sizes() { + let text = |t: &str| parse_size(&toml::Value::String(t.into())); + assert_eq!(text("0"), Some(0)); + assert_eq!(text("500"), Some(500)); + assert_eq!(text("500k"), Some(500 << 10)); + assert_eq!(text("1G"), Some(1 << 30)); + assert_eq!(text("1T"), Some(1 << 40)); + assert_eq!(parse_size(&toml::Value::Integer(1024)), Some(1024)); + for bad in ["", "G", "2T", "1.5G", "1GB", "-1", "1 G"] { + assert_eq!(text(bad), None, "{bad}"); + } + assert_eq!(parse_size(&toml::Value::Integer(-1)), None); + assert_eq!(parse_size(&toml::Value::Boolean(true)), None); + } + + #[test] + fn peer_addresses() { + for good in [ + "10.0.0.2:7000", + "server-2.lan:7000", + "[fd00::2]:7000", + "localhost:1", + ] { + assert!(is_peer_address(good), "{good}"); + } + for bad in [ + "10.0.0.2", + "10.0.0.2:0", + ":7000", + "fd00::2:7000", + "a b:7000", + "x:70000", + ] { + assert!(!is_peer_address(bad), "{bad}"); + } + } +} diff --git a/crates/bakashrot-config/tests/config.rs b/crates/bakashrot-config/tests/config.rs new file mode 100644 index 0000000..84472be --- /dev/null +++ b/crates/bakashrot-config/tests/config.rs @@ -0,0 +1,391 @@ +//! Configs taken and refused, and what they mean. + +use bakashrot_config::{Config, Synchronous}; +use std::path::Path; +use std::time::Duration; + +const EXAMPLE: &str = include_str!("../example.toml"); + +/// The least a config has. +const MINIMAL: &str = r#" +[server] +listen = "127.0.0.1:7000" +ca = "ca.crt" +certificate = "server.crt" +key = "server.key" +"#; + +fn with(extra: &str) -> String { + format!("{MINIMAL}{extra}") +} + +/// The error of a config that must be refused. +fn refused(text: &str) -> String { + match Config::parse(text) { + Ok(config) => panic!("taken: {config:?}\n{text}"), + Err(error) => error.to_string(), + } +} + +fn days(days: u64) -> Option { + Some(Duration::from_secs(days * 86_400)) +} + +#[test] +fn the_example() { + let config = Config::parse(EXAMPLE).unwrap(); + let server = &config.server; + assert_eq!(server.listen, "0.0.0.0:7000".parse().unwrap()); + assert_eq!(server.crl, None); + assert_eq!(server.topics.len(), 3); + assert!(server.has_topic("Sensors.Kitchen")); + assert!(!server.has_topic("sensors")); + assert_eq!(server.synchronous, Synchronous::Full); + assert_eq!(server.max_attachment_size, 1 << 30); + assert_eq!(config.replication.push_to, Vec::::new()); + assert_eq!(config.replication.accept_from, Vec::::new()); + assert_eq!(config.retention.age("logs"), days(30)); + assert_eq!( + config.retention.age("sensors.kitchen"), + Some(Duration::from_secs(43_200)) + ); + assert_eq!(config.retention.age("other"), None); + let names: Vec<&str> = config.roles.iter().map(|role| role.name.as_str()).collect(); + assert_eq!(names, ["sensor", "dashboard", "peer"]); +} + +#[test] +fn defaults() { + let config = Config::parse(MINIMAL).unwrap(); + let server = &config.server; + assert_eq!(server.database, Path::new("bakashrot.sqlite")); + assert!(server.topics.is_empty()); + assert_eq!(server.synchronous, Synchronous::Full); + assert_eq!(server.max_attachment_size, 1 << 30); + assert_eq!(server.retention_interval, Duration::from_secs(60)); + assert_eq!(config.retention.age("logs"), None); + assert_eq!(config.replication.retry_delay, Duration::from_secs(10)); + assert_eq!(config.replication.sync_interval, Duration::from_secs(5)); + assert_eq!(config.replication.batch_size, 1000); + assert_eq!(config.replication.replicated_topics, None); + assert!(config.roles.is_empty()); + assert!(config.permissions(&["anything"]).is_none()); +} + +#[test] +fn settings() { + let config = Config::parse(&with( + r#"crl = "ca.crl" +database = "data/messages.sqlite" +synchronous = "NORMAL" +max_attachment_size = 0 +retention_interval = "1h30m" + +[replication] +push_to = ["10.0.0.2:7000", "server-3.lan:7001", "[fd00::4]:7000"] +accept_from = ["10.0.0.2", "server-3.lan", "fd00::4"] +retry_delay = "1m" +sync_interval = "2s" +batch_size = 10000 +replicated_topics = ["logs"] +"#, + )) + .unwrap(); + assert_eq!(config.server.crl.as_deref(), Some(Path::new("ca.crl"))); + assert_eq!(config.server.synchronous, Synchronous::Normal); + assert_eq!(config.server.max_attachment_size, 0); + assert_eq!(config.server.retention_interval, Duration::from_secs(5400)); + assert_eq!(config.replication.push_to.len(), 3); + assert_eq!(config.replication.accept_from[2], "fd00::4"); + assert_eq!(config.replication.retry_delay, Duration::from_secs(60)); + assert_eq!(config.replication.batch_size, 10_000); +} + +#[test] +fn retention_order() { + let config = Config::parse(&with( + r#" +[retention] +"*" = "365d" +"sensors.?????" = "1h" +"sensors.*" = "12h" +"sensors.k*" = "2h" +"Sensors.Kitchen" = "forever" +logs = "30d" +"#, + )) + .unwrap(); + let age = |topic| config.retention.age(topic); + let hours = |hours: u64| Some(Duration::from_secs(hours * 3600)); + // Its name's line first, wherever it is. + assert_eq!(age("sensors.kitchen"), None); + assert_eq!(age("LOGS"), days(30)); + // Else the first pattern in the file's order (sorted, "sensors.*" + // would come first), not the closest. + assert_eq!(age("sensors.alpha"), hours(1)); + assert_eq!(age("sensors.kettle"), hours(12)); + // "*" last, though it's first. + assert_eq!(age("other"), days(365)); +} + +#[test] +fn permissions() { + let config = Config::parse(&with( + r#" +[roles.sensor] +push_topics = ["sensors.*"] + +[roles.Reader] +read_topics = ["logs", "sensors.kitchen"] + +[roles.admin] +query = true + +[roles.peer] +send_topics = ["logs"] +send_nodes = ["kitchen-*"] + +[roles.backup] +send_topics = ["sensors.*"] +accept_topics = ["*"] +accept_nodes = ["garage"] + +[roles.idle] +"#, + )) + .unwrap(); + + // None of its roles here: refused. Roles compare without case. + assert!(config.permissions(&["unknown"]).is_none()); + assert!(config.permissions::<&str>(&[]).is_none()); + let idle = config.permissions(&["IDLE", "unknown"]).unwrap(); + assert_eq!(idle.roles().collect::>(), ["idle"]); + assert!(!idle.can_push("logs") && !idle.can_read("logs") && !idle.can_query()); + assert!(!idle.replicates()); + + // Everything its roles allow. + let both = config.permissions(&["sensor", "reader"]).unwrap(); + assert!(both.can_push("sensors.garage")); + assert!(!both.can_push("logs")); + assert!(both.can_read("Logs")); + assert!(!both.can_read("sensors.garage")); + assert!(!both.can_query()); + assert!(config.permissions(&["admin"]).unwrap().can_query()); + + // Replication: each role's topics with that role's nodes, not mixed. + let peer = config.permissions(&["peer", "backup"]).unwrap(); + assert!(peer.replicates()); + assert!(peer.sends("logs", "kitchen-1")); + assert!(!peer.sends("logs", "garage")); + assert!(peer.sends("sensors.a", "garage")); + assert!(!peer.sends("other", "kitchen-1")); + assert!(peer.accepts("anything", "garage")); + assert!(!peer.accepts("logs", "kitchen-1")); + // A role without the topics replicates nothing, whatever its nodes. + let only_peer = config.permissions(&["peer"]).unwrap(); + assert!(!only_peer.accepts("logs", "kitchen-1")); + // What SyncState lists: the accepting roles' lists only. + let strings = |list: &[&str]| list.iter().map(|s| s.to_string()).collect::>(); + assert_eq!(peer.accepted(), (strings(&["*"]), strings(&["garage"]))); + assert_eq!(only_peer.accepted(), (vec![], vec![])); +} + +#[test] +fn replicated_topics_filter_the_roles() { + let config = Config::parse(&with( + r#" +[replication] +replicated_topics = ["logs", "alerts.*"] + +[roles.peer] +send_topics = ["*"] +accept_topics = ["*"] + +[roles.sensor] +push_topics = ["*"] +"#, + )) + .unwrap(); + let peer = config.permissions(&["peer", "sensor"]).unwrap(); + assert!(peer.sends("logs", "kitchen") && peer.accepts("Logs", "kitchen")); + assert!(peer.sends("alerts.fire", "kitchen")); + assert!(!peer.sends("sensors.a", "kitchen") && !peer.accepts("sensors.a", "kitchen")); + assert!(peer.replicates()); + // Only replication: pushing isn't filtered. + assert!(peer.can_push("sensors.a")); + + // Empty: nothing replicated. + let none = Config::parse(&with( + "[replication]\nreplicated_topics = []\n[roles.peer]\nsend_topics = [\"*\"]\n", + )) + .unwrap(); + assert!( + !none + .permissions(&["peer"]) + .unwrap() + .sends("logs", "kitchen") + ); + assert!(refused(&with("[replication]\nreplicated_topics = [\"a b\"]\n")).contains("'a b'")); +} + +#[test] +fn files_are_from_the_configs_folder() { + let folder = std::env::temp_dir().join(format!("bakashrot-config-{}", std::process::id())); + std::fs::create_dir_all(&folder).unwrap(); + let path = folder.join("server.toml"); + std::fs::write(&path, with("crl = \"revoked/ca.crl\"\n")).unwrap(); + let config = Config::load(&path).unwrap(); + assert_eq!(config.server.ca, folder.join("ca.crt")); + assert_eq!(config.server.crl, Some(folder.join("revoked/ca.crl"))); + assert_eq!(config.server.database, folder.join("bakashrot.sqlite")); + + std::fs::write(&path, "[server]\n").unwrap(); + let error = Config::load(&path).unwrap_err().to_string(); + assert!(error.starts_with(&path.display().to_string()), "{error}"); + assert!(error.contains("listen"), "{error}"); + std::fs::remove_dir_all(&folder).unwrap(); + + let error = Config::load(&folder.join("missing.toml")).unwrap_err(); + assert!(error.to_string().contains("missing.toml"), "{error}"); +} + +#[test] +fn refusals() { + let cases: &[(&str, &str)] = &[ + // Not TOML, or another shape: the line is said. + ("[server", "line 1"), + ("", "missing field `server`"), + (&with("lsiten = \"x\"\n"), "unknown field `lsiten`"), + (&with("[other]\n"), "unknown field `other`"), + // The old ini's keys. + (&with("PrivateKey = \"x\"\n"), "unknown field `PrivateKey`"), + ( + &with("[roles.sensor]\nAllowWrite = 1\n"), + "unknown field `AllowWrite`", + ), + ( + &with("[roles.sensor]\ndefault_topic = \"x\"\n"), + "unknown field `default_topic`", + ), + // [server] + ( + &MINIMAL.replace("127.0.0.1:7000", "127.0.0.1"), + "'127.0.0.1' isn't an address and a port", + ), + (&with("topics = [\"a b\"]\n"), "'a b' isn't a name ("), + ( + &with("topics = [\"sensors.*\"]\n"), + "'sensors.*' isn't a name (", + ), + (&with("topics = [\"12\"]\n"), "'12' isn't a name"), + ( + &with("topics = [\"logs\", \"Logs\"]\n"), + "'Logs' is given twice", + ), + ( + &with("synchronous = \"OFF\"\n"), + "isn't allowed: a power loss", + ), + (&with("synchronous = \"extra\"\n"), "write \"full\""), + ( + &with("synchronous = \"fast\"\n"), + "'fast' isn't \"full\" or \"normal\"", + ), + ( + &with("max_attachment_size = \"2T\"\n"), + "isn't a size up to 1T", + ), + (&with("max_attachment_size = -1\n"), "isn't a size up to 1T"), + ( + &with("max_attachment_size = \"1GB\"\n"), + "isn't a size up to 1T", + ), + (&with("retention_interval = \"3600\"\n"), "isn't a duration"), + (&with("retention_interval = 60\n"), "invalid type: integer"), + // Gone with protocol 7: no upload waits for its message. + ( + &with("upload_timeout = \"1h\"\n"), + "unknown field `upload_timeout`", + ), + ( + &with("retention_interval = \"0s\"\n"), + "'0s' isn't a duration", + ), + // [retention] + ( + &with("[retention]\nlogs = \"30\"\n"), + "logs = \"30\" isn't an age", + ), + (&with("[retention]\nlogs = 30\n"), "isn't an age"), + ( + &with("[retention]\n\"a b\" = \"1d\"\n"), + "'a b' isn't a topic name or a pattern", + ), + ( + &with("[retention]\nlogs = \"1d\"\nLOGS = \"2d\"\n"), + "'LOGS' is given twice", + ), + ( + &with("[retention]\nsensors.kitchen = \"1d\"\n"), + "quote names with dots", + ), + // [replication] + ( + &with("[replication]\npush_to = [\"10.0.0.2\"]\n"), + "isn't a host and a port", + ), + ( + &with("[replication]\npush_to = [\"a:1\", \"a:1\"]\n"), + "'a:1' is given twice", + ), + ( + &with("[replication]\naccept_from = [\"10.0.0.2:7000\"]\n"), + "without a port", + ), + ( + &with("[replication]\naccept_from = [\"a.lan\", \"A.lan\"]\n"), + "'A.lan' is given twice", + ), + ( + &with("[replication]\npeers = []\n"), + "unknown field `peers`", + ), + ( + &with("[replication]\nbatch_size = 0\n"), + "batch size must be 1 to 10000", + ), + ( + &with("[replication]\nbatch_size = 10001\n"), + "batch size must be 1 to 10000", + ), + ( + &with("[replication]\nsync_interval = \"soon\"\n"), + "'soon' isn't a duration", + ), + // [roles] + (&with("[roles.\"a b\"]\n"), "'a b' isn't a role name"), + ( + &with("[roles.peer]\n[roles.Peer]\n"), + "'peer' and 'Peer' are the same role", + ), + ( + &with("[roles.r]\npush_topics = [\"a b\"]\n"), + "'a b' isn't a name or a pattern", + ), + ( + &with("[roles.r]\naccept_nodes = [\"x\", \"X\"]\n"), + "'X' is given twice", + ), + (&with("[roles.r]\nquery = 1\n"), "invalid type: integer"), + (&with("[roles.site.reader]\n"), "unknown field `reader`"), + ]; + for (text, expected) in cases { + let error = refused(text); + assert!( + error.contains(expected), + "expected {expected:?} in:\n{error}" + ); + // Every refusal says where. + assert!(error.contains("line "), "no line in:\n{error}"); + } +} diff --git a/crates/bakashrot-pki/Cargo.toml b/crates/bakashrot-pki/Cargo.toml new file mode 100644 index 0000000..bf9118f --- /dev/null +++ b/crates/bakashrot-pki/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "bakashrot-pki" +description = "BakaShrot's certificates: issuing them and CRLs, reading identities, the TLS setup of servers and clients." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +authors.workspace = true +repository.workspace = true +publish.workspace = true + +[dependencies] +bakashrot-proto = { path = "../bakashrot-proto" } +# Issuing certificates and CRLs, P-384 keys through aws-lc. +rcgen = { version = "0.14.10", default-features = false, features = ["x509-parser", "pem", "aws_lc_rs"] } +# TLS 1.3 only, through aws-lc (the one with ML-KEM). +rustls = { version = "0.23.46", default-features = false, features = ["aws_lc_rs", "std"] } +time = "0.3.55" +# Reading certificates and CRLs, a CRL's signature checked through aws-lc. +x509-parser = { version = "0.18.1", features = ["verify-aws"] } +# The identity extension's DER (rcgen's own DER library). +yasna = "0.6.0" + +[lints] +workspace = true diff --git a/crates/bakashrot-pki/src/ca.rs b/crates/bakashrot-pki/src/ca.rs new file mode 100644 index 0000000..6460f14 --- /dev/null +++ b/crates/bakashrot-pki/src/ca.rs @@ -0,0 +1,238 @@ +//! A CA: issuing client and server certificates, and CRLs. +//! +//! Every key is ECDSA P-384, every signature SHA-384. A server certificate +//! is for servers and clients both (servers are their peers' clients), and +//! has the DNS name [`SERVER_NAME`] its clients ask for. + +use crate::{Error, IDENTITY_OID, Identity, Result, SERVER_NAME, parse_certificate, pem_der}; +use rcgen::{ + BasicConstraints, CertificateParams, CertificateRevocationListParams, CustomExtension, + DistinguishedName, DnType, ExtendedKeyUsagePurpose, IsCa, Issuer, KeyIdMethod, KeyPair, + KeyUsagePurpose, PKCS_ECDSA_P384_SHA384, PublicKeyData, RevokedCertParams, SanType, + SerialNumber, +}; +use time::{Duration, OffsetDateTime}; +use x509_parser::x509::X509Name; + +/// What a certificate is for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Usage { + /// A client's: it connects to servers. + Client, + /// A server's: clients and peers connect to it, and it connects to its + /// peers. + Server, +} + +/// A certificate and its private key, PEM. +#[derive(Debug, Clone)] +pub struct Issued { + /// The certificate: public, goes wherever it's needed. + pub certificate: String, + /// Its private key: stays with its owner. + pub key: String, +} + +/// A CA, loaded from its certificate and its key. +pub struct Ca { + certificate: Vec, + issuer: Issuer<'static, KeyPair>, +} + +fn rcgen_error(what: &str) -> impl Fn(rcgen::Error) -> Error + '_ { + move |error| Error::new(format!("{what}: {error}")) +} + +fn new_key() -> Result { + KeyPair::generate_for(&PKCS_ECDSA_P384_SHA384).map_err(rcgen_error("making a key")) +} + +/// Parameters valid from now on, for `days`, with `name` as the CN. +fn params(name: &str, days: u32) -> CertificateParams { + let mut params = CertificateParams::default(); + let mut subject = DistinguishedName::new(); + subject.push(DnType::CommonName, name); + params.distinguished_name = subject; + let now = OffsetDateTime::now_utc(); + params.not_before = now; + params.not_after = now + Duration::days(days.into()); + params +} + +impl Ca { + /// Makes a new CA named `name` (its CN), valid `days`: its certificate + /// and its key. Keep the key off the servers: whoever has it can make + /// any identity. + pub fn create(name: &str, days: u32) -> Result { + if name.trim().is_empty() { + return Err(Error::new("a CA needs a name")); + } + let key = new_key()?; + let mut params = params(name, days); + params.is_ca = IsCa::Ca(BasicConstraints::Constrained(0)); + params.key_usages = vec![ + KeyUsagePurpose::KeyCertSign, + KeyUsagePurpose::CrlSign, + KeyUsagePurpose::DigitalSignature, + ]; + let certificate = params + .self_signed(&key) + .map_err(rcgen_error("making the CA"))?; + Ok(Issued { + certificate: certificate.pem(), + key: key.serialize_pem(), + }) + } + + /// Loads a CA from its certificate and its key (PEM). Fails if the + /// certificate isn't a CA's, or the key isn't its. + pub fn load(certificate: &str, key: &str) -> Result { + let key = KeyPair::from_pem(key).map_err(rcgen_error("the CA's key"))?; + let der = pem_der(certificate, "CERTIFICATE")?; + { + let parsed = parse_certificate(&der)?; + if !parsed.is_ca() { + return Err(Error::new("the certificate isn't a CA's")); + } + if parsed.public_key().raw != key.subject_public_key_info() { + return Err(Error::new("the key isn't the CA certificate's")); + } + } + let issuer = Issuer::from_ca_cert_pem(certificate, key) + .map_err(rcgen_error("the CA's certificate"))?; + Ok(Ca { + certificate: der, + issuer, + }) + } + + /// Issues a certificate for `identity`, valid `days`: its certificate and + /// a new key. + pub fn issue(&self, identity: &Identity, usage: Usage, days: u32) -> Result { + let key = new_key()?; + let mut params = params(&identity.name, days); + params.key_usages = vec![KeyUsagePurpose::DigitalSignature]; + params.use_authority_key_identifier_extension = true; + params.custom_extensions = vec![CustomExtension::from_oid_content( + IDENTITY_OID, + identity.to_der(), + )]; + match usage { + Usage::Client => { + params.extended_key_usages = vec![ExtendedKeyUsagePurpose::ClientAuth]; + } + Usage::Server => { + params.extended_key_usages = vec![ + ExtendedKeyUsagePurpose::ServerAuth, + ExtendedKeyUsagePurpose::ClientAuth, + ]; + let name = SERVER_NAME + .try_into() + .map_err(rcgen_error("the server name"))?; + params.subject_alt_names = vec![SanType::DnsName(name)]; + } + } + let certificate = params + .signed_by(&key, &self.issuer) + .map_err(rcgen_error("issuing the certificate"))?; + Ok(Issued { + certificate: certificate.pem(), + key: key.serialize_pem(), + }) + } + + /// Whether this CA issued `certificate` (PEM): its signature checks out + /// with the CA's key. + pub fn issued(&self, certificate: &str) -> Result { + let ca = parse_certificate(&self.certificate)?; + let der = pem_der(certificate, "CERTIFICATE")?; + let certificate = parse_certificate(&der)?; + Ok(certificate.verify_signature(Some(ca.public_key())).is_ok()) + } + + /// A CRL revoking the certificates of these serial numbers (as + /// [`Summary::serial`] gives them), PEM. It says to expect the next one + /// within `days`; servers don't hold it against an older one. + pub fn revocation_list(&self, serials: &[Vec], days: u32) -> Result { + let now = OffsetDateTime::now_utc(); + let params = CertificateRevocationListParams { + this_update: now, + next_update: now + Duration::days(days.max(1).into()), + crl_number: SerialNumber::from(now.unix_timestamp().max(1) as u64), + issuing_distribution_point: None, + revoked_certs: serials + .iter() + .map(|serial| RevokedCertParams { + serial_number: SerialNumber::from_slice(serial), + revocation_time: now, + reason_code: None, + invalidity_date: None, + }) + .collect(), + key_identifier_method: KeyIdMethod::Sha256, + }; + let list = params + .signed_by(&self.issuer) + .map_err(rcgen_error("making the CRL"))?; + list.pem().map_err(rcgen_error("writing the CRL")) + } +} + +/// What a certificate says, for people (and the tool). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Summary { + /// Its subject's CN. + pub subject: String, + /// Its issuer's CN. + pub issuer: String, + /// Its serial number, as it's written (what a CRL lists). + pub serial: Vec, + /// Valid from, as written in it. + pub not_before: String, + /// Valid until, as written in it. + pub not_after: String, + /// Whether it's a CA's. + pub is_ca: bool, + /// What it's for, if it's one of ours. + pub usage: Option, + /// Who it is, if it has an identity. + pub identity: Option, +} + +impl Summary { + /// The serial number in hex. + pub fn serial_hex(&self) -> String { + self.serial + .iter() + .map(|byte| format!("{byte:02x}")) + .collect() + } +} + +/// What a certificate (PEM) says. +pub fn summarize(certificate: &str) -> Result { + let der = pem_der(certificate, "CERTIFICATE")?; + let parsed = parse_certificate(&der)?; + let common_name = |name: &X509Name<'_>| { + name.iter_common_name() + .next() + .and_then(|cn| cn.as_str().ok()) + .unwrap_or("") + .to_owned() + }; + let usage = match parsed.extended_key_usage() { + Ok(Some(eku)) if eku.value.server_auth => Some(Usage::Server), + Ok(Some(eku)) if eku.value.client_auth => Some(Usage::Client), + _ => None, + }; + Ok(Summary { + subject: common_name(parsed.subject()), + issuer: common_name(parsed.issuer()), + serial: parsed.raw_serial().to_vec(), + not_before: parsed.validity().not_before.to_string(), + not_after: parsed.validity().not_after.to_string(), + is_ca: parsed.is_ca(), + usage, + identity: Identity::from_certificate(&der).ok(), + }) +} diff --git a/crates/bakashrot-pki/src/identity.rs b/crates/bakashrot-pki/src/identity.rs new file mode 100644 index 0000000..b807aec --- /dev/null +++ b/crates/bakashrot-pki/src/identity.rs @@ -0,0 +1,147 @@ +//! The identity extension: who a certificate is. +//! +//! ```text +//! BakaShrotIdentity ::= SEQUENCE { +//! version INTEGER, -- 1 +//! name UTF8String, -- the node: "kitchen" +//! roles SEQUENCE OF UTF8String -- free: "sensor", "peer"... +//! } +//! ``` +//! +//! Non-critical (rustls refuses critical extensions it doesn't know), read +//! by BakaShrot only. Names and roles follow the name rules +//! (`bakashrot_proto::names`). + +use crate::{Error, IDENTITY_OID, Result, parse_certificate}; +use bakashrot_proto::names::is_valid_name; +use x509_parser::oid_registry::Oid; + +/// The version written, the only one read. +const VERSION: u32 = 1; + +/// The most roles a certificate may have. +pub const MAX_ROLES: usize = 64; + +/// Who a certificate is: a node, and its roles (their meaning is the +/// server's config's). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Identity { + /// The node's name. + pub name: String, + /// Its roles, in order. + pub roles: Vec, +} + +impl Identity { + /// An identity, checked: a name, roles that are names too. + pub fn new(name: &str, roles: &[&str]) -> Result { + let identity = Identity { + name: name.to_owned(), + roles: roles.iter().map(|role| (*role).to_owned()).collect(), + }; + identity.check()?; + Ok(identity) + } + + /// Whether it has `role` (roles compare without case, like names). + pub fn has_role(&self, role: &str) -> bool { + self.roles.iter().any(|own| own.eq_ignore_ascii_case(role)) + } + + fn check(&self) -> Result<()> { + if !is_valid_name(&self.name) { + return Err(Error::new(format!("'{}' isn't a valid name", self.name))); + } + if self.roles.len() > MAX_ROLES { + return Err(Error::new(format!("more than {MAX_ROLES} roles"))); + } + if let Some(role) = self.roles.iter().find(|role| !is_valid_name(role)) { + return Err(Error::new(format!("'{role}' isn't a valid role"))); + } + Ok(()) + } + + /// The extension's value, DER. + pub(crate) fn to_der(&self) -> Vec { + yasna::construct_der(|writer| { + writer.write_sequence(|writer| { + writer.next().write_u32(VERSION); + writer.next().write_utf8_string(&self.name); + writer.next().write_sequence_of(|writer| { + for role in &self.roles { + writer.next().write_utf8_string(role); + } + }); + }); + }) + } + + /// Reads the extension's value, DER. + pub(crate) fn from_der(der: &[u8]) -> Result { + let (version, name, roles) = yasna::parse_der(der, |reader| { + reader.read_sequence(|reader| { + let version = reader.next().read_u32()?; + let name = reader.next().read_utf8string()?; + let roles = reader + .next() + .collect_sequence_of(|reader| reader.read_utf8string())?; + Ok((version, name, roles)) + }) + }) + .map_err(|error| Error::new(format!("the identity extension isn't readable: {error}")))?; + if version != VERSION { + return Err(Error::new(format!( + "identity version {version}, this one reads {VERSION}" + ))); + } + let identity = Identity { name, roles }; + identity.check()?; + Ok(identity) + } + + /// The identity of a certificate (DER), the one the TLS connection + /// presented once verified. + pub fn from_certificate(der: &[u8]) -> Result { + let certificate = parse_certificate(der)?; + let oid = Oid::from(IDENTITY_OID).map_err(|_| Error::new("the identity OID is invalid"))?; + let extension = certificate + .get_extension_unique(&oid) + .map_err(|error| Error::new(format!("the identity extension: {error}")))? + .ok_or_else(|| Error::new("the certificate has no BakaShrot identity"))?; + Identity::from_der(extension.value) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn round_trip() { + let identity = Identity::new("kitchen", &["sensor", "Reader"]).unwrap(); + assert_eq!(Identity::from_der(&identity.to_der()), Ok(identity.clone())); + assert!(identity.has_role("reader")); + assert!(!identity.has_role("peer")); + let alone = Identity::new("kitchen", &[]).unwrap(); + assert_eq!(Identity::from_der(&alone.to_der()), Ok(alone)); + } + + #[test] + fn refused() { + assert!(Identity::new("12", &[]).is_err()); + assert!(Identity::new("a b", &[]).is_err()); + assert!(Identity::new("kitchen", &["bad role"]).is_err()); + assert!(Identity::new("kitchen", &["r"; MAX_ROLES + 1]).is_err()); + assert!(Identity::from_der(b"garbage").is_err()); + + // Another version. + let other = yasna::construct_der(|writer| { + writer.write_sequence(|writer| { + writer.next().write_u32(2); + writer.next().write_utf8_string("kitchen"); + writer.next().write_sequence_of(|_| {}); + }); + }); + assert!(Identity::from_der(&other).is_err()); + } +} diff --git a/crates/bakashrot-pki/src/lib.rs b/crates/bakashrot-pki/src/lib.rs new file mode 100644 index 0000000..e7ece82 --- /dev/null +++ b/crates/bakashrot-pki/src/lib.rs @@ -0,0 +1,87 @@ +//! BakaShrot's certificates, and the TLS they're used with. +//! +//! - [`Identity`]: who a certificate is (a node's name, its roles), in an +//! extension of BakaShrot's own. +//! - [`Ca`]: a CA issuing client and server certificates, and CRLs. +//! - [`Revocations`]: the certificates a CRL revokes, for servers to check +//! (and reload when the CRL file changes). +//! - [`tls`]: the server's and the client's rustls configurations, at the +//! strongest settings rustls has. +//! +//! Everything is PEM text in and out, as files hold it. The profile and the +//! reasons behind it: `docs/certificates.md`. + +mod ca; +mod identity; +mod revocation; +pub mod tls; + +pub use ca::{Ca, Issued, Summary, Usage, summarize}; +pub use identity::Identity; +pub use revocation::{Revocations, SharedRevocations, serial}; + +use std::fmt; +use x509_parser::certificate::X509Certificate; + +/// The identity extension's OID. +/// +/// **A placeholder** ([`IDENTITY_OID_IS_PLACEHOLDER`]): under PEN 32473, +/// which RFC 5612 reserves for documentation. Replace it with one under +/// NibblePoker's own PEN once IANA gave it (`docs/oid.md`), before +/// issuing certificates for real: certificates made with this one stop +/// being read once it changes. +pub const IDENTITY_OID: &[u64] = &[1, 3, 6, 1, 4, 1, 32473, 1, 1]; + +/// Whether [`IDENTITY_OID`] is still the placeholder: `bakashrot-cert` +/// warns when it makes a CA or a certificate then. Set it to `false` with +/// the real OID. +pub const IDENTITY_OID_IS_PLACEHOLDER: bool = true; + +/// The DNS name every server certificate has, and every client asks for: +/// a label, not a host. Servers are known by their certificate, wherever +/// they are. +pub const SERVER_NAME: &str = "bakashrot-server"; + +/// Default lifetimes, in days. +pub const CA_DAYS: u32 = 3650; +/// See [`CA_DAYS`]. +pub const CERTIFICATE_DAYS: u32 = 365; + +/// What went wrong, in words: everything here fails on a file or a value +/// that isn't right, which people fix. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Error(String); + +impl Error { + pub(crate) fn new(what: impl fmt::Display) -> Self { + Error(what.to_string()) + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +impl std::error::Error for Error {} + +/// A result of this crate. +pub type Result = std::result::Result; + +/// Reads one PEM block of `label`, its DER. +fn pem_der(text: &str, label: &str) -> Result> { + let (_, pem) = x509_parser::pem::parse_x509_pem(text.as_bytes()) + .map_err(|error| Error::new(format!("not PEM: {error}")))?; + if pem.label != label { + return Err(Error::new(format!("a {}, not a {label}", pem.label))); + } + Ok(pem.contents) +} + +/// Reads a certificate (DER). +fn parse_certificate(der: &[u8]) -> Result> { + let (_, certificate) = x509_parser::parse_x509_certificate(der) + .map_err(|error| Error::new(format!("not a certificate: {error}")))?; + Ok(certificate) +} diff --git a/crates/bakashrot-pki/src/revocation.rs b/crates/bakashrot-pki/src/revocation.rs new file mode 100644 index 0000000..bdaaea9 --- /dev/null +++ b/crates/bakashrot-pki/src/revocation.rs @@ -0,0 +1,91 @@ +//! The certificates a CRL revokes. +//! +//! A server loads its CRL file into [`Revocations`], shares it with its TLS +//! setup ([`SharedRevocations`]), and replaces what's inside when the file +//! changes: new connections are checked against the new list at once, and +//! the server checks the open ones itself ([`Revocations::revokes_serial`], +//! their serials read once with [`serial`]). +//! +//! A CRL is only taken if it's the CA's: issued by it, its signature +//! checked. Its "next update" isn't held against it: CRLs are pushed by +//! hand, an old one still revokes what it lists. + +use crate::{Error, Result, parse_certificate, pem_der}; +use std::collections::HashSet; +use std::sync::{Arc, RwLock}; + +/// The serial numbers of the certificates a CRL revokes. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Revocations { + serials: HashSet>, +} + +/// Revocations shared between a server's TLS setup and whatever reloads +/// them. +pub type SharedRevocations = Arc>; + +impl Revocations { + /// Nothing revoked: no CRL file. + pub fn none() -> Revocations { + Revocations::default() + } + + /// Reads a CRL (PEM), which must be the CA's (its certificate, PEM). + pub fn load(crl: &str, ca_certificate: &str) -> Result { + let crl_der = pem_der(crl, "X509 CRL")?; + let ca_der = pem_der(ca_certificate, "CERTIFICATE")?; + let (_, list) = x509_parser::parse_x509_crl(&crl_der) + .map_err(|error| Error::new(format!("not a CRL: {error}")))?; + let ca = parse_certificate(&ca_der) + .map_err(|error| Error::new(format!("the CA's certificate: {error}")))?; + if list.issuer().as_raw() != ca.subject().as_raw() { + return Err(Error::new("the CRL is another CA's")); + } + list.verify_signature(ca.public_key()) + .map_err(|_| Error::new("the CRL's signature isn't the CA's"))?; + Ok(Revocations { + serials: list + .iter_revoked_certificates() + .map(|revoked| revoked.raw_serial().to_vec()) + .collect(), + }) + } + + /// Whether it revokes this certificate (DER). One that can't be read is + /// taken as revoked. + pub fn revokes(&self, certificate: &[u8]) -> bool { + serial(certificate).map_or(true, |serial| self.revokes_serial(&serial)) + } + + /// Whether it revokes the certificate with this serial number + /// ([`serial`]): checking an open connection without reading its + /// certificate again. + pub fn revokes_serial(&self, serial: &[u8]) -> bool { + self.serials.contains(serial) + } + + /// The serial numbers it revokes. + pub fn serials(&self) -> impl Iterator { + self.serials.iter().map(Vec::as_slice) + } + + /// How many it revokes. + pub fn len(&self) -> usize { + self.serials.len() + } + + /// Whether it revokes none. + pub fn is_empty(&self) -> bool { + self.serials.is_empty() + } + + /// Wraps it for sharing. + pub fn shared(self) -> SharedRevocations { + Arc::new(RwLock::new(self)) + } +} + +/// A certificate's (DER) serial number, as CRLs list them. +pub fn serial(certificate: &[u8]) -> Result> { + Ok(parse_certificate(certificate)?.raw_serial().to_vec()) +} diff --git a/crates/bakashrot-pki/src/tls.rs b/crates/bakashrot-pki/src/tls.rs new file mode 100644 index 0000000..7ad19bc --- /dev/null +++ b/crates/bakashrot-pki/src/tls.rs @@ -0,0 +1,254 @@ +//! The TLS setup of servers and clients: TLS 1.3 only, AES-256-GCM-SHA384 +//! only, the X25519MLKEM768 key exchange only, ALPN `bakashrot`, and a +//! certificate from the CA on both ends. +//! +//! Each end checks the other with rustls' own verifier (a server's +//! certificate for the name they all have, [`SERVER_NAME`]: no host names +//! or IPs), then that it isn't revoked and has an identity. Both ends take +//! [`SharedRevocations`]: a server dialing its peer is that peer's client, +//! so servers block each other the same way. Once connected, either end +//! reads the other's [`Identity`] with [`peer_identity`]. + +use crate::{Error, Identity, Result, SERVER_NAME, SharedRevocations}; +use bakashrot_proto::limits::ALPN; +use rustls::client::WebPkiServerVerifier; +use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier}; +use rustls::crypto::{CryptoProvider, aws_lc_rs}; +use rustls::pki_types::pem::PemObject; +use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName, UnixTime}; +use rustls::server::WebPkiClientVerifier; +use rustls::server::danger::{ClientCertVerified, ClientCertVerifier}; +use rustls::{ + CertificateError, ClientConfig, DigitallySignedStruct, DistinguishedName, RootCertStore, + ServerConfig, SignatureScheme, +}; +use std::sync::Arc; + +/// aws-lc, with only the strongest cipher suite and key exchange. +pub fn provider() -> Arc { + Arc::new(CryptoProvider { + cipher_suites: vec![aws_lc_rs::cipher_suite::TLS13_AES_256_GCM_SHA384], + kx_groups: vec![aws_lc_rs::kx_group::X25519MLKEM768], + ..aws_lc_rs::default_provider() + }) +} + +/// The name a client asks for: [`SERVER_NAME`]. +pub fn server_name() -> ServerName<'static> { + ServerName::try_from(SERVER_NAME).expect("SERVER_NAME is a DNS name") +} + +/// A server's configuration: its certificate and key (PEM), the CA it takes +/// clients from (PEM), and the revocations it checks them against. +pub fn server_config( + ca: &str, + certificate: &str, + key: &str, + revocations: SharedRevocations, +) -> Result> { + let provider = provider(); + let webpki = WebPkiClientVerifier::builder_with_provider(roots(ca)?, provider.clone()) + .build() + .map_err(|error| Error::new(format!("the CA: {error}")))?; + let mut config = ServerConfig::builder_with_provider(provider) + .with_protocol_versions(&[&rustls::version::TLS13]) + .map_err(tls_error)? + .with_client_cert_verifier(Arc::new(ClientCheck { + webpki, + revocations, + })) + .with_single_cert(chain(certificate)?, private_key(key)?) + .map_err(tls_error)?; + config.alpn_protocols = vec![ALPN.to_vec()]; + Ok(Arc::new(config)) +} + +/// A client's configuration: its certificate and key (PEM), the CA it takes +/// servers from (PEM), and the revocations it checks them against +/// (`Revocations::none()` without a CRL). Connect with [`server_name`]. +pub fn client_config( + ca: &str, + certificate: &str, + key: &str, + revocations: SharedRevocations, +) -> Result> { + let provider = provider(); + let webpki = WebPkiServerVerifier::builder_with_provider(roots(ca)?, provider.clone()) + .build() + .map_err(|error| Error::new(format!("the CA: {error}")))?; + let mut config = ClientConfig::builder_with_provider(provider) + .with_protocol_versions(&[&rustls::version::TLS13]) + .map_err(tls_error)? + .dangerous() + .with_custom_certificate_verifier(Arc::new(ServerCheck { + webpki, + revocations, + })) + .with_client_auth_cert(chain(certificate)?, private_key(key)?) + .map_err(tls_error)?; + config.alpn_protocols = vec![ALPN.to_vec()]; + Ok(Arc::new(config)) +} + +/// The identity of the other end, from its certificates once connected +/// (`peer_certificates()` of a rustls connection). +pub fn peer_identity(certificates: Option<&[CertificateDer<'_>]>) -> Result { + let certificate = certificates + .and_then(<[_]>::first) + .ok_or_else(|| Error::new("no certificate from the other end"))?; + Identity::from_certificate(certificate) +} + +fn tls_error(error: rustls::Error) -> Error { + Error::new(format!("TLS: {error}")) +} + +fn roots(ca: &str) -> Result> { + let mut roots = RootCertStore::empty(); + for certificate in CertificateDer::pem_slice_iter(ca.as_bytes()) { + let certificate = certificate.map_err(|error| Error::new(format!("the CA: {error}")))?; + roots.add(certificate).map_err(tls_error)?; + } + if roots.is_empty() { + return Err(Error::new("the CA: no certificate")); + } + Ok(Arc::new(roots)) +} + +fn chain(certificate: &str) -> Result>> { + let chain = CertificateDer::pem_slice_iter(certificate.as_bytes()) + .collect::, _>>() + .map_err(|error| Error::new(format!("the certificate: {error}")))?; + if chain.is_empty() { + return Err(Error::new("the certificate: none in it")); + } + Ok(chain) +} + +fn private_key(key: &str) -> Result> { + PrivateKeyDer::from_pem_slice(key.as_bytes()) + .map_err(|error| Error::new(format!("the key: {error}"))) +} + +/// What both ends check once rustls' verifier took the other's certificate: +/// not revoked, an identity. +fn ours( + certificate: &CertificateDer<'_>, + revocations: &SharedRevocations, +) -> std::result::Result<(), rustls::Error> { + // A poisoned lock: refuse rather than guess. + let revoked = revocations + .read() + .map_or(true, |revocations| revocations.revokes(certificate)); + if revoked { + return Err(rustls::Error::InvalidCertificate(CertificateError::Revoked)); + } + if Identity::from_certificate(certificate).is_err() { + return Err(rustls::Error::InvalidCertificate( + CertificateError::ApplicationVerificationFailure, + )); + } + Ok(()) +} + +/// The server's check of clients: rustls', then [`ours`]. +#[derive(Debug)] +struct ClientCheck { + webpki: Arc, + revocations: SharedRevocations, +} + +impl ClientCertVerifier for ClientCheck { + fn root_hint_subjects(&self) -> &[DistinguishedName] { + self.webpki.root_hint_subjects() + } + + fn verify_client_cert( + &self, + end_entity: &CertificateDer<'_>, + intermediates: &[CertificateDer<'_>], + now: UnixTime, + ) -> std::result::Result { + let verified = self + .webpki + .verify_client_cert(end_entity, intermediates, now)?; + ours(end_entity, &self.revocations)?; + Ok(verified) + } + + fn verify_tls12_signature( + &self, + message: &[u8], + certificate: &CertificateDer<'_>, + signature: &DigitallySignedStruct, + ) -> std::result::Result { + self.webpki + .verify_tls12_signature(message, certificate, signature) + } + + fn verify_tls13_signature( + &self, + message: &[u8], + certificate: &CertificateDer<'_>, + signature: &DigitallySignedStruct, + ) -> std::result::Result { + self.webpki + .verify_tls13_signature(message, certificate, signature) + } + + fn supported_verify_schemes(&self) -> Vec { + self.webpki.supported_verify_schemes() + } +} + +/// The client's check of servers: rustls', then [`ours`]. +#[derive(Debug)] +struct ServerCheck { + webpki: Arc, + revocations: SharedRevocations, +} + +impl ServerCertVerifier for ServerCheck { + fn verify_server_cert( + &self, + end_entity: &CertificateDer<'_>, + intermediates: &[CertificateDer<'_>], + server_name: &ServerName<'_>, + ocsp_response: &[u8], + now: UnixTime, + ) -> std::result::Result { + let verified = self.webpki.verify_server_cert( + end_entity, + intermediates, + server_name, + ocsp_response, + now, + )?; + ours(end_entity, &self.revocations)?; + Ok(verified) + } + + fn verify_tls12_signature( + &self, + message: &[u8], + certificate: &CertificateDer<'_>, + signature: &DigitallySignedStruct, + ) -> std::result::Result { + self.webpki + .verify_tls12_signature(message, certificate, signature) + } + + fn verify_tls13_signature( + &self, + message: &[u8], + certificate: &CertificateDer<'_>, + signature: &DigitallySignedStruct, + ) -> std::result::Result { + self.webpki + .verify_tls13_signature(message, certificate, signature) + } + + fn supported_verify_schemes(&self) -> Vec { + self.webpki.supported_verify_schemes() + } +} diff --git a/crates/bakashrot-pki/tests/ca.rs b/crates/bakashrot-pki/tests/ca.rs new file mode 100644 index 0000000..e9f5815 --- /dev/null +++ b/crates/bakashrot-pki/tests/ca.rs @@ -0,0 +1,235 @@ +//! Issuing: what certificates and CRLs hold, and OpenSSL agreeing. + +use bakashrot_pki::{Ca, Identity, Revocations, Usage, summarize}; +use std::path::PathBuf; +use std::process::Command; + +fn ca() -> (Ca, String) { + let issued = Ca::create("Test CA", 30).unwrap(); + ( + Ca::load(&issued.certificate, &issued.key).unwrap(), + issued.certificate, + ) +} + +#[test] +fn certificates_say_who_and_what_for() { + let (ca, ca_certificate) = ca(); + let identity = Identity::new("kitchen", &["sensor", "reader"]).unwrap(); + let client = ca.issue(&identity, Usage::Client, 365).unwrap(); + let server = ca + .issue( + &Identity::new("server-1", &["peer"]).unwrap(), + Usage::Server, + 365, + ) + .unwrap(); + + let summary = summarize(&client.certificate).unwrap(); + assert_eq!(summary.identity, Some(identity)); + assert_eq!(summary.subject, "kitchen"); + assert_eq!(summary.issuer, "Test CA"); + assert_eq!(summary.usage, Some(Usage::Client)); + assert!(!summary.is_ca); + assert!(!summary.serial.is_empty()); + + assert_eq!( + summarize(&server.certificate).unwrap().usage, + Some(Usage::Server) + ); + let ca_summary = summarize(&ca_certificate).unwrap(); + assert!(ca_summary.is_ca); + assert_eq!(ca_summary.identity, None); + + assert!(ca.issued(&client.certificate).unwrap()); + let (other, _) = self::ca(); + assert!(!other.issued(&client.certificate).unwrap()); +} + +#[test] +fn a_ca_needs_its_own_key() { + let first = Ca::create("First", 30).unwrap(); + let second = Ca::create("Second", 30).unwrap(); + assert!(Ca::load(&first.certificate, &second.key).is_err()); + assert!(Ca::load(&first.certificate, &first.key).is_ok()); + + let ca = Ca::load(&first.certificate, &first.key).unwrap(); + let client = ca + .issue(&Identity::new("kitchen", &[]).unwrap(), Usage::Client, 30) + .unwrap(); + assert!( + Ca::load(&client.certificate, &client.key).is_err(), + "not a CA" + ); + assert!(Ca::create(" ", 30).is_err()); +} + +#[test] +fn crls_revoke_what_they_list() { + let (ca, ca_certificate) = ca(); + let certificates: Vec = (0..8) + .map(|n| { + let identity = Identity::new(&format!("node-{n}"), &[]).unwrap(); + ca.issue(&identity, Usage::Client, 30).unwrap().certificate + }) + .collect(); + let serials: Vec> = certificates[..4] + .iter() + .map(|certificate| summarize(certificate).unwrap().serial) + .collect(); + let crl = ca.revocation_list(&serials, 30).unwrap(); + let revocations = Revocations::load(&crl, &ca_certificate).unwrap(); + assert_eq!(revocations.len(), 4); + for (n, certificate) in certificates.iter().enumerate() { + assert_eq!(revocations.revokes(&der(certificate)), n < 4, "node-{n}"); + } + assert!(Revocations::none().is_empty()); + assert!(!Revocations::none().revokes(&der(&certificates[0]))); + + let empty = ca.revocation_list(&[], 30).unwrap(); + assert!( + Revocations::load(&empty, &ca_certificate) + .unwrap() + .is_empty() + ); +} + +#[test] +fn only_the_cas_crls_are_taken() { + let (ca, ca_certificate) = ca(); + let (other, other_certificate) = self::ca(); + let crl = other.revocation_list(&[vec![1]], 30).unwrap(); + assert!( + Revocations::load(&crl, &ca_certificate).is_err(), + "another CA's" + ); + assert!(Revocations::load(&crl, &other_certificate).is_ok()); + + // Tampered: a character of its Base64 changed. + let crl = ca.revocation_list(&[vec![1]], 30).unwrap(); + let at = crl.len() / 2; + let swapped = if &crl[at..=at] == "A" { "B" } else { "A" }; + let tampered = format!("{}{}{}", &crl[..at], swapped, &crl[at + 1..]); + assert!(Revocations::load(&tampered, &ca_certificate).is_err()); + + assert!(Revocations::load("not a CRL", &ca_certificate).is_err()); + assert!( + Revocations::load(&ca_certificate, &ca_certificate).is_err(), + "a certificate" + ); +} + +fn der(certificate: &str) -> Vec { + use rustls::pki_types::{CertificateDer, pem::PemObject}; + CertificateDer::from_pem_slice(certificate.as_bytes()) + .unwrap() + .to_vec() +} + +/// OpenSSL, from the PATH or Git for Windows'. +fn openssl() -> Option { + let candidates = [ + PathBuf::from("openssl"), + PathBuf::from(r"C:\Program Files\Git\ucrt64\bin\openssl.exe"), + PathBuf::from(r"C:\Program Files\Git\mingw64\bin\openssl.exe"), + PathBuf::from(r"C:\Program Files\Git\usr\bin\openssl.exe"), + ]; + candidates.into_iter().find(|candidate| { + Command::new(candidate) + .arg("version") + .output() + .is_ok_and(|output| output.status.success()) + }) +} + +#[test] +fn openssl_agrees() { + let Some(openssl) = openssl() else { + eprintln!("SKIP: no openssl"); + return; + }; + let folder = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("pki-openssl"); + let _ = std::fs::remove_dir_all(&folder); + std::fs::create_dir_all(&folder).unwrap(); + + let issued = Ca::create("Test CA", 30).unwrap(); + let ca = Ca::load(&issued.certificate, &issued.key).unwrap(); + let client = ca + .issue( + &Identity::new("kitchen", &["sensor"]).unwrap(), + Usage::Client, + 30, + ) + .unwrap(); + let server = ca + .issue(&Identity::new("server-1", &[]).unwrap(), Usage::Server, 30) + .unwrap(); + let serial = summarize(&client.certificate).unwrap().serial; + let files = [ + ("ca.crt", issued.certificate.clone()), + ("client.crt", client.certificate), + ("server.crt", server.certificate), + ("ca.crl", ca.revocation_list(&[serial], 30).unwrap()), + ]; + for (name, text) in &files { + std::fs::write(folder.join(name), text).unwrap(); + } + let run = |args: &[&str]| { + let output = Command::new(&openssl) + .args(args) + .current_dir(&folder) + .output() + .unwrap(); + let text = format!( + "{}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + (output.status.success(), text) + }; + + let (ok, text) = run(&[ + "verify", + "-CAfile", + "ca.crt", + "-purpose", + "sslclient", + "client.crt", + ]); + assert!(ok, "{text}"); + let (ok, text) = run(&[ + "verify", + "-CAfile", + "ca.crt", + "-purpose", + "sslserver", + "server.crt", + ]); + assert!(ok, "{text}"); + let (ok, _) = run(&[ + "verify", + "-CAfile", + "ca.crt", + "-purpose", + "sslserver", + "client.crt", + ]); + assert!(!ok, "a client's certificate isn't a server's"); + let (ok, text) = run(&["crl", "-in", "ca.crl", "-CAfile", "ca.crt", "-noout"]); + assert!(ok && text.contains("verify OK"), "{text}"); + let (ok, text) = run(&[ + "verify", + "-CAfile", + "ca.crt", + "-CRLfile", + "ca.crl", + "-crl_check", + "client.crt", + ]); + assert!(!ok && text.contains("revoked"), "{text}"); + let (ok, text) = run(&["x509", "-in", "server.crt", "-noout", "-text"]); + assert!( + ok && text.contains("NIST CURVE: P-384") && text.contains("DNS:bakashrot-server"), + "{text}" + ); +} diff --git a/crates/bakashrot-pki/tests/tls.rs b/crates/bakashrot-pki/tests/tls.rs new file mode 100644 index 0000000..7948ace --- /dev/null +++ b/crates/bakashrot-pki/tests/tls.rs @@ -0,0 +1,388 @@ +//! Handshakes in memory, no sockets: what's accepted and what's refused. + +use bakashrot_pki::tls::{self, peer_identity}; +use bakashrot_pki::{Ca, Identity, Issued, Revocations, SharedRevocations, Usage, summarize}; +use bakashrot_proto::limits::ALPN; +use rustls::{ClientConfig, ClientConnection, ConnectionCommon, ServerConfig, ServerConnection}; +use std::io::{Read, Write}; +use std::sync::Arc; + +struct Pki { + ca: Ca, + ca_certificate: String, + ca_key: String, +} + +impl Pki { + fn new(name: &str) -> Pki { + let issued = Ca::create(name, 30).unwrap(); + Pki { + ca: Ca::load(&issued.certificate, &issued.key).unwrap(), + ca_certificate: issued.certificate, + ca_key: issued.key, + } + } + + fn issue(&self, name: &str, roles: &[&str], usage: Usage) -> Issued { + self.ca + .issue(&Identity::new(name, roles).unwrap(), usage, 30) + .unwrap() + } + + fn server(&self, issued: &Issued, revocations: SharedRevocations) -> Arc { + tls::server_config( + &self.ca_certificate, + &issued.certificate, + &issued.key, + revocations, + ) + .unwrap() + } + + fn client(&self, issued: &Issued) -> Arc { + self.client_checking(issued, Revocations::none().shared()) + } + + fn client_checking( + &self, + issued: &Issued, + revocations: SharedRevocations, + ) -> Arc { + tls::client_config( + &self.ca_certificate, + &issued.certificate, + &issued.key, + revocations, + ) + .unwrap() + } + + /// Revocations listing these certificates. + fn revoking(&self, certificates: &[&Issued]) -> SharedRevocations { + let serials: Vec> = certificates + .iter() + .map(|issued| summarize(&issued.certificate).unwrap().serial) + .collect(); + let crl = self.ca.revocation_list(&serials, 30).unwrap(); + Revocations::load(&crl, &self.ca_certificate) + .unwrap() + .shared() + } +} + +fn transfer(from: &mut ConnectionCommon, to: &mut ConnectionCommon) { + while from.wants_write() { + let mut bytes = Vec::new(); + from.write_tls(&mut bytes).unwrap(); + let mut rest = &bytes[..]; + while !rest.is_empty() { + to.read_tls(&mut rest).unwrap(); + } + } +} + +/// A handshake, then a byte each way: the connections, or which end +/// refused and why. +fn connect( + client: Arc, + server: Arc, +) -> Result<(ClientConnection, ServerConnection), String> { + let mut client = ClientConnection::new(client, tls::server_name()).unwrap(); + let mut server = ServerConnection::new(server).unwrap(); + for _ in 0..10 { + transfer(&mut client, &mut server); + server + .process_new_packets() + .map_err(|e| format!("server: {e}"))?; + transfer(&mut server, &mut client); + client + .process_new_packets() + .map_err(|e| format!("client: {e}"))?; + if !client.is_handshaking() && !server.is_handshaking() { + break; + } + } + client.writer().write_all(b"c").unwrap(); + transfer(&mut client, &mut server); + server + .process_new_packets() + .map_err(|e| format!("server: {e}"))?; + server.writer().write_all(b"s").unwrap(); + transfer(&mut server, &mut client); + client + .process_new_packets() + .map_err(|e| format!("client: {e}"))?; + + let mut byte = [0]; + server + .reader() + .read_exact(&mut byte) + .map_err(|e| format!("server read: {e}"))?; + assert_eq!(&byte, b"c"); + client + .reader() + .read_exact(&mut byte) + .map_err(|e| format!("client read: {e}"))?; + assert_eq!(&byte, b"s"); + Ok((client, server)) +} + +#[test] +fn connected_at_the_strongest_settings() { + let pki = Pki::new("Test CA"); + let server = pki.issue("server-1", &["peer"], Usage::Server); + let client = pki.issue("kitchen", &["sensor"], Usage::Client); + let (client, server) = connect( + pki.client(&client), + pki.server(&server, Revocations::none().shared()), + ) + .unwrap(); + + assert_eq!( + client.protocol_version(), + Some(rustls::ProtocolVersion::TLSv1_3) + ); + assert_eq!( + client.negotiated_cipher_suite().unwrap().suite(), + rustls::CipherSuite::TLS13_AES_256_GCM_SHA384 + ); + assert_eq!( + client.negotiated_key_exchange_group().unwrap().name(), + rustls::NamedGroup::X25519MLKEM768 + ); + assert_eq!(client.alpn_protocol(), Some(ALPN)); + assert_eq!(server.alpn_protocol(), Some(ALPN)); + + // Each end knows who the other is. + let client_identity = peer_identity(server.peer_certificates()).unwrap(); + assert_eq!( + client_identity, + Identity::new("kitchen", &["sensor"]).unwrap() + ); + let server_identity = peer_identity(client.peer_certificates()).unwrap(); + assert_eq!(server_identity.name, "server-1"); + assert!(server_identity.has_role("peer")); +} + +#[test] +fn servers_connect_to_their_peers() { + let pki = Pki::new("Test CA"); + let first = pki.issue("server-1", &["peer"], Usage::Server); + let second = pki.issue("server-2", &["peer"], Usage::Server); + // A server's certificate is a client's too. + let (_, server) = connect( + pki.client(&first), + pki.server(&second, Revocations::none().shared()), + ) + .unwrap(); + assert_eq!( + peer_identity(server.peer_certificates()).unwrap().name, + "server-1" + ); +} + +#[test] +fn a_client_of_another_ca_is_refused() { + let pki = Pki::new("Test CA"); + let other = Pki::new("Other CA"); + let server = pki.server( + &pki.issue("server-1", &[], Usage::Server), + Revocations::none().shared(), + ); + let stranger = other.issue("kitchen", &[], Usage::Client); + let client = tls::client_config( + &pki.ca_certificate, + &stranger.certificate, + &stranger.key, + Revocations::none().shared(), + ) + .unwrap(); + let error = connect(client, server).unwrap_err(); + assert!(error.starts_with("server:"), "{error}"); +} + +#[test] +fn a_server_of_another_ca_is_refused() { + let pki = Pki::new("Test CA"); + let other = Pki::new("Other CA"); + let client = pki.client(&pki.issue("kitchen", &[], Usage::Client)); + let impostor = other.issue("server-1", &[], Usage::Server); + let server = tls::server_config( + &pki.ca_certificate, + &impostor.certificate, + &impostor.key, + Revocations::none().shared(), + ) + .unwrap(); + let error = connect(client, server).unwrap_err(); + assert!(error.starts_with("client:"), "{error}"); +} + +#[test] +fn a_clients_certificate_isnt_a_servers() { + let pki = Pki::new("Test CA"); + let client = pki.client(&pki.issue("kitchen", &[], Usage::Client)); + let posing = pki.issue("server-1", &[], Usage::Client); + let error = connect(client, pki.server(&posing, Revocations::none().shared())).unwrap_err(); + assert!(error.starts_with("client:"), "{error}"); +} + +#[test] +fn revoked_clients_are_refused_and_reloading_takes_effect() { + let pki = Pki::new("Test CA"); + let revocations = Revocations::none().shared(); + let server = pki.server( + &pki.issue("server-1", &[], Usage::Server), + revocations.clone(), + ); + let kitchen = pki.issue("kitchen", &[], Usage::Client); + let garage = pki.issue("garage", &[], Usage::Client); + assert!(connect(pki.client(&kitchen), server.clone()).is_ok()); + + // The CRL changes: the same server configuration refuses at once. + let serial = summarize(&kitchen.certificate).unwrap().serial; + let crl = pki.ca.revocation_list(&[serial], 30).unwrap(); + *revocations.write().unwrap() = Revocations::load(&crl, &pki.ca_certificate).unwrap(); + let error = connect(pki.client(&kitchen), server.clone()).unwrap_err(); + assert!( + error.starts_with("server:") && error.contains("Revoked"), + "{error}" + ); + assert!( + connect(pki.client(&garage), server.clone()).is_ok(), + "only kitchen" + ); + + *revocations.write().unwrap() = Revocations::none(); + assert!(connect(pki.client(&kitchen), server).is_ok()); +} + +#[test] +fn a_certificate_without_an_identity_is_refused() { + let pki = Pki::new("Test CA"); + let server = pki.server( + &pki.issue("server-1", &[], Usage::Server), + Revocations::none().shared(), + ); + + // Signed by the right CA, but not by Ca::issue: no identity extension. + let ca_key = rcgen::KeyPair::from_pem(&pki.ca_key).unwrap(); + let issuer = rcgen::Issuer::from_ca_cert_pem(&pki.ca_certificate, ca_key).unwrap(); + let key = rcgen::KeyPair::generate_for(&rcgen::PKCS_ECDSA_P384_SHA384).unwrap(); + let mut params = rcgen::CertificateParams::default(); + params.extended_key_usages = vec![rcgen::ExtendedKeyUsagePurpose::ClientAuth]; + let certificate = params.signed_by(&key, &issuer).unwrap().pem(); + + let client = tls::client_config( + &pki.ca_certificate, + &certificate, + &key.serialize_pem(), + Revocations::none().shared(), + ) + .unwrap(); + let error = connect(client, server).unwrap_err(); + assert!(error.starts_with("server:"), "{error}"); +} + +#[test] +fn another_protocol_is_refused() { + let pki = Pki::new("Test CA"); + let server = pki.server( + &pki.issue("server-1", &[], Usage::Server), + Revocations::none().shared(), + ); + let client = pki.issue("kitchen", &[], Usage::Client); + let mut config = (*pki.client(&client)).clone(); + config.alpn_protocols = vec![b"http/1.1".to_vec()]; + let error = connect(Arc::new(config), server).unwrap_err(); + assert!(error.starts_with("server:"), "{error}"); +} + +#[test] +fn bad_files_are_told() { + let pki = Pki::new("Test CA"); + let client = pki.issue("kitchen", &[], Usage::Client); + let none = || Revocations::none().shared(); + assert!(tls::client_config("", &client.certificate, &client.key, none()).is_err()); + assert!(tls::client_config(&pki.ca_certificate, "", &client.key, none()).is_err()); + assert!(tls::client_config(&pki.ca_certificate, &client.certificate, "", none()).is_err()); + assert!(peer_identity(None).is_err()); +} + +#[test] +fn clients_given_a_crl_refuse_revoked_servers() { + let pki = Pki::new("Test CA"); + let server = pki.issue("server-1", &[], Usage::Server); + let client = pki.issue("kitchen", &[], Usage::Client); + let config = pki.server(&server, Revocations::none().shared()); + assert!(connect(pki.client(&client), config.clone()).is_ok()); + let error = connect( + pki.client_checking(&client, pki.revoking(&[&server])), + config, + ) + .unwrap_err(); + assert!( + error.starts_with("client:") && error.contains("Revoked"), + "{error}" + ); +} + +#[test] +fn servers_block_each_other() { + let pki = Pki::new("Test CA"); + let first = pki.issue("server-1", &["peer"], Usage::Server); + let second = pki.issue("server-2", &["peer"], Usage::Server); + let crl = pki.revoking(&[&second]); + // server-1 has the CRL: it refuses server-2 both ways. + let error = connect(pki.client(&second), pki.server(&first, crl.clone())).unwrap_err(); + assert!( + error.starts_with("server:") && error.contains("Revoked"), + "{error}" + ); + let error = connect( + pki.client_checking(&first, crl), + pki.server(&second, Revocations::none().shared()), + ) + .unwrap_err(); + assert!( + error.starts_with("client:") && error.contains("Revoked"), + "{error}" + ); +} + +#[test] +fn same_named_servers_have_their_own_certificates() { + let pki = Pki::new("Test CA"); + let first = pki.issue("server-1", &["peer"], Usage::Server); + let second = pki.issue("server-1", &["peer"], Usage::Server); + assert_ne!(first.certificate, second.certificate); + assert_ne!( + summarize(&first.certificate).unwrap().serial, + summarize(&second.certificate).unwrap().serial + ); + let client = pki.issue("kitchen", &[], Usage::Client); + for server in [&first, &second] { + assert!( + connect( + pki.client(&client), + pki.server(server, Revocations::none().shared()) + ) + .is_ok() + ); + } + + // Revoking one leaves the other alone, as a server and as a client. + let crl = pki.revoking(&[&first]); + let checking = pki.client_checking(&client, crl.clone()); + assert!( + connect( + checking.clone(), + pki.server(&first, Revocations::none().shared()) + ) + .is_err() + ); + assert!(connect(checking, pki.server(&second, Revocations::none().shared())).is_ok()); + let gate = pki.server(&pki.issue("server-2", &[], Usage::Server), crl); + assert!(connect(pki.client(&first), gate.clone()).is_err()); + assert!(connect(pki.client(&second), gate).is_ok()); +} diff --git a/crates/bakashrot-proto/Cargo.toml b/crates/bakashrot-proto/Cargo.toml new file mode 100644 index 0000000..dfa2ab9 --- /dev/null +++ b/crates/bakashrot-proto/Cargo.toml @@ -0,0 +1,28 @@ +[package] +name = "bakashrot-proto" +description = "BakaShrot's protocol: packets, frames, names, limits and error codes, shared by the server, the clients and the tools." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +authors.workspace = true +repository.workspace = true +publish.workspace = true + +[lints] +workspace = true + +# As few as possible: every other crate builds on this one. +[dependencies] +rmp-serde = "1.3.1" +serde = { version = "1.0.229", features = ["derive"] } +serde_bytes = "0.11.19" +tokio-util = { version = "0.7.20", features = ["codec"], optional = true } + +[features] +# `frame::codec()`, for the async server: the blocking client (the DLL) +# leaves it off and never pulls tokio in. +tokio = ["dep:tokio-util"] + +[dev-dependencies] +bytes = "1.12.1" diff --git a/crates/bakashrot-proto/src/error.rs b/crates/bakashrot-proto/src/error.rs new file mode 100644 index 0000000..7c5248c --- /dev/null +++ b/crates/bakashrot-proto/src/error.rs @@ -0,0 +1,181 @@ +//! The error codes: what a server sends with each refusal (1-99, in a +//! `RequestRefused`), and the client's own (100 and up, what the DLL's +//! `BakaShrot_GetLastError()` returns). The same numbers as protocol 6 +//! (`OldSource/Client/BakaShrot_ErrorCodes.pbi`): never renumber one, only +//! add new ones. +//! +//! What to do about each: +//! - reconnect, then retry: `NotConnected`, `ConnectFailed`, +//! `ConnectionLost`, `ProtocolError` (the connection is closed); +//! - retry later: `NotReady`, `ServerError`; +//! - fix the configuration: `AuthRejected`, `ServerNotVerified`, +//! `NotAllowed`, `UnknownName`, `NoDefaultTopic`; +//! - update one end: `VersionMismatch`; +//! - fix the call: `InvalidArgument`, `InvalidRequest`, `TooBig`, +//! `QueryFailed`, `FileError`; +//! - gone, or not there yet: `NotFound`; +//! - send it again: `DataMismatch` (an upload), `AttachmentMismatch` (a +//! download). +//! +//! A push whose answer was lost (`ConnectionLost`) may have been stored all +//! the same: pushed again, it's stored twice. Delivery is at least once. + +use std::fmt; + +/// The highest code a refusal can have: anything above is the client's own. +pub const MAX_REFUSAL_CODE: u32 = 99; + +macro_rules! error_codes { + ($( $name:ident = $code:literal, $description:literal; )*) => { + /// An error code, see the [module](self). + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + #[repr(u32)] + pub enum ErrorCode { + $( #[doc = $description] $name = $code, )* + } + + impl ErrorCode { + /// Every code, in order. + pub const ALL: &'static [ErrorCode] = &[$(ErrorCode::$name),*]; + + /// The code with this number, if there's one. + pub const fn from_code(code: u32) -> Option { + match code { + $( $code => Some(ErrorCode::$name), )* + _ => None, + } + } + + /// Its name, as the constants have it: "NotFound". + pub const fn name(self) -> &'static str { + match self { + $( ErrorCode::$name => stringify!($name), )* + } + } + + /// What it means: its documentation. + pub const fn description(self) -> &'static str { + match self { + $( ErrorCode::$name => $description, )* + } + } + } + }; +} + +// One text per code: its documentation, and what `description()` says. +error_codes! { + // Refused by the server: the connection is still open. + NotAllowed = 1, "Not allowed to this client: its roles' permissions, or a request only peers may make."; + UnknownName = 2, "A topic or node this server doesn't know."; + NotFound = 3, "No such message or attachment."; + NotReady = 4, "The attachment isn't on this server yet (still being replicated)."; + TooBig = 5, "A message, attachment or query result over a limit, or an attachment bigger than this server keeps."; + NoDefaultTopic = 6, "Protocol 6's: a push without a topic and no default one. Protocol 7 pushes always name their topic: never sent, kept so the number isn't reused."; + InvalidRequest = 7, "A request that doesn't fit: an attachment's parts not matching its size, a part that doesn't exist..."; + DataMismatch = 8, "An uploaded attachment that doesn't match its SHA-256: dropped."; + QueryFailed = 9, "The SQL of a query failed (its error in the reason)."; + ServerError = 10, "The server couldn't store or read something: its database failed."; + + // The client's own. + NotConnected = 100, "Not connected: never, or the connection was closed or lost before."; + ConnectFailed = 101, "The server couldn't be reached at that host and port."; + AuthRejected = 102, "The server refused the connection: a certificate it doesn't take (another CA, revoked, expired), or another protocol version."; + ServerNotVerified = 103, "The server's certificate isn't from the expected CA, or isn't for that host."; + ConnectionLost = 104, "The connection broke during a request (it's closed now). A push may still have been stored."; + ProtocolError = 105, "The server answered something unexpected or malformed: the connection is closed."; + InvalidArgument = 106, "A bad argument: a topic or node that isn't a name, a null pointer, a message or attachment over the limits, a setting missing before connecting."; + FileError = 107, "A file couldn't be opened, read or written."; + AttachmentMismatch = 108, "A downloaded attachment doesn't match its SHA-256."; + AlreadyConnected = 109, "Already connected: disconnect first."; + Internal = 110, "Out of memory, or another failure inside the client."; + VersionMismatch = 111, "The server speaks another version of the protocol: update the client or the server."; +} + +impl ErrorCode { + /// Its number. + pub const fn code(self) -> u32 { + self as u32 + } + + /// Whether a server sends it with a refusal (1-99): the connection is + /// still open. + pub const fn is_refusal(self) -> bool { + is_refusal_code(self.code()) + } +} + +/// Whether `code` is a refusal's (1-99), known or not. +pub const fn is_refusal_code(code: u32) -> bool { + code >= 1 && code <= MAX_REFUSAL_CODE +} + +/// The name of any code: `None` for 0, the code's name, or `Error ` +/// for one this version doesn't know. +pub fn code_name(code: u32) -> String { + match ErrorCode::from_code(code) { + Some(known) => known.name().to_owned(), + None if code == 0 => "None".to_owned(), + None => format!("Error {code}"), + } +} + +impl fmt::Display for ErrorCode { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.name()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_numbers_of_protocol_6() { + let expected: &[(u32, &str)] = &[ + (1, "NotAllowed"), + (2, "UnknownName"), + (3, "NotFound"), + (4, "NotReady"), + (5, "TooBig"), + (6, "NoDefaultTopic"), + (7, "InvalidRequest"), + (8, "DataMismatch"), + (9, "QueryFailed"), + (10, "ServerError"), + (100, "NotConnected"), + (101, "ConnectFailed"), + (102, "AuthRejected"), + (103, "ServerNotVerified"), + (104, "ConnectionLost"), + (105, "ProtocolError"), + (106, "InvalidArgument"), + (107, "FileError"), + (108, "AttachmentMismatch"), + (109, "AlreadyConnected"), + (110, "Internal"), + (111, "VersionMismatch"), + ]; + assert_eq!(ErrorCode::ALL.len(), expected.len()); + for (code, name) in expected { + let known = ErrorCode::from_code(*code).expect("a known code"); + assert_eq!(known.code(), *code); + assert_eq!(known.name(), *name); + assert_eq!(known.is_refusal(), *code < 100); + assert!(!known.description().is_empty()); + } + } + + #[test] + fn names_of_any_code() { + assert_eq!(code_name(0), "None"); + assert_eq!(code_name(3), "NotFound"); + assert_eq!(code_name(42), "Error 42"); + assert_eq!(ErrorCode::from_code(0), None); + assert_eq!(ErrorCode::from_code(42), None); + assert!(is_refusal_code(42)); + assert!(!is_refusal_code(0)); + assert!(!is_refusal_code(100)); + assert_eq!(ErrorCode::TooBig.to_string(), "TooBig"); + } +} diff --git a/crates/bakashrot-proto/src/frame.rs b/crates/bakashrot-proto/src/frame.rs new file mode 100644 index 0000000..13e30f3 --- /dev/null +++ b/crates/bakashrot-proto/src/frame.rs @@ -0,0 +1,252 @@ +//! Frames: every packet goes as one, its size as a 4-byte little-endian +//! unsigned integer, then the packet. A frame of more than the limit is +//! invalid as soon as its size arrived: the connection is aborted without +//! waiting for the rest. An empty one is too (as a frame here, as a packet +//! that doesn't decode with [`codec()`]). +//! +//! Over TLS, which takes care of the encryption: unlike protocol 6, frames +//! carry packets as they are. +//! +//! Before any frame, right after TLS, each end sends its protocol version +//! (4 bytes, little-endian) and reads the other's: [`write_version()`], +//! [`read_version()`], [`check_version()`]. Ends of different versions +//! abandon the connection there, whatever later versions do to frames and +//! packets. +//! +//! - [`write()`] and [`read()`]: on a blocking stream, the client's (the +//! DLL has no async runtime). +//! - [`codec()`], with the `tokio` feature: the same frames for the async +//! server, `tokio-util`'s codec (with `Framed`, a connection becomes a +//! stream of packets in and a sink of packets out). + +use crate::limits::{MAX_PACKET_SIZE, PROTOCOL_VERSION}; +use std::fmt; +use std::io::{self, Read, Write}; + +/// The size of a frame's header. +pub const HEADER_SIZE: usize = 4; + +/// The size of the version each end sends first. +pub const VERSION_SIZE: usize = 4; + +/// The version bytes this end sends: [`PROTOCOL_VERSION`], little-endian. +pub const fn version_bytes() -> [u8; VERSION_SIZE] { + PROTOCOL_VERSION.to_le_bytes() +} + +/// Checks the version bytes the other end sent: `Err` with its version if +/// it isn't this one (abandon the connection then). +pub const fn check_version(bytes: [u8; VERSION_SIZE]) -> Result<(), u32> { + let theirs = u32::from_le_bytes(bytes); + if theirs == PROTOCOL_VERSION { + Ok(()) + } else { + Err(theirs) + } +} + +/// Sends this end's version, on a blocking stream. +pub fn write_version(writer: &mut W) -> io::Result<()> { + writer.write_all(&version_bytes()) +} + +/// Reads the other end's version, on a blocking stream: compare it with +/// [`check_version()`]. +pub fn read_version(reader: &mut R) -> io::Result<[u8; VERSION_SIZE]> { + let mut bytes = [0; VERSION_SIZE]; + reader.read_exact(&mut bytes)?; + Ok(bytes) +} + +/// Why a frame is invalid. Either aborts the connection. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FrameError { + /// A frame of 0 bytes. + Empty, + /// A frame bigger than the limit. + TooBig { + /// Its size. + size: usize, + /// The limit. + max: usize, + }, +} + +impl fmt::Display for FrameError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + FrameError::Empty => f.write_str("an empty frame"), + FrameError::TooBig { size, max } => { + write!(f, "a frame of {size} bytes, over the limit of {max}") + } + } + } +} + +impl std::error::Error for FrameError {} + +fn check(size: usize, max: usize) -> Result<(), FrameError> { + if size == 0 { + Err(FrameError::Empty) + } else if size > max { + Err(FrameError::TooBig { size, max }) + } else { + Ok(()) + } +} + +/// `packet` as a frame: its size, then itself. Fails if it's empty or over +/// [`MAX_PACKET_SIZE`]. +pub fn encode(packet: &[u8]) -> Result, FrameError> { + check(packet.len(), MAX_PACKET_SIZE)?; + let mut frame = Vec::with_capacity(HEADER_SIZE + packet.len()); + frame.extend_from_slice(&(packet.len() as u32).to_le_bytes()); + frame.extend_from_slice(packet); + Ok(frame) +} + +/// Writes `packet` as a frame, in one write. +pub fn write(writer: &mut W, packet: &[u8]) -> io::Result<()> { + let frame = + encode(packet).map_err(|error| io::Error::new(io::ErrorKind::InvalidInput, error))?; + writer.write_all(&frame) +} + +/// Reads the next frame's packet, at most `max` bytes. +/// +/// `Ok(None)` when the stream ended cleanly, before the next frame. An +/// error of kind `UnexpectedEof` if it ended inside one, `InvalidData` (a +/// [`FrameError`] inside) if its size is 0 or over `max`. +pub fn read(reader: &mut R, max: usize) -> io::Result>> { + let mut header = [0u8; HEADER_SIZE]; + let mut got = 0; + while got < HEADER_SIZE { + match reader.read(&mut header[got..]) { + Ok(0) if got == 0 => return Ok(None), + Ok(0) => return Err(io::ErrorKind::UnexpectedEof.into()), + Ok(count) => got += count, + Err(error) if error.kind() == io::ErrorKind::Interrupted => {} + Err(error) => return Err(error), + } + } + let size = u32::from_le_bytes(header) as usize; + check(size, max).map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?; + let mut packet = vec![0; size]; + reader.read_exact(&mut packet)?; + Ok(Some(packet)) +} + +/// The frames as `tokio-util` cuts and writes them, for the async server: +/// the same as [`read()`] and [`write()`], packets of up to `max` bytes +/// ([`MAX_PACKET_SIZE`] at most). Use it with `tokio_util::codec::Framed`. +#[cfg(feature = "tokio")] +pub fn codec(max: usize) -> tokio_util::codec::LengthDelimitedCodec { + tokio_util::codec::LengthDelimitedCodec::builder() + .little_endian() + .length_field_length(HEADER_SIZE) + .max_frame_length(max.min(MAX_PACKET_SIZE)) + .new_codec() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn blocking_round_trip() { + let mut stream = Vec::new(); + write(&mut stream, b"abc").unwrap(); + write(&mut stream, &[7; 300]).unwrap(); + assert_eq!(&stream[..7], &[3, 0, 0, 0, b'a', b'b', b'c']); + + let mut reader = &stream[..]; + assert_eq!(read(&mut reader, 1000).unwrap(), Some(b"abc".to_vec())); + assert_eq!(read(&mut reader, 1000).unwrap(), Some(vec![7; 300])); + assert_eq!(read(&mut reader, 1000).unwrap(), None); + } + + #[test] + fn versions() { + let mut stream = Vec::new(); + write_version(&mut stream).unwrap(); + assert_eq!(stream, [7, 0, 0, 0]); + let bytes = read_version(&mut &stream[..]).unwrap(); + assert_eq!(check_version(bytes), Ok(())); + assert_eq!(check_version([6, 0, 0, 0]), Err(6)); + assert_eq!(check_version([8, 0, 0, 0]), Err(8)); + assert!(read_version(&mut &[7u8, 0][..]).is_err()); + } + + #[test] + fn blocking_refusals() { + assert_eq!(encode(&[]), Err(FrameError::Empty)); + assert!(write(&mut Vec::new(), &[]).is_err()); + + let kind = |bytes: &[u8], max| read(&mut &bytes[..], max).unwrap_err().kind(); + assert_eq!(kind(&[0, 0, 0, 0], 10), io::ErrorKind::InvalidData); + assert_eq!(kind(&[11, 0, 0, 0], 10), io::ErrorKind::InvalidData); + assert_eq!(kind(&[3, 0], 10), io::ErrorKind::UnexpectedEof); + assert_eq!(kind(&[3, 0, 0, 0, 1], 10), io::ErrorKind::UnexpectedEof); + } + + #[cfg(feature = "tokio")] + mod codec { + use super::super::*; + use bytes::{Bytes, BytesMut}; + use tokio_util::codec::{Decoder, Encoder}; + + #[test] + fn the_same_frames() { + let mut codec = codec(MAX_PACKET_SIZE); + let mut written = BytesMut::new(); + codec + .encode(Bytes::from_static(b"abc"), &mut written) + .unwrap(); + assert_eq!(&written[..], &encode(b"abc").unwrap()[..]); + } + + #[test] + fn byte_by_byte() { + let mut stream = encode(b"first").unwrap(); + stream.extend(encode(&[1; 70_000]).unwrap()); + stream.extend(encode(b"third").unwrap()); + + let mut codec = codec(100_000); + let mut buffer = BytesMut::new(); + let mut packets = Vec::new(); + for byte in &stream { + buffer.extend_from_slice(&[*byte]); + while let Some(packet) = codec.decode(&mut buffer).unwrap() { + packets.push(packet.to_vec()); + } + } + assert_eq!( + packets, + vec![b"first".to_vec(), vec![1; 70_000], b"third".to_vec()] + ); + } + + #[test] + fn refused_as_soon_as_the_size_came() { + let mut codec = codec(10); + let mut buffer = BytesMut::from(&[11u8, 0, 0][..]); + assert!(codec.decode(&mut buffer).unwrap().is_none()); + buffer.extend_from_slice(&[0]); + assert!(codec.decode(&mut buffer).is_err()); + + // Never above the protocol's limit. + assert_eq!( + super::super::codec(usize::MAX).max_frame_length(), + MAX_PACKET_SIZE + ); + } + + #[test] + fn an_empty_frame_is_an_empty_packet() { + let mut codec = codec(10); + let mut buffer = BytesMut::from(&[0u8, 0, 0, 0][..]); + let packet = codec.decode(&mut buffer).unwrap().unwrap(); + assert!(crate::Packet::decode(&packet).is_err()); + } + } +} diff --git a/crates/bakashrot-proto/src/lib.rs b/crates/bakashrot-proto/src/lib.rs new file mode 100644 index 0000000..8138a2a --- /dev/null +++ b/crates/bakashrot-proto/src/lib.rs @@ -0,0 +1,23 @@ +//! BakaShrot's protocol, version 7: what the server, the clients and the +//! tools share, and nothing else. +//! +//! No I/O of its own beyond reading and writing frames on a stream it's +//! given: everything here is tested on its own. Packets are MessagePack, +//! through `serde` and `rmp-serde`. +//! +//! - [`limits`]: the protocol's numbers (sizes, counts, the version). +//! - [`error`]: the error codes, the same numbers as protocol 6. +//! - [`names`]: topic and node names, wildcards. +//! - [`frame`]: frames, a 4-byte size then a packet. +//! - [`packets`]: every packet, and [`Packet`] to encode and decode them. +//! +//! The wire format is described in `docs/protocol.md`. + +pub mod error; +pub mod frame; +pub mod limits; +pub mod names; +pub mod packets; + +pub use error::ErrorCode; +pub use packets::{Body, DecodeError, Packet, PacketType}; diff --git a/crates/bakashrot-proto/src/limits.rs b/crates/bakashrot-proto/src/limits.rs new file mode 100644 index 0000000..edeb54f --- /dev/null +++ b/crates/bakashrot-proto/src/limits.rs @@ -0,0 +1,105 @@ +//! The protocol's numbers: its version, sizes and counts. Servers may set +//! lower limits of their own (a smaller maximum attachment, say), never +//! higher ones. + +/// The protocol's version. Both ends must have the same: they tell each +/// other first thing (`frame::write_version()`), and abandon the +/// connection if it differs. 6 was the last PureBasic one (`OldSource/`); +/// 7 runs over TLS. +pub const PROTOCOL_VERSION: u32 = 7; + +/// The ALPN protocol name both ends offer during the TLS handshake: what +/// isn't BakaShrot doesn't get past it. Not versioned: the version is +/// checked once connected, so a mismatch is told as such. +pub const ALPN: &[u8] = b"bakashrot"; + +/// The biggest packet on the wire, in bytes (a frame's size field). +pub const MAX_PACKET_SIZE: usize = 16 * 1024 * 1024; + +/// The biggest message a client may push, in UTF-8 bytes. It leaves room +/// for the fields around it, so a stored message fits in every packet that +/// carries one (a `Messages` or `ReplicateMessages` of one). +pub const MAX_MESSAGE_SIZE: usize = MAX_PACKET_SIZE - 4096; + +/// The latest time a message can have been pushed: 9999-12-31 23:59:59.999 +/// UTC, in milliseconds since 1970-01-01 00:00:00 UTC. Times on the wire go +/// from 1 to this. +pub const MAX_TIMESTAMP: u64 = 253_402_300_799_999; + +/// The biggest message id: 2^43 - 1, about 8.8 trillion per topic and +/// node. Servers store it in 43 bits of a packed key +/// (`docs/storage.md`, "Keys"). +pub const MAX_MESSAGE_ID: u64 = (1 << 43) - 1; + +/// The longest topic or node name, in characters (ASCII only). +pub const MAX_NAME_LENGTH: usize = 64; + +/// The most messages a `GetMessages` may ask for, a `Messages` may carry, +/// and a `ReplicateMessages` may hold. +pub const MAX_MESSAGES_PER_PACKET: u32 = 10_000; + +/// The most names in a `NamesList`, and in each list of a `SyncState`. +pub const MAX_NAMES_LIST_ENTRIES: usize = 65_536; + +/// The most attachments a `SyncState` lists as missing at once. +pub const MAX_MISSING_ATTACHMENTS: usize = 256; + +/// Attachments go in parts of this many bytes, the last one what's left. +pub const ATTACHMENT_PART_SIZE: u64 = 1024 * 1024; + +/// The biggest attachment the protocol allows (1 TiB). +pub const MAX_ATTACHMENT_SIZE: u64 = 1 << 40; + +/// How many parts the biggest attachment takes. +pub const MAX_ATTACHMENT_PARTS: u64 = MAX_ATTACHMENT_SIZE / ATTACHMENT_PART_SIZE; + +/// How many parts an attachment of `size` bytes takes. +pub const fn attachment_part_count(size: u64) -> u64 { + size.div_ceil(ATTACHMENT_PART_SIZE) +} + +/// The size of part `index` of an attachment of `size` bytes, 0 if it has +/// no such part. +pub const fn attachment_part_len(size: u64, index: u64) -> u64 { + if index >= attachment_part_count(size) { + 0 + } else if index == attachment_part_count(size) - 1 { + size - index * ATTACHMENT_PART_SIZE + } else { + ATTACHMENT_PART_SIZE + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parts() { + assert_eq!(attachment_part_count(0), 0); + assert_eq!(attachment_part_count(1), 1); + assert_eq!(attachment_part_count(ATTACHMENT_PART_SIZE), 1); + assert_eq!(attachment_part_count(ATTACHMENT_PART_SIZE + 1), 2); + assert_eq!( + attachment_part_count(MAX_ATTACHMENT_SIZE), + MAX_ATTACHMENT_PARTS + ); + + let size = 2 * ATTACHMENT_PART_SIZE + 10; + assert_eq!(attachment_part_len(size, 0), ATTACHMENT_PART_SIZE); + assert_eq!(attachment_part_len(size, 1), ATTACHMENT_PART_SIZE); + assert_eq!(attachment_part_len(size, 2), 10); + assert_eq!(attachment_part_len(size, 3), 0); + assert_eq!(attachment_part_len(0, 0), 0); + assert_eq!( + attachment_part_len(ATTACHMENT_PART_SIZE, 0), + ATTACHMENT_PART_SIZE + ); + } + + #[test] + fn a_stored_message_fits_in_a_packet() { + const { assert!(MAX_MESSAGE_SIZE + 4096 <= MAX_PACKET_SIZE) }; + assert!(MAX_PACKET_SIZE <= u32::MAX as usize); + } +} diff --git a/crates/bakashrot-proto/src/names.rs b/crates/bakashrot-proto/src/names.rs new file mode 100644 index 0000000..cefa5df --- /dev/null +++ b/crates/bakashrot-proto/src/names.rs @@ -0,0 +1,148 @@ +//! Topic and node names, and wildcards: the rules of protocol 6 +//! (`OldSource/Commons/Networking/Names.pbi`), without its ids. +//! +//! Topics and nodes go by name everywhere on the wire: a server's ids for +//! them are its own business, in its database. +//! +//! - A **name** is 1-64 characters out of `A-Z a-z 0-9 _ . -`, not only +//! digits, compared without case ("Logs" is "logs"). +//! - A **pattern** is a name with wildcards, like file names: `*` any +//! characters (none included), `?` exactly one. + +use crate::limits::MAX_NAME_LENGTH; + +/// Whether `c` may be in a name. +const fn is_name_char(c: u8) -> bool { + c.is_ascii_alphanumeric() || c == b'_' || c == b'.' || c == b'-' +} + +/// Whether `name` can be a topic or node name, see the [module](self). +pub fn is_valid_name(name: &str) -> bool { + !name.is_empty() + && name.len() <= MAX_NAME_LENGTH + && !name.bytes().all(|c| c.is_ascii_digit()) + && name.bytes().all(is_name_char) +} + +/// Whether two names are the same name (without case). +pub fn names_equal(a: &str, b: &str) -> bool { + a.eq_ignore_ascii_case(b) +} + +/// Whether `pattern` is a valid pattern: a `*` or a `?` at least, and +/// otherwise only characters a name can have, 64 at most. +pub fn is_valid_pattern(pattern: &str) -> bool { + !pattern.is_empty() + && pattern.len() <= MAX_NAME_LENGTH + && pattern.bytes().any(|c| c == b'*' || c == b'?') + && pattern + .bytes() + .all(|c| is_name_char(c) || c == b'*' || c == b'?') +} + +/// Whether `text` is a name or a pattern: what a list of topics or nodes +/// holds (`SyncState`, configs). +pub fn is_valid_name_or_pattern(text: &str) -> bool { + is_valid_name(text) || is_valid_pattern(text) +} + +/// Whether the name `name` matches `pattern` (without case). Anything that +/// isn't a valid name never matches. +pub fn pattern_matches(pattern: &str, name: &str) -> bool { + if !is_valid_name(name) { + return false; + } + let pattern = pattern.as_bytes(); + let name = name.as_bytes(); + let (mut p, mut n) = (0, 0); + // Where the last `*` was, and where in the name it started matching. + let mut star: Option<(usize, usize)> = None; + + // Greedy, going back to the last `*` on a mismatch: linear enough for + // 64 characters. + while n < name.len() { + if p < pattern.len() && pattern[p] == b'*' { + star = Some((p, n)); + p += 1; + } else if p < pattern.len() + && (pattern[p] == b'?' || pattern[p].eq_ignore_ascii_case(&name[n])) + { + p += 1; + n += 1; + } else if let Some((star_p, star_n)) = star { + p = star_p + 1; + n = star_n + 1; + star = Some((star_p, star_n + 1)); + } else { + return false; + } + } + pattern[p..].iter().all(|c| *c == b'*') +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn names() { + for name in [ + "logs", + "Logs", + "kitchen-1", + "a.b_c-d", + "x", + "1a", + &"a".repeat(64), + ] { + assert!(is_valid_name(name), "{name}"); + } + for name in ["", "12", "0", "a b", "é", "a/b", "a*", &"a".repeat(65)] { + assert!(!is_valid_name(name), "{name}"); + } + assert!(names_equal("Logs", "lOGS")); + assert!(!names_equal("logs", "log")); + } + + #[test] + fn patterns() { + for pattern in ["*", "?", "sensors.*", "kitchen-??", "*a*b*"] { + assert!(is_valid_pattern(pattern), "{pattern}"); + assert!(is_valid_name_or_pattern(pattern), "{pattern}"); + } + for pattern in ["", "logs", "a b*", "a/*", &format!("{}*", "a".repeat(64))] { + assert!(!is_valid_pattern(pattern), "{pattern}"); + } + assert!(is_valid_name_or_pattern("logs")); + assert!(!is_valid_name_or_pattern("12")); + assert!(!is_valid_name_or_pattern("a b")); + + let cases = [ + ("*", "logs", true), + ("sensors.*", "sensors.kitchen", true), + // `*` matches nothing too, and "sensors." is a name. + ("sensors.*", "sensors.", true), + ("sensors.*", "SENSORS.x", true), + ("sensors.*", "sensor.x", false), + ("kitchen-??", "kitchen-12", true), + ("kitchen-??", "kitchen-1", false), + ("kitchen-??", "kitchen-123", false), + ("*a*b*", "xxaxxbxx", true), + ("*a*b", "ab", true), + ("*a*b", "aba", false), + ("a*a*a", "aaa", true), + ("a*a*a", "aa", false), + ("**", "x", true), + ("*", "12", false), + ("?", "1", false), + ("*", "", false), + ]; + for (pattern, name, expected) in cases { + assert_eq!( + pattern_matches(pattern, name), + expected, + "{pattern} / {name}" + ); + } + } +} diff --git a/crates/bakashrot-proto/src/packets/attachments.rs b/crates/bakashrot-proto/src/packets/attachments.rs new file mode 100644 index 0000000..1ce5687 --- /dev/null +++ b/crates/bakashrot-proto/src/packets/attachments.rs @@ -0,0 +1,108 @@ +//! Attachments: one per message at most, in parts of `ATTACHMENT_PART_SIZE` +//! (the last one what's left), checked with their SHA-256 once all came. +//! +//! Parts are streamed, without a request or an answer each: +//! - **Pushing:** `PushMessage` with its `Attachment`, the server's +//! `Continue`, every part, then `MessagePushed` (or `RequestRefused`, +//! `DataMismatch` if the SHA-256 doesn't match). Once it said `Continue`, +//! the server reads every part even if storing them failed, then refuses. +//! - **Reading:** `GetAttachment`, the server's `Attachment`, then the +//! parts from the one asked to the last. A server that fails while +//! sending them closes the connection. +//! - **Replicating:** `ReplicateAttachment`, the server's `Continue`, the +//! parts from the one it lacks, then `MessagePushed`. +//! +//! A part is its data alone: its index follows from the order, its size +//! from the attachment's ([`Attachment::part_len`]), which the receiver +//! checks. + +use super::rules; +use super::{Check, DecodeError}; +use crate::limits::{ + ATTACHMENT_PART_SIZE, MAX_ATTACHMENT_PARTS, MAX_ATTACHMENT_SIZE, attachment_part_count, + attachment_part_len, +}; +use serde::{Deserialize, Serialize}; + +/// An attachment's size and checksum: in a `PushMessage` or a replicated +/// message, and on its own before the parts of a `GetAttachment`. +/// +/// `[9, [size, sha256]]` +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Attachment { + /// Its size, 1 to `MAX_ATTACHMENT_SIZE` (servers may take less). + pub size: u64, + /// Its SHA-256. + #[serde(with = "serde_bytes")] + pub sha256: [u8; 32], +} + +impl Attachment { + /// How many parts it takes. + pub const fn part_count(&self) -> u64 { + attachment_part_count(self.size) + } + + /// The size its part `index` must have, 0 if it has no such part. + pub const fn part_len(&self, index: u64) -> u64 { + attachment_part_len(self.size, index) + } +} + +impl Check for Attachment { + fn check(&self) -> Result<(), DecodeError> { + rules::range(self.size, 1, MAX_ATTACHMENT_SIZE, "Attachment.size") + } +} + +/// A part of an attachment, the next one. +/// +/// `[10, [data]]` +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct AttachmentPart { + /// The part, 1 to `ATTACHMENT_PART_SIZE` bytes (its exact size is the + /// receiver's to check). + #[serde(with = "serde_bytes")] + pub data: Vec, +} + +impl Check for AttachmentPart { + fn check(&self) -> Result<(), DecodeError> { + rules::range( + self.data.len() as u64, + 1, + ATTACHMENT_PART_SIZE, + "AttachmentPart.data", + ) + } +} + +/// A message's attachment, from a part on (0 for all of it). +/// +/// `[8, [topic, node, message_id, from_part]]` +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct GetAttachment { + /// The topic. + pub topic: String, + /// The node. + pub node: String, + /// The message. + pub message_id: u64, + /// The first part to send: a client going on from where a lost + /// connection stopped. + pub from_part: u64, +} + +impl Check for GetAttachment { + fn check(&self) -> Result<(), DecodeError> { + rules::name(&self.topic, "GetAttachment.topic")?; + rules::name(&self.node, "GetAttachment.node")?; + rules::message_id(self.message_id, "GetAttachment.message_id")?; + rules::range( + self.from_part, + 0, + MAX_ATTACHMENT_PARTS - 1, + "GetAttachment.from_part", + ) + } +} diff --git a/crates/bakashrot-proto/src/packets/messages.rs b/crates/bakashrot-proto/src/packets/messages.rs new file mode 100644 index 0000000..d958d24 --- /dev/null +++ b/crates/bakashrot-proto/src/packets/messages.rs @@ -0,0 +1,235 @@ +//! Clients' requests and their answers: pushing and reading messages, +//! names, queries. + +use super::rules; +use super::{Attachment, Check, DecodeError}; +use crate::limits::{ + MAX_ATTACHMENT_SIZE, MAX_MESSAGE_ID, MAX_MESSAGES_PER_PACKET, MAX_NAMES_LIST_ENTRIES, +}; +use serde::{Deserialize, Serialize}; + +/// A message's attachment, as reads show it. +/// +/// `[size, ready]` +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct StoredAttachment { + /// Its size, 1 and up. + pub size: u64, + /// Whether all of it is on this server (it may still be on its way from + /// a peer). + pub ready: bool, +} + +/// A stored message, as `Messages` carries it. +/// +/// `[id, pushed_at, data, attachment]` +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct MessageEntry { + /// Its id, in its topic/node pair (1 and up). + pub id: u64, + /// When it was pushed: milliseconds since 1970 UTC, by the server it was + /// pushed to, kept as is by replication. + pub pushed_at: u64, + /// The message, as pushed (JSON or not). + pub data: String, + /// Its attachment, if it has one. + pub attachment: Option, +} + +impl Check for MessageEntry { + fn check(&self) -> Result<(), DecodeError> { + rules::message_id(self.id, "message.id")?; + rules::timestamp(self.pushed_at, "message.pushed_at")?; + if let Some(attachment) = &self.attachment { + rules::range( + attachment.size, + 1, + MAX_ATTACHMENT_SIZE, + "message.attachment.size", + )?; + } + Ok(()) + } +} + +/// Stores a message under the client's node. With an attachment, the +/// server answers `Continue` (or refuses), the client sends all its parts, +/// then the server stores both and answers `MessagePushed`. +/// +/// `[4, [topic, data, attachment]]` +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct PushMessage { + /// The topic: a push always names it. + pub topic: String, + /// The message (JSON or not), up to `MAX_MESSAGE_SIZE` bytes (the + /// server refuses bigger ones). + pub data: String, + /// Its attachment, whose parts follow the server's `Continue`. + pub attachment: Option, +} + +impl Check for PushMessage { + fn check(&self) -> Result<(), DecodeError> { + rules::name(&self.topic, "PushMessage.topic")?; + if let Some(attachment) = &self.attachment { + attachment.check()?; + } + Ok(()) + } +} + +/// The id a message was stored with (the last of a replicated batch). +/// +/// `[5, [message_id]]` +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct MessagePushed { + /// The id. + pub message_id: u64, +} + +impl Check for MessagePushed { + fn check(&self) -> Result<(), DecodeError> { + rules::message_id(self.message_id, "MessagePushed.message_id") + } +} + +/// A topic/node's messages, in id order: those after an id, or its last +/// ones. +/// +/// `[6, [topic, node, after, limit]]` +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct GetMessages { + /// The topic. + pub topic: String, + /// The node. + pub node: String, + /// Those with a higher id than this (0 for all), or nil for the last + /// `limit` ones (the latest message: nil and 1). + pub after: Option, + /// At most this many, 1 to `MAX_MESSAGES_PER_PACKET`. + pub limit: u32, +} + +impl Check for GetMessages { + fn check(&self) -> Result<(), DecodeError> { + rules::name(&self.topic, "GetMessages.topic")?; + rules::name(&self.node, "GetMessages.node")?; + if let Some(after) = self.after { + rules::range(after, 0, MAX_MESSAGE_ID, "GetMessages.after")?; + } + rules::range( + self.limit.into(), + 1, + MAX_MESSAGES_PER_PACKET.into(), + "GetMessages.limit", + ) + } +} + +/// A run of a topic/node's messages, in id order. None isn't a refusal. +/// +/// `[7, [more, [message...]]]` +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Messages { + /// Whether more follow the last one: ask again after its id. + pub more: bool, + /// The messages, ids strictly increasing, `MAX_MESSAGES_PER_PACKET` at + /// most; fewer than asked once they reach about a megabyte (the + /// server's choice), a bigger message alone. + pub messages: Vec, +} + +impl Check for Messages { + fn check(&self) -> Result<(), DecodeError> { + rules::most( + self.messages.len(), + MAX_MESSAGES_PER_PACKET as usize, + "Messages.messages", + )?; + rules::increasing(self.messages.iter().map(|m| m.id), "Messages.messages")?; + self.messages.iter().try_for_each(Check::check) + } +} + +/// Raw read-only SQL. +/// +/// `[13, [sql]]` +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Query { + /// The query: one statement, starting with SELECT or WITH. + pub sql: String, +} + +impl Check for Query {} + +/// A query's result. +/// +/// `[14, [json]]` +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct QueryResult { + /// `{"columns":[...],"rows":[[...],...]}`. + pub json: String, +} + +impl Check for QueryResult {} + +/// Topics or nodes: 1 or 2 on the wire. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(into = "u8", try_from = "u8")] +pub enum NameKind { + /// Topics. + Topic = 1, + /// Nodes. + Node = 2, +} + +impl From for u8 { + fn from(kind: NameKind) -> u8 { + kind as u8 + } +} + +impl TryFrom for NameKind { + type Error = &'static str; + + fn try_from(value: u8) -> Result { + match value { + 1 => Ok(NameKind::Topic), + 2 => Ok(NameKind::Node), + _ => Err("a name kind is 1 (topics) or 2 (nodes)"), + } + } +} + +/// Every topic or node the client may see. +/// +/// `[11, [kind]]` +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ListNames { + /// Topics or nodes. + pub kind: NameKind, +} + +impl Check for ListNames {} + +/// Topics or nodes. +/// +/// `[12, [kind, truncated, [name...]]]` +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct NamesList { + /// Topics or nodes. + pub kind: NameKind, + /// Whether some didn't fit. + pub truncated: bool, + /// The names, `MAX_NAMES_LIST_ENTRIES` at most. + pub names: Vec, +} + +impl Check for NamesList { + fn check(&self) -> Result<(), DecodeError> { + rules::most(self.names.len(), MAX_NAMES_LIST_ENTRIES, "NamesList.names")?; + self.names + .iter() + .try_for_each(|name| rules::name(name, "NamesList.names")) + } +} diff --git a/crates/bakashrot-proto/src/packets/mod.rs b/crates/bakashrot-proto/src/packets/mod.rs new file mode 100644 index 0000000..2662888 --- /dev/null +++ b/crates/bakashrot-proto/src/packets/mod.rs @@ -0,0 +1,324 @@ +//! Every packet of protocol 7. +//! +//! A packet is a MessagePack array of two: its type, then its fields as an +//! array, `[type, [field, field, ...]]`. Structs inside are arrays of their +//! fields too, `Option`s nil or their value, bytes binaries. All of it is +//! derived with `serde` (`rmp-serde`'s compact form): the structs below +//! are the format, `docs/protocol.md` lists them. +//! +//! [`Packet::decode`] checks everything: the types and the number of +//! fields (`serde`), then each packet's rules ([`Check`]: ranges, names, +//! ids in order), and that nothing follows. (A struct given as a map of its +//! field names is taken too, `serde`'s derive: nothing writes that form, it +//! isn't part of the format, its values are checked all the same.) Whatever isn't right is a +//! [`DecodeError`]: the connection is aborted. What's well-formed but not +//! allowed or not found (a topic this server doesn't have) is the server's +//! to refuse, with a `RequestRefused`. +//! +//! Topics and nodes are names everywhere, never ids. +//! +//! Adding a packet: a struct deriving `Serialize` and `Deserialize`, with +//! its [`Check`], in the file of its family; a line in the `packets!` table +//! below with the next id (never reuse one); a sample in `tests/packets.rs`; +//! its row in `docs/protocol.md`. + +mod attachments; +mod messages; +mod replication; +mod session; + +pub use attachments::{Attachment, AttachmentPart, GetAttachment}; +pub use messages::{ + GetMessages, ListNames, MessageEntry, MessagePushed, Messages, NameKind, NamesList, + PushMessage, Query, QueryResult, StoredAttachment, +}; +pub use replication::{ + Head, MissingAttachment, ReplicateAttachment, ReplicateMessages, ReplicatedMessage, SyncState, + SyncStateRequest, +}; +pub use session::{Continue, RequestRefused, Welcome}; + +use serde::de::{self, DeserializeOwned, IgnoredAny, SeqAccess, Visitor}; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use std::fmt; +use std::io::Cursor; + +/// Why a packet couldn't be read. Any of these aborts the connection. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum DecodeError { + /// Not a packet: not MessagePack, a value of the wrong type, a field + /// missing or one too many, a type this version doesn't know. + Malformed(String), + /// Bytes after the packet. + TrailingBytes, + /// A field breaking a rule of its packet. + Invalid { + /// The field. + field: &'static str, + /// The rule it breaks. + rule: &'static str, + }, +} + +impl fmt::Display for DecodeError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + DecodeError::Malformed(why) => write!(f, "malformed packet: {why}"), + DecodeError::TrailingBytes => f.write_str("bytes after the end of the packet"), + DecodeError::Invalid { field, rule } => write!(f, "{field}: {rule}"), + } + } +} + +impl std::error::Error for DecodeError {} + +/// The rules a packet's fields follow beyond their types, checked by +/// [`Packet::decode`]. None by default. +pub trait Check { + /// Fails on the first rule broken. + fn check(&self) -> Result<(), DecodeError> { + Ok(()) + } +} + +/// What every packet's struct is, implemented by the `packets!` table. +pub trait Body: Serialize + DeserializeOwned + Check + Into { + /// Its type, the packet's first value. + const TYPE: PacketType; + + /// The whole packet: `[type, [fields...]]`. + fn encode(&self) -> Vec { + rmp_serde::to_vec(&(Self::TYPE.id(), self)).expect("packets always serialize") + } +} + +// The one table of packets: their names (the struct's and the variant's) +// and ids. Protocol 7's own: protocol 6's ids don't apply (the versions are +// checked before any packet). +macro_rules! packets { + ($( $(#[$doc:meta])* $name:ident = $id:literal, )*) => { + /// The type of a packet: its first value. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + #[repr(u8)] + pub enum PacketType { + $( $(#[$doc])* $name = $id, )* + } + + impl PacketType { + /// Every type. + pub const ALL: &'static [PacketType] = &[$(PacketType::$name),*]; + + /// The type with this id, if there's one. + pub const fn from_id(id: u64) -> Option { + match id { + $( $id => Some(PacketType::$name), )* + _ => None, + } + } + + /// Its id. + pub const fn id(self) -> u8 { + self as u8 + } + + /// Its name: "PushMessage". + pub const fn name(self) -> &'static str { + match self { + $( PacketType::$name => stringify!($name), )* + } + } + } + + /// Any packet. + #[derive(Debug, Clone, PartialEq, Eq)] + pub enum Packet { + $( $(#[$doc])* $name($name), )* + } + + $( + impl Body for $name { + const TYPE: PacketType = PacketType::$name; + } + + impl From<$name> for Packet { + fn from(body: $name) -> Packet { + Packet::$name(body) + } + } + )* + + impl Packet { + /// Its type. + pub const fn packet_type(&self) -> PacketType { + match self { + $( Packet::$name(_) => PacketType::$name, )* + } + } + + fn check(&self) -> Result<(), DecodeError> { + match self { + $( Packet::$name(body) => body.check(), )* + } + } + } + + impl Serialize for Packet { + fn serialize(&self, serializer: S) -> Result { + match self { + $( Packet::$name(body) => (PacketType::$name.id(), body).serialize(serializer), )* + } + } + } + + impl<'de> Deserialize<'de> for Packet { + fn deserialize>(deserializer: D) -> Result { + struct PacketVisitor; + + impl<'de> Visitor<'de> for PacketVisitor { + type Value = Packet; + + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("a packet, [type, [fields...]]") + } + + fn visit_seq>(self, mut seq: A) -> Result { + let id: u64 = seq + .next_element()? + .ok_or_else(|| de::Error::invalid_length(0, &self))?; + let packet = match PacketType::from_id(id) { + $( + Some(PacketType::$name) => Packet::$name( + seq.next_element()? + .ok_or_else(|| de::Error::invalid_length(1, &self))?, + ), + )* + None => return Err(de::Error::custom(format_args!("unknown packet type {id}"))), + }; + if seq.next_element::()?.is_some() { + return Err(de::Error::invalid_length(3, &self)); + } + Ok(packet) + } + } + + deserializer.deserialize_seq(PacketVisitor) + } + } + }; +} + +packets! { + /// S→C, S→P: the server's first packet, once TLS is up. + Welcome = 1, + /// S→C, S→P: a request refused, with an error code; the connection stays. + RequestRefused = 2, + /// S→C, S→P: send the attachment's parts now. + Continue = 3, + /// C→S: stores a message, its attachment's parts after it if it has one + /// (`MessagePushed` / `RequestRefused`, `Continue` first for an attachment). + PushMessage = 4, + /// S→C, S→P: the stored message's id (the last one of a replicated batch). + MessagePushed = 5, + /// C→S: a topic/node's messages after an id, or its last ones (`Messages` / `RequestRefused`). + GetMessages = 6, + /// S→C: a run of messages. + Messages = 7, + /// C→S: a message's attachment, from a part on (`Attachment` then its parts / `RequestRefused`). + GetAttachment = 8, + /// S→C: the attachment whose parts follow. + Attachment = 9, + /// C→S, S→C, P→S: a part of an attachment, the next one. + AttachmentPart = 10, + /// C→S: every topic or node the client may see (`NamesList`). + ListNames = 11, + /// S→C: topics or nodes. + NamesList = 12, + /// C→S: read-only SQL (`QueryResult` / `RequestRefused`). + Query = 13, + /// S→C: a query's result. + QueryResult = 14, + /// P→S: what the server takes from this peer and has (`SyncState` / `RequestRefused`). + SyncStateRequest = 15, + /// S→P: what the server takes from this peer, how far it is, the attachments it lacks. + SyncState = 16, + /// P→S: messages of a topic/node the server is missing (`MessagePushed` / `RequestRefused`). + ReplicateMessages = 17, + /// P→S: an attachment the server is missing, its parts after it (`Continue`, then `MessagePushed` / `RequestRefused`). + ReplicateAttachment = 18, +} + +impl Packet { + /// It, encoded: what goes in a frame. + pub fn encode(&self) -> Vec { + rmp_serde::to_vec(self).expect("packets always serialize") + } + + /// Reads a packet, a frame's contents. See the [module](self) for what's + /// checked. + pub fn decode(bytes: &[u8]) -> Result { + // A reader that grows its buffers as the data comes, never from a + // length the packet announces. + let mut deserializer = rmp_serde::Deserializer::new(Cursor::new(bytes)); + let packet = Packet::deserialize(&mut deserializer) + .map_err(|error| DecodeError::Malformed(error.to_string()))?; + if deserializer.position() != bytes.len() as u64 { + return Err(DecodeError::TrailingBytes); + } + packet.check()?; + Ok(packet) + } +} + +// The rules fields follow, for the `Check`s. +pub(crate) mod rules { + use super::DecodeError; + use crate::limits::{MAX_MESSAGE_ID, MAX_TIMESTAMP}; + use crate::names; + + /// Fails with `rule` unless `ok`. + pub fn require(ok: bool, field: &'static str, rule: &'static str) -> Result<(), DecodeError> { + if ok { + Ok(()) + } else { + Err(DecodeError::Invalid { field, rule }) + } + } + + /// From `min` to `max`. + pub fn range(value: u64, min: u64, max: u64, field: &'static str) -> Result<(), DecodeError> { + require((min..=max).contains(&value), field, "out of range") + } + + /// At most `max` items. + pub fn most(len: usize, max: usize, field: &'static str) -> Result<(), DecodeError> { + require(len <= max, field, "too many") + } + + /// A topic or node name. + pub fn name(value: &str, field: &'static str) -> Result<(), DecodeError> { + require(names::is_valid_name(value), field, "must be a name") + } + + /// A message id: 1 and up. + pub fn message_id(value: u64, field: &'static str) -> Result<(), DecodeError> { + range(value, 1, MAX_MESSAGE_ID, field) + } + + /// When a message was pushed: milliseconds since 1970 UTC, 1 to 9999-12-31. + pub fn timestamp(value: u64, field: &'static str) -> Result<(), DecodeError> { + range(value, 1, MAX_TIMESTAMP, field) + } + + /// Strictly increasing ids. + pub fn increasing( + ids: impl Iterator, + field: &'static str, + ) -> Result<(), DecodeError> { + let mut last = 0; + for id in ids { + require(id > last, field, "ids must be strictly increasing")?; + last = id; + } + Ok(()) + } +} diff --git a/crates/bakashrot-proto/src/packets/replication.rs b/crates/bakashrot-proto/src/packets/replication.rs new file mode 100644 index 0000000..a70677f --- /dev/null +++ b/crates/bakashrot-proto/src/packets/replication.rs @@ -0,0 +1,199 @@ +//! Replication, between servers: at each check-in a peer (P) asks the +//! server (S) what it takes and has, then sends what it's missing, +//! messages first, then attachments (`OldSource/Design/Packets.md`, +//! "Replication"). Servers only ever send each other names: each has its +//! own ids. + +use super::rules; +use super::{Attachment, Check, DecodeError}; +use crate::limits::{ + MAX_ATTACHMENT_PARTS, MAX_MESSAGE_ID, MAX_MESSAGES_PER_PACKET, MAX_MISSING_ATTACHMENTS, + MAX_NAMES_LIST_ENTRIES, +}; +use crate::names; +use serde::{Deserialize, Serialize}; + +/// What the server takes from this peer, how far it is, and the +/// attachments it lacks. +/// +/// `[15, []]` +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct SyncStateRequest {} + +impl Check for SyncStateRequest {} + +/// How far the server is in a topic/node pair. +/// +/// `[topic, node, last_id]` +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Head { + /// The topic. + pub topic: String, + /// The node. + pub node: String, + /// The highest message id it has (deleted ones included). + pub last_id: u64, +} + +/// An attachment the server lacks, and where to go on from. +/// +/// `[topic, node, message_id, next_part]` +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct MissingAttachment { + /// The topic. + pub topic: String, + /// The node. + pub node: String, + /// The message. + pub message_id: u64, + /// The next part it needs (it keeps what it got). + pub next_part: u64, +} + +/// What the server takes from this peer, how far it is, and the +/// attachments it lacks: all a check-in needs. +/// +/// `[16, [[topic...], [node...], [head...], [missing...]]]` +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SyncState { + /// The topics it takes from this peer: names, and wildcards (it takes + /// the names they match, even those it doesn't have yet). + pub topics: Vec, + /// The nodes it takes from this peer, the same way. + pub nodes: Vec, + /// Its highest message id in each topic/node pair of those. + pub heads: Vec, + /// The attachments it lacks among those, `MAX_MISSING_ATTACHMENTS` at + /// most. + pub missing: Vec, +} + +impl Check for SyncState { + fn check(&self) -> Result<(), DecodeError> { + for (list, field) in [ + (&self.topics, "SyncState.topics"), + (&self.nodes, "SyncState.nodes"), + ] { + rules::most(list.len(), MAX_NAMES_LIST_ENTRIES, field)?; + for item in list { + rules::require( + names::is_valid_name_or_pattern(item), + field, + "must be a name or a pattern", + )?; + } + } + for head in &self.heads { + rules::name(&head.topic, "SyncState.heads.topic")?; + rules::name(&head.node, "SyncState.heads.node")?; + rules::range(head.last_id, 0, MAX_MESSAGE_ID, "SyncState.heads.last_id")?; + } + rules::most( + self.missing.len(), + MAX_MISSING_ATTACHMENTS, + "SyncState.missing", + )?; + for missing in &self.missing { + rules::name(&missing.topic, "SyncState.missing.topic")?; + rules::name(&missing.node, "SyncState.missing.node")?; + rules::message_id(missing.message_id, "SyncState.missing.message_id")?; + rules::range( + missing.next_part, + 0, + MAX_ATTACHMENT_PARTS - 1, + "SyncState.missing.next_part", + )?; + } + Ok(()) + } +} + +/// A message as replication carries it. +/// +/// `[id, pushed_at, data, attachment]` +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ReplicatedMessage { + /// Its id, as on its origin. + pub id: u64, + /// When it was pushed to its origin. + pub pushed_at: u64, + /// The message. + pub data: String, + /// Its attachment's size and SHA-256, if it has one: its parts come + /// later, by `ReplicateAttachment`. + pub attachment: Option, +} + +/// Messages of a topic/node pair the server is missing, in id order. +/// +/// `[17, [topic, node, [message...]]]` +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ReplicateMessages { + /// The topic. + pub topic: String, + /// The node. + pub node: String, + /// The messages, 1 to `MAX_MESSAGES_PER_PACKET`, ids strictly + /// increasing. + pub messages: Vec, +} + +impl Check for ReplicateMessages { + fn check(&self) -> Result<(), DecodeError> { + rules::name(&self.topic, "ReplicateMessages.topic")?; + rules::name(&self.node, "ReplicateMessages.node")?; + rules::require( + !self.messages.is_empty(), + "ReplicateMessages.messages", + "one at least", + )?; + rules::most( + self.messages.len(), + MAX_MESSAGES_PER_PACKET as usize, + "ReplicateMessages.messages", + )?; + rules::increasing( + self.messages.iter().map(|m| m.id), + "ReplicateMessages.messages", + )?; + for message in &self.messages { + rules::message_id(message.id, "ReplicateMessages.id")?; + rules::timestamp(message.pushed_at, "ReplicateMessages.pushed_at")?; + if let Some(attachment) = &message.attachment { + attachment.check()?; + } + } + Ok(()) + } +} + +/// An attachment the server is missing: the server answers `Continue` (or +/// refuses), the peer sends its parts from `from_part` to the last, the +/// server checks it all and answers `MessagePushed` with the message's id. +/// +/// `[18, [topic, node, message_id, from_part]]` +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ReplicateAttachment { + /// The topic. + pub topic: String, + /// The node. + pub node: String, + /// The message. + pub message_id: u64, + /// The first part sent: the `next_part` the server listed. + pub from_part: u64, +} + +impl Check for ReplicateAttachment { + fn check(&self) -> Result<(), DecodeError> { + rules::name(&self.topic, "ReplicateAttachment.topic")?; + rules::name(&self.node, "ReplicateAttachment.node")?; + rules::message_id(self.message_id, "ReplicateAttachment.message_id")?; + rules::range( + self.from_part, + 0, + MAX_ATTACHMENT_PARTS - 1, + "ReplicateAttachment.from_part", + ) + } +} diff --git a/crates/bakashrot-proto/src/packets/session.rs b/crates/bakashrot-proto/src/packets/session.rs new file mode 100644 index 0000000..4396f27 --- /dev/null +++ b/crates/bakashrot-proto/src/packets/session.rs @@ -0,0 +1,76 @@ +//! The connection itself: the server's welcome, refusals, and the go-ahead +//! for an attachment's parts. + +use super::Check; +use super::DecodeError; +use super::rules; +use crate::error::{ErrorCode, MAX_REFUSAL_CODE}; +use serde::{Deserialize, Serialize}; + +/// The server's first packet, once TLS is up and both ends' versions +/// matched (`frame::check_version()`): who this connection is, as the +/// server sees it. +/// +/// `[1, [server, node]]` +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Welcome { + /// The server's own name (its node). + pub server: String, + /// The node this connection writes as, from its certificate. + pub node: String, +} + +impl Check for Welcome { + fn check(&self) -> Result<(), DecodeError> { + rules::name(&self.server, "Welcome.server")?; + rules::name(&self.node, "Welcome.node") + } +} + +/// A request refused: the connection stays open. +/// +/// `[2, [code, reason]]` +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct RequestRefused { + /// What kind of refusal, 1-99: what clients act on. Kept as a number, + /// a newer server may send one this version doesn't know. + pub code: u32, + /// Why, for logs and people. + pub reason: String, +} + +impl RequestRefused { + /// A refusal with a known code (a refusal's, 1-99). + pub fn new(code: ErrorCode, reason: impl Into) -> Self { + debug_assert!(code.is_refusal(), "{code} isn't a refusal's code"); + RequestRefused { + code: code.code(), + reason: reason.into(), + } + } + + /// Its code, if this version knows it. + pub fn error_code(&self) -> Option { + ErrorCode::from_code(self.code) + } +} + +impl Check for RequestRefused { + fn check(&self) -> Result<(), DecodeError> { + rules::range( + self.code.into(), + 1, + MAX_REFUSAL_CODE.into(), + "RequestRefused.code", + ) + } +} + +/// Send the attachment's parts now: the answer to a `PushMessage` or a +/// `ReplicateAttachment` with an attachment, when the server takes it. +/// +/// `[3, []]` +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Continue {} + +impl Check for Continue {} diff --git a/crates/bakashrot-proto/tests/packets.rs b/crates/bakashrot-proto/tests/packets.rs new file mode 100644 index 0000000..fcd5459 --- /dev/null +++ b/crates/bakashrot-proto/tests/packets.rs @@ -0,0 +1,563 @@ +//! Every packet: round trips, the exact bytes of a few, what decoding +//! refuses, and that no input makes it panic. + +use bakashrot_proto::limits::{ + ATTACHMENT_PART_SIZE, MAX_ATTACHMENT_SIZE, MAX_MESSAGE_ID, MAX_MESSAGES_PER_PACKET, + MAX_TIMESTAMP, +}; +use bakashrot_proto::packets::*; +use bakashrot_proto::{Body, DecodeError, ErrorCode, Packet, PacketType}; + +fn message(id: u64) -> MessageEntry { + MessageEntry { + id, + pushed_at: 1_763_000_000_000 + id, + data: format!("{{\"n\":{id}}}"), + attachment: None, + } +} + +fn attachment(size: u64) -> Attachment { + Attachment { + size, + sha256: [0xab; 32], + } +} + +/// One packet of each type at least, with values at their limits here and +/// there. +fn samples() -> Vec { + vec![ + Welcome { + server: "server-1".into(), + node: "kitchen".into(), + } + .into(), + RequestRefused::new(ErrorCode::UnknownName, "Unknown topic 'nope'").into(), + Continue {}.into(), + PushMessage { + topic: "logs".into(), + data: "é€ \u{1F600} {\"a\":[1,2]}".into(), + attachment: None, + } + .into(), + PushMessage { + topic: "sensors".into(), + data: String::new(), + attachment: Some(attachment(MAX_ATTACHMENT_SIZE)), + } + .into(), + MessagePushed { + message_id: MAX_MESSAGE_ID, + } + .into(), + GetMessages { + topic: "logs".into(), + node: "kitchen".into(), + after: Some(0), + limit: MAX_MESSAGES_PER_PACKET, + } + .into(), + GetMessages { + topic: "logs".into(), + node: "kitchen".into(), + after: None, + limit: 1, + } + .into(), + Messages { + more: true, + messages: (1..=20) + .map(|i| MessageEntry { + attachment: (i % 3 == 0).then_some(StoredAttachment { + size: i, + ready: i % 2 == 0, + }), + ..message(i * 3) + }) + .collect(), + } + .into(), + Messages { + more: false, + messages: vec![], + } + .into(), + GetAttachment { + topic: "sensors".into(), + node: "kitchen".into(), + message_id: 4, + from_part: 2, + } + .into(), + attachment(2 * ATTACHMENT_PART_SIZE + 10).into(), + AttachmentPart { + data: vec![0x5a; ATTACHMENT_PART_SIZE as usize], + } + .into(), + AttachmentPart { data: vec![1] }.into(), + ListNames { + kind: NameKind::Topic, + } + .into(), + NamesList { + kind: NameKind::Node, + truncated: true, + names: vec!["kitchen".into(), "garage-1".into()], + } + .into(), + Query { + sql: "SELECT * FROM messages WHERE topic = 'logs'".into(), + } + .into(), + QueryResult { + json: r#"{"columns":["a"],"rows":[[1],[null]]}"#.into(), + } + .into(), + SyncStateRequest {}.into(), + SyncState { + topics: vec!["logs".into(), "sensors.*".into()], + nodes: vec!["*".into()], + heads: vec![ + Head { + topic: "logs".into(), + node: "kitchen".into(), + last_id: 0, + }, + Head { + topic: "sensors.a".into(), + node: "garage-1".into(), + last_id: 123_456_789, + }, + ], + missing: vec![MissingAttachment { + topic: "logs".into(), + node: "kitchen".into(), + message_id: 11, + next_part: 3, + }], + } + .into(), + ReplicateMessages { + topic: "logs".into(), + node: "kitchen".into(), + messages: vec![ + ReplicatedMessage { + id: 10, + pushed_at: 1, + data: "not JSON".into(), + attachment: None, + }, + ReplicatedMessage { + id: 11, + pushed_at: MAX_TIMESTAMP, + data: "{}".into(), + attachment: Some(attachment(5)), + }, + ], + } + .into(), + ReplicateAttachment { + topic: "logs".into(), + node: "kitchen".into(), + message_id: 11, + from_part: 3, + } + .into(), + ] +} + +/// Encodes anything serializable as a packet's body, `[type, body]`: to make +/// packets that break rules or have the wrong shape. +fn raw(packet_type: PacketType, body: impl serde::Serialize) -> Vec { + rmp_serde::to_vec(&(packet_type.id(), body)).unwrap() +} + +fn refused(bytes: &[u8]) -> DecodeError { + Packet::decode(bytes).expect_err("must be refused") +} + +fn invalid(bytes: &[u8]) -> bool { + matches!(refused(bytes), DecodeError::Invalid { .. }) +} + +fn malformed(bytes: &[u8]) -> bool { + matches!(refused(bytes), DecodeError::Malformed(_)) +} + +#[test] +fn every_type_has_a_sample() { + let samples = samples(); + for packet_type in PacketType::ALL { + assert!( + samples.iter().any(|p| p.packet_type() == *packet_type), + "no sample of {}", + packet_type.name() + ); + } + for (index, packet_type) in PacketType::ALL.iter().enumerate() { + assert_eq!( + usize::from(packet_type.id()), + index + 1, + "ids follow each other" + ); + assert_eq!( + PacketType::from_id(packet_type.id().into()), + Some(*packet_type) + ); + } +} + +#[test] +fn round_trips() { + for packet in samples() { + let bytes = packet.encode(); + assert_eq!( + Packet::decode(&bytes), + Ok(packet.clone()), + "{}", + packet.packet_type().name() + ); + assert_eq!(bytes[1], packet.packet_type().id(), "the type comes first"); + } +} + +#[test] +fn golden_bytes() { + // [4, ["logs", "{}", nil]]: what protocol.md shows. + let push = PushMessage { + topic: "logs".into(), + data: "{}".into(), + attachment: None, + }; + assert_eq!( + push.encode(), + [ + 0x92, 0x04, 0x93, 0xa4, b'l', b'o', b'g', b's', 0xa2, b'{', b'}', 0xc0 + ] + ); + assert_eq!(Continue {}.encode(), [0x92, 0x03, 0x90]); + assert_eq!( + MessagePushed { message_id: 300 }.encode(), + [0x92, 0x05, 0x91, 0xcd, 0x01, 0x2c] + ); + // Bytes are binaries, not arrays of numbers. + assert_eq!( + AttachmentPart { data: vec![7, 8] }.encode(), + [0x92, 0x0a, 0x91, 0xc4, 0x02, 7, 8] + ); + let sha = attachment(1).encode(); + assert_eq!(sha[..6], [0x92, 0x09, 0x92, 0x01, 0xc4, 0x20]); +} + +#[test] +fn every_truncation_is_refused() { + for packet in samples() { + let bytes = packet.encode(); + // The 1 MB part's prefixes are all alike past its header. + let step = if bytes.len() > 4096 { 4093 } else { 1 }; + for len in (0..bytes.len()).step_by(step) { + assert!( + Packet::decode(&bytes[..len]).is_err(), + "{} cut at {len}", + packet.packet_type().name() + ); + } + } +} + +#[test] +fn trailing_bytes_are_refused() { + for packet in samples() { + let mut bytes = packet.encode(); + bytes.push(0); + assert_eq!(Packet::decode(&bytes), Err(DecodeError::TrailingBytes)); + } +} + +#[test] +fn shapes() { + // Unknown types, not a packet. + assert!(malformed(&raw_unknown(0))); + assert!(malformed(&raw_unknown(19))); + assert!(malformed(&raw_unknown(255))); + assert!(malformed(&[0x90]), "empty"); + assert!(malformed(&[0x91, 0x05]), "no body"); + assert!(malformed(&[0x05]), "not an array"); + assert!(malformed(&[0x93, 0x03, 0x90, 0x90]), "one value too many"); + // A field missing, one too many. + assert!(malformed(&raw(PacketType::MessagePushed, ()))); + assert!(malformed(&raw(PacketType::MessagePushed, ((),)))); + assert!(malformed(&raw(PacketType::MessagePushed, (1u64, 2u64)))); + assert!(malformed(&raw(PacketType::Continue, (1u64,)))); + // The wrong types. + assert!(malformed(&raw(PacketType::MessagePushed, ("1",)))); + assert!(malformed(&raw(PacketType::MessagePushed, (-1i64,)))); + assert!(malformed(&raw( + PacketType::Messages, + (1u8, Vec::::new()) + ))); + assert!(malformed(&raw(PacketType::ListNames, (3u8,))), "kind 3"); + assert!(malformed(&raw(PacketType::ListNames, (0u8,))), "kind 0"); + assert!( + malformed(&raw( + PacketType::Attachment, + (1u64, serde_bytes::Bytes::new(&[0; 31])) + )), + "a 31-byte SHA-256" + ); + // A strings that isn't UTF-8: "ab" -> 0xc3 0x28. + let mut bytes = Query { sql: "ab".into() }.encode(); + let at = bytes.len() - 2; + bytes[at] = 0xc3; + bytes[at + 1] = 0x28; + assert!(malformed(&bytes)); + // An integer written as a signed one, still taken. + assert_eq!( + Packet::decode(&raw(PacketType::MessagePushed, (300i64,))), + Ok(MessagePushed { message_id: 300 }.into()) + ); + // A binary announcing 4 GiB: refused without allocating it. + assert!(malformed(&[ + 0x92, 0x0a, 0x91, 0xc6, 0xff, 0xff, 0xff, 0xff, 0x00 + ])); + assert!(malformed(&[ + 0x92, 0x07, 0x92, 0xc3, 0xdd, 0xff, 0xff, 0xff, 0xff + ])); +} + +fn raw_unknown(id: u8) -> Vec { + rmp_serde::to_vec(&(id, ())).unwrap() +} + +#[test] +fn ranges() { + assert!(invalid(&raw(PacketType::MessagePushed, (0u64,)))); + assert!(invalid(&raw(PacketType::MessagePushed, (1u64 << 63,)))); + // Ids end where a server's 43 bits do. + assert!(Packet::decode(&raw(PacketType::MessagePushed, (MAX_MESSAGE_ID,))).is_ok()); + assert!(invalid(&raw( + PacketType::MessagePushed, + (MAX_MESSAGE_ID + 1,) + ))); + + let refusal = |code: u32| raw(PacketType::RequestRefused, (code, "x")); + assert!( + Packet::decode(&refusal(99)).is_ok(), + "an unknown refusal code still decodes" + ); + assert!(invalid(&refusal(0))); + assert!(invalid(&refusal(100))); + + let get = |after: Option, limit: u32| { + GetMessages { + topic: "t".into(), + node: "n".into(), + after, + limit, + } + .encode() + }; + assert!(Packet::decode(&get(None, 1)).is_ok()); + assert!(invalid(&get(None, 0))); + assert!(invalid(&get(Some(0), 10_001))); + assert!(invalid(&get(Some(1 << 63), 1))); + assert!(Packet::decode(&get(Some(MAX_MESSAGE_ID), 1)).is_ok()); + assert!(invalid(&get(Some(MAX_MESSAGE_ID + 1), 1))); + + let times = |pushed_at| { + Messages { + more: false, + messages: vec![MessageEntry { + pushed_at, + ..message(1) + }], + } + .encode() + }; + assert!(Packet::decode(×(MAX_TIMESTAMP)).is_ok()); + assert!(invalid(×(0))); + assert!(invalid(×(MAX_TIMESTAMP + 1))); + + let sizes = |size| { + PushMessage { + topic: "logs".into(), + data: String::new(), + attachment: Some(attachment(size)), + } + .encode() + }; + assert!(invalid(&sizes(0))); + assert!(invalid(&sizes(MAX_ATTACHMENT_SIZE + 1))); + + let part = |len| AttachmentPart { data: vec![0; len] }.encode(); + assert!(invalid(&part(0))); + assert!(invalid(&part(ATTACHMENT_PART_SIZE as usize + 1))); +} + +#[test] +fn parts_of_an_attachment() { + let attachment = attachment(2 * ATTACHMENT_PART_SIZE + 10); + assert_eq!(attachment.part_count(), 3); + assert_eq!(attachment.part_len(0), ATTACHMENT_PART_SIZE); + assert_eq!(attachment.part_len(2), 10); + assert_eq!(attachment.part_len(3), 0); +} + +#[test] +fn ids_in_order() { + let messages = |ids: &[u64]| { + Messages { + more: false, + messages: ids.iter().map(|id| message(*id)).collect(), + } + .encode() + }; + assert!(Packet::decode(&messages(&[1, 2, 5])).is_ok()); + assert!(invalid(&messages(&[1, 1]))); + assert!(invalid(&messages(&[3, 2]))); + assert!(invalid(&messages(&[0]))); + + let replicated = |ids: &[u64]| { + ReplicateMessages { + topic: "logs".into(), + node: "kitchen".into(), + messages: ids + .iter() + .map(|id| ReplicatedMessage { + id: *id, + pushed_at: 1, + data: String::new(), + attachment: None, + }) + .collect(), + } + .encode() + }; + assert!(invalid(&replicated(&[2, 1]))); + assert!(invalid(&replicated(&[]))); +} + +#[test] +fn too_many_items() { + let too_many = Messages { + more: false, + messages: (1..=u64::from(MAX_MESSAGES_PER_PACKET) + 1) + .map(message) + .collect(), + }; + assert!(invalid(&too_many.encode())); + + let missing = SyncState { + topics: vec![], + nodes: vec![], + heads: vec![], + missing: (1..=257) + .map(|id| MissingAttachment { + topic: "t".into(), + node: "n".into(), + message_id: id, + next_part: 0, + }) + .collect(), + }; + assert!(invalid(&missing.encode())); +} + +#[test] +fn names_everywhere() { + for bad in ["12", "", "a b", "é"] { + let get = GetMessages { + topic: bad.into(), + node: "kitchen".into(), + after: None, + limit: 1, + }; + assert!(invalid(&get.encode()), "{bad:?}"); + let push = PushMessage { + topic: bad.into(), + data: String::new(), + attachment: None, + }; + assert!(invalid(&push.encode()), "{bad:?}"); + let replicate = ReplicateMessages { + topic: "logs".into(), + node: bad.into(), + messages: vec![ReplicatedMessage { + id: 1, + pushed_at: 1, + data: String::new(), + attachment: None, + }], + }; + assert!(invalid(&replicate.encode()), "{bad:?}"); + let list = NamesList { + kind: NameKind::Topic, + truncated: false, + names: vec![bad.into()], + }; + assert!(invalid(&list.encode()), "{bad:?}"); + } + + let state = |topic: &str| { + SyncState { + topics: vec![topic.into()], + nodes: vec![], + heads: vec![], + missing: vec![], + } + .encode() + }; + assert!(Packet::decode(&state("*")).is_ok()); + assert!(Packet::decode(&state("logs")).is_ok()); + assert!(invalid(&state("12"))); + assert!(invalid(&state("a b*"))); + + let welcome = Welcome { + server: "s".into(), + node: "7".into(), + }; + assert!(invalid(&welcome.encode())); +} + +/// xorshift64*, enough to make bytes that look like anything. +struct Random(u64); + +impl Random { + fn next(&mut self) -> u64 { + self.0 ^= self.0 >> 12; + self.0 ^= self.0 << 25; + self.0 ^= self.0 >> 27; + self.0.wrapping_mul(0x2545_f491_4f6c_dd1d) + } +} + +#[test] +fn nothing_makes_it_panic() { + let mut random = Random(0x9e37_79b9_7f4a_7c15); + // Random bytes, often starting like a packet. + for round in 0..200_000 { + let len = (random.next() % 48) as usize; + let mut bytes: Vec = (0..len).map(|_| random.next() as u8).collect(); + if round % 2 == 0 && bytes.len() > 2 { + bytes[0] = 0x92; + bytes[1] = 1 + (bytes[1] % 18); + bytes[2] = 0x90 | (bytes[2] & 0x0f); + } + let _ = Packet::decode(&bytes); + } + // Every sample with bytes changed here and there. + let samples: Vec> = samples() + .iter() + .map(Packet::encode) + .filter(|bytes| bytes.len() < 4096) + .collect(); + for _ in 0..50_000 { + let mut bytes = samples[(random.next() % samples.len() as u64) as usize].clone(); + for _ in 0..1 + random.next() % 3 { + let at = (random.next() % bytes.len() as u64) as usize; + bytes[at] = random.next() as u8; + } + let _ = Packet::decode(&bytes); + } +} diff --git a/crates/bakashrot-server/Cargo.toml b/crates/bakashrot-server/Cargo.toml new file mode 100644 index 0000000..e0f13d9 --- /dev/null +++ b/crates/bakashrot-server/Cargo.toml @@ -0,0 +1,33 @@ +[package] +name = "bakashrot-server" +description = "BakaShrot's server: TLS, identities from certificates, the requests of protocol 7 on the storage." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +authors.workspace = true +repository.workspace = true +publish.workspace = true + +[dependencies] +bakashrot-proto = { path = "../bakashrot-proto", features = ["tokio"] } +bakashrot-pki = { path = "../bakashrot-pki" } +bakashrot-config = { path = "../bakashrot-config" } +bakashrot-storage = { path = "../bakashrot-storage" } +tokio = { version = "1.54.1", features = ["rt-multi-thread", "net", "time", "macros", "signal", "io-util", "sync"] } +tokio-rustls = { version = "0.26.6", default-features = false } +tokio-util = { version = "0.7.20", features = ["codec"] } +futures-util = { version = "0.3.34", default-features = false, features = ["sink"] } +bytes = "1.12.1" +# The attachments' SHA-256: the TLS one's (aws-lc), no other crate. +aws-lc-rs = "1.19.0" +tracing = "0.1.44" +tracing-subscriber = { version = "0.3.23", default-features = false, features = ["fmt", "std", "ansi"] } + +[lints] +workspace = true + +[dev-dependencies] +bakashrot-client = { path = "../bakashrot-client" } +# To damage a stored attachment from a test (the storage's own version). +rusqlite = { version = "0.42.0", features = ["bundled"] } diff --git a/crates/bakashrot-server/src/accept_from.rs b/crates/bakashrot-server/src/accept_from.rs new file mode 100644 index 0000000..2a085d8 --- /dev/null +++ b/crates/bakashrot-server/src/accept_from.rs @@ -0,0 +1,218 @@ +//! Replication's receiving end: a server that dialed in sends what this +//! one lacks (`push_to.rs` is the other end). Taken only from addresses in +//! `[replication] accept_from`, and only what its roles' `accept_*` allow. + +use crate::connection::{Frames, Peer, receive_parts, refused, send}; +use crate::writer::Write; +use crate::{Shared, now}; +use bakashrot_proto::limits::{ATTACHMENT_PART_SIZE, MAX_MESSAGE_SIZE, MAX_MISSING_ATTACHMENTS}; +use bakashrot_proto::packets::{ + Attachment, Continue, MessagePushed, ReplicateAttachment, ReplicateMessages, SyncState, +}; +use bakashrot_proto::{ErrorCode, Packet}; +use bakashrot_storage::AttachmentState; +use std::net::IpAddr; +use std::sync::Arc; + +/// Whether `address` is in `accept_from`: `*`, an address as written, or +/// a hostname resolving to it (looked up now). +async fn is_accepted(shared: &Shared, address: IpAddr) -> bool { + let address = address.to_canonical(); + for host in &shared.config.replication.accept_from { + if host == "*" { + return true; + } + if let Ok(ip) = host.parse::() { + if ip.to_canonical() == address { + return true; + } + } else if let Ok(found) = tokio::net::lookup_host((host.as_str(), 0)).await + && found + .into_iter() + .any(|at| at.ip().to_canonical() == address) + { + return true; + } + } + false +} + +/// Refused unless the connection comes from `accept_from` (looked up at +/// its first replication request). +async fn check_address(shared: &Shared, peer: &mut Peer) -> Result<(), Packet> { + let accepted = match peer.accepted { + Some(accepted) => accepted, + None => *peer + .accepted + .insert(is_accepted(shared, peer.address).await), + }; + match accepted { + true => Ok(()), + false => Err(refused( + ErrorCode::NotAllowed, + format!( + "this server doesn't take replication from {} ({}): not in its accept_from", + peer.node, peer.address + ), + )), + } +} + +/// Refused unless the connection comes from `accept_from` and its roles +/// accept `node`'s messages in `topic`. +async fn check(shared: &Shared, peer: &mut Peer, topic: &str, node: &str) -> Result<(), Packet> { + check_address(shared, peer).await?; + match peer.permissions.accepts(topic, node) { + true => Ok(()), + false => Err(refused( + ErrorCode::NotAllowed, + format!("this server doesn't take {topic}:{node} from {}", peer.node), + )), + } +} + +/// What it takes from this peer, how far it is in those, and the +/// attachments it lacks among them. +pub(crate) async fn sync_state(shared: &Arc, peer: &mut Peer) -> Packet { + if let Err(refusal) = check_address(shared, peer).await { + return refusal; + } + let (topics, nodes) = peer.permissions.accepted(); + let found = shared + .read(|reader| { + Ok(( + reader.heads()?, + reader.missing_attachments(MAX_MISSING_ATTACHMENTS)?, + )) + }) + .await; + let (mut heads, mut missing) = match found { + Ok(found) => found, + Err(refusal) => return refusal.into(), + }; + heads.retain(|head| peer.permissions.accepts(&head.topic, &head.node)); + missing.retain(|missing| peer.permissions.accepts(&missing.topic, &missing.node)); + SyncState { + topics, + nodes, + heads, + missing, + } + .into() +} + +/// A batch of a topic and node's messages: stored (those past their age +/// here only counted), answered with its last id. +pub(crate) async fn replicate_messages( + shared: &Arc, + peer: &mut Peer, + batch: ReplicateMessages, +) -> Packet { + if let Err(refusal) = check(shared, peer, &batch.topic, &batch.node).await { + return refusal; + } + if let Some(big) = batch + .messages + .iter() + .find(|m| m.data.len() > MAX_MESSAGE_SIZE) + { + return refused( + ErrorCode::TooBig, + format!("message #{}: {MAX_MESSAGE_SIZE} bytes at most", big.id), + ); + } + let skip_before = shared + .config + .retention + .age(&batch.topic) + .map_or(0, |age| now().saturating_sub(age.as_millis() as u64)); + let write = Write::Replicate { + topic: batch.topic, + node: batch.node, + messages: batch.messages, + max_attachment_size: shared.config.server.max_attachment_size, + skip_before, + }; + match shared.pushes.send(write).await { + Ok(message_id) => MessagePushed { message_id }.into(), + Err(refusal) => refusal.into(), + } +} + +/// An attachment this server lacks: `Continue`, its parts from where it +/// stopped, checked with its SHA-256 (the parts it had read back for it). +/// An error closes the connection. +pub(crate) async fn replicate_attachment( + shared: &Arc, + peer: &mut Peer, + frames: &mut Frames, + request: ReplicateAttachment, +) -> Result { + if let Err(refusal) = check(shared, peer, &request.topic, &request.node).await { + return Ok(refusal); + } + let message = format!("{}:{}#{}", request.topic, request.node, request.message_id); + let ReplicateAttachment { + topic, + node, + message_id, + from_part, + } = request; + let stored = match shared + .read(move |reader| reader.attachment(&topic, &node, message_id)) + .await + { + Ok(Some(stored)) if stored.state == AttachmentState::Replicating => stored, + Ok(_) => { + return Ok(refused( + ErrorCode::NotFound, + format!("{message}: no attachment missing here"), + )); + } + Err(refusal) => return Ok(refusal.into()), + }; + let attachment = Attachment { + size: stored.size, + sha256: stored.sha256, + }; + let next = stored.received / ATTACHMENT_PART_SIZE; + if from_part != next || stored.received == stored.size { + return Ok(refused( + ErrorCode::InvalidRequest, + format!("{message}: part {next} is the next one here, not {from_part}"), + )); + } + + // The parts it has, read back for the SHA-256. + let sha256 = match shared.hash_parts(stored.id, 0..from_part).await { + Ok(sha256) => sha256, + Err(refusal) => return Ok(refusal.into()), + }; + let attachment_id = stored.id as u64; + send(frames, Continue {}.into()) + .await + .map_err(|error| error.to_string())?; + let refusal = receive_parts( + shared, + frames, + attachment_id, + &attachment, + from_part, + sha256, + ) + .await?; + if let Some(refusal) = &refusal + && refusal.code != ErrorCode::DataMismatch.code() + { + // A part not written: it goes on from there next time. + return Ok(refusal.clone().into()); + } + let finish = Write::FinishReplicated { + attachment: attachment_id, + matches: refusal.is_none(), + }; + Ok(match (shared.pushes.send(finish).await, refusal) { + (Err(refusal), _) | (Ok(_), Some(refusal)) => refusal.into(), + (Ok(_), None) => MessagePushed { message_id }.into(), + }) +} diff --git a/crates/bakashrot-server/src/connection.rs b/crates/bakashrot-server/src/connection.rs new file mode 100644 index 0000000..fbfd823 --- /dev/null +++ b/crates/bakashrot-server/src/connection.rs @@ -0,0 +1,543 @@ +//! One connection: TLS, the versions, who it is, then its requests, one at +//! a time (`docs/protocol.md`). + +use crate::writer::Write; +use crate::{Shared, accept_from, now}; +use aws_lc_rs::digest; +use bakashrot_config::Permissions; +use bakashrot_pki::Identity; +use bakashrot_proto::limits::{MAX_MESSAGE_SIZE, MAX_NAMES_LIST_ENTRIES, MAX_PACKET_SIZE}; +use bakashrot_proto::names::names_equal; +use bakashrot_proto::packets::{ + Attachment, AttachmentPart, Continue, GetAttachment, GetMessages, ListNames, MessagePushed, + Messages, NameKind, NamesList, PushMessage, Query, QueryResult, RequestRefused, Welcome, +}; +use bakashrot_proto::{ErrorCode, Packet, frame}; +use bakashrot_storage::AttachmentState; +use futures_util::{SinkExt, StreamExt}; +use std::collections::VecDeque; +use std::net::{IpAddr, SocketAddr}; +use std::sync::Arc; +use std::time::Duration; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::TcpStream; +use tokio::time::timeout; +use tokio_rustls::server::TlsStream; +use tokio_util::codec::{Framed, LengthDelimitedCodec}; +use tracing::{debug, info}; + +/// How long TLS and the versions may take. +const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10); + +/// How long a connection may stay silent between requests. +const IDLE_TIMEOUT: Duration = Duration::from_secs(300); + +/// How long an attachment's next part may take to come. +const PART_TIMEOUT: Duration = Duration::from_secs(30); + +/// An upload's parts given to the writer and not written yet, at most: the +/// next ones wait (the client with them, through TCP). +const PARTS_IN_FLIGHT: usize = 4; + +pub(crate) type Frames = Framed, LengthDelimitedCodec>; + +/// Serves one connection until it ends, logging why. +pub(crate) async fn handle(shared: Arc, tcp: TcpStream, peer: SocketAddr) { + match serve(&shared, tcp, peer.ip()).await { + Ok(node) => debug!("{peer} ({node}): closed"), + Err(why) => info!("{peer}: {why}"), + } +} + +/// Who it is once checked: its node, its certificate's serial (for later +/// revocations), what it may do, where it connects from. +pub(crate) struct Peer { + pub(crate) node: String, + serial: Vec, + pub(crate) permissions: Permissions, + pub(crate) address: IpAddr, + /// Whether `accept_from` has it, once a replication request asked. + pub(crate) accepted: Option, +} + +async fn serve(shared: &Arc, tcp: TcpStream, address: IpAddr) -> Result { + tcp.set_nodelay(true).map_err(|error| error.to_string())?; + let (mut frames, mut peer) = timeout(HANDSHAKE_TIMEOUT, open(shared, tcp, address)) + .await + .map_err(|_| "too slow to connect".to_owned())??; + debug!("{} connected", peer.node); + + loop { + let bytes = match timeout(IDLE_TIMEOUT, frames.next()).await { + Err(_) => return Err(format!("{}: idle too long", peer.node)), + Ok(None) => return Ok(peer.node), + // Closed without TLS's close_notify: how the tools, the DLL and + // a killed process leave (a request cut short isn't run). + Ok(Some(Err(error))) if error.kind() == std::io::ErrorKind::UnexpectedEof => { + return Ok(peer.node); + } + Ok(Some(bytes)) => bytes.map_err(|error| format!("{}: {error}", peer.node))?, + }; + let revoked = shared + .revocations + .read() + .map_or(true, |revocations| revocations.revokes_serial(&peer.serial)); + if revoked { + return Err(format!("{}: its certificate was revoked", peer.node)); + } + let packet = Packet::decode(&bytes).map_err(|error| format!("{}: {error}", peer.node))?; + let failed = |why: String| format!("{}: {why}", peer.node); + let answer = match packet { + Packet::PushMessage(push) => self::push(shared, &peer, &mut frames, push) + .await + .map_err(failed)?, + Packet::GetAttachment(get) => { + match get_attachment(shared, &peer, &mut frames, get) + .await + .map_err(failed)? + { + Some(refusal) => refusal, + None => continue, + } + } + Packet::GetMessages(get) => get_messages(shared, &peer, get).await, + Packet::ListNames(list) => list_names(shared, &peer, list).await, + Packet::Query(query) => self::query(shared, &peer, query).await, + Packet::SyncStateRequest(_) => accept_from::sync_state(shared, &mut peer).await, + Packet::ReplicateMessages(batch) => { + accept_from::replicate_messages(shared, &mut peer, batch).await + } + Packet::ReplicateAttachment(request) => { + accept_from::replicate_attachment(shared, &mut peer, &mut frames, request) + .await + .map_err(|why| format!("{}: {why}", peer.node))? + } + other => { + return Err(format!( + "{}: sent {}, not a request", + peer.node, + other.packet_type().name() + )); + } + }; + send(&mut frames, answer) + .await + .map_err(|error| format!("{}: {error}", peer.node))?; + } +} + +/// After a refused handshake (its alert sent): a close the client reads, +/// not a reset that can beat the alert to it. In TLS 1.3 the client has +/// already sent its version when the server refuses its certificate, and +/// a socket closed with data unread is reset (Windows drops what the +/// client hadn't read yet then). So: shut down, and read until the client +/// closes, 1 s at most. +async fn close_gently(mut tcp: TcpStream) { + let _ = tcp.shutdown().await; + let mut unread = [0; 1024]; + let _ = timeout(Duration::from_secs(1), async { + while tcp.read(&mut unread).await.is_ok_and(|read| read > 0) {} + }) + .await; +} + +/// TLS, the versions, the identity, the welcome (or the refusal). +async fn open( + shared: &Arc, + tcp: TcpStream, + address: IpAddr, +) -> Result<(Frames, Peer), String> { + let mut stream = match shared.acceptor.accept(tcp).into_fallible().await { + Ok(stream) => stream, + Err((error, tcp)) => { + close_gently(tcp).await; + return Err(format!("TLS: {error}")); + } + }; + + stream + .write_all(&frame::version_bytes()) + .await + .map_err(|error| error.to_string())?; + stream.flush().await.map_err(|error| error.to_string())?; + let mut theirs = [0; frame::VERSION_SIZE]; + stream + .read_exact(&mut theirs) + .await + .map_err(|error| error.to_string())?; + frame::check_version(theirs).map_err(|version| format!("speaks protocol {version}"))?; + + let (_, connection) = stream.get_ref(); + let certificate = connection + .peer_certificates() + .and_then(<[_]>::first) + .map(|certificate| certificate.to_vec()) + .unwrap_or_default(); + let identity = Identity::from_certificate(&certificate).map_err(|error| error.to_string())?; + let serial = bakashrot_pki::serial(&certificate).map_err(|error| error.to_string())?; + let mut frames = Framed::new(stream, frame::codec(MAX_PACKET_SIZE)); + + let Some(permissions) = shared.config.permissions(&identity.roles) else { + let refused = RequestRefused::new( + ErrorCode::NotAllowed, + format!( + "none of {}'s roles ({}) is allowed on this server", + identity.name, + identity.roles.join(", ") + ), + ); + let _ = send(&mut frames, refused.into()).await; + return Err(format!( + "{}: refused, none of its roles is allowed", + identity.name + )); + }; + let welcome = Welcome { + server: shared.name.clone(), + node: identity.name.clone(), + }; + send(&mut frames, welcome.into()) + .await + .map_err(|error| error.to_string())?; + Ok(( + frames, + Peer { + node: identity.name, + serial, + permissions, + address, + accepted: None, + }, + )) +} + +/// A push, with its attachment's parts if it has one. An error closes the +/// connection. +async fn push( + shared: &Arc, + peer: &Peer, + frames: &mut Frames, + push: PushMessage, +) -> Result { + if !shared.config.server.has_topic(&push.topic) { + return Ok(refused( + ErrorCode::UnknownName, + format!("unknown topic '{}'", push.topic), + )); + } + if !peer.permissions.can_push(&push.topic) { + return Ok(refused( + ErrorCode::NotAllowed, + format!("{} may not push to '{}'", peer.node, push.topic), + )); + } + if push.data.len() > MAX_MESSAGE_SIZE { + return Ok(refused( + ErrorCode::TooBig, + format!( + "a message of {} bytes: {MAX_MESSAGE_SIZE} at most", + push.data.len() + ), + )); + } + let PushMessage { + topic, + data, + attachment, + } = push; + let Some(attachment) = attachment else { + let write = Write::Push { + topic, + node: peer.node.clone(), + pushed_at: now(), + data, + }; + return Ok(pushed(shared.pushes.send(write).await)); + }; + + let max = shared.config.server.max_attachment_size; + if attachment.size > max { + return Ok(refused( + ErrorCode::TooBig, + format!( + "an attachment of {} bytes: {max} at most on this server", + attachment.size + ), + )); + } + let start = Write::StartUpload { + size: attachment.size, + sha256: attachment.sha256, + }; + let upload = match shared.pushes.send(start).await { + Ok(upload) => upload, + Err(refusal) => return Ok(refusal.into()), + }; + let sha256 = digest::Context::new(&digest::SHA256); + let received = match send(frames, Continue {}.into()).await { + Ok(()) => receive_parts(shared, frames, upload, &attachment, 0, sha256).await, + Err(error) => Err(error.to_string()), + }; + let refusal = match received { + Ok(None) => { + let write = Write::PushWithUpload { + upload, + topic, + node: peer.node.clone(), + pushed_at: now(), + data, + }; + match shared.pushes.send(write).await { + Ok(message_id) => return Ok(MessagePushed { message_id }.into()), + Err(refusal) => Ok(refusal), + } + } + Ok(Some(refusal)) => Ok(refusal), + Err(why) => Err(why), + }; + // Not pushed: the upload goes (queued after its parts). + drop(shared.pushes.send(Write::CancelUpload { upload })); + refusal.map(Packet::from) +} + +/// Reads an attachment's parts from `from_part` on (an upload's, or a +/// replicated one's), has the writer store them while the next ones come, +/// checks the SHA-256 (`sha256` has the parts before): the refusal if one +/// is due (the parts all read even then; `DataMismatch` for the SHA-256), +/// an error if the connection must close. +pub(crate) async fn receive_parts( + shared: &Arc, + frames: &mut Frames, + upload: u64, + attachment: &Attachment, + from_part: u64, + mut sha256: digest::Context, +) -> Result, String> { + let mut writing = VecDeque::new(); + let mut refusal = None; + for part in from_part..attachment.part_count() { + let bytes = match timeout(PART_TIMEOUT, frames.next()).await { + Err(_) => return Err(format!("part {part} of an attachment: too slow")), + Ok(None) => return Err(format!("closed at part {part} of an attachment")), + Ok(Some(bytes)) => bytes.map_err(|error| error.to_string())?, + }; + let Packet::AttachmentPart(AttachmentPart { data }) = + Packet::decode(&bytes).map_err(|error| error.to_string())? + else { + return Err(format!( + "sent something else than part {part} of an attachment" + )); + }; + if refusal.is_some() { + continue; + } + let expected = attachment.part_len(part); + if data.len() as u64 != expected { + refusal = Some(RequestRefused::new( + ErrorCode::InvalidRequest, + format!("part {part}: {} bytes, {expected} expected", data.len()), + )); + continue; + } + sha256.update(&data); + writing.push_back(shared.pushes.send(Write::Part { upload, part, data })); + if writing.len() >= PARTS_IN_FLIGHT + && let Some(written) = writing.pop_front() + && let Err(refused) = written.await + { + refusal = Some(refused); + } + } + for written in writing { + if let Err(refused) = written.await { + refusal.get_or_insert(refused); + } + } + if refusal.is_none() && sha256.finish().as_ref() != attachment.sha256 { + refusal = Some(RequestRefused::new( + ErrorCode::DataMismatch, + "the attachment doesn't match its SHA-256", + )); + } + Ok(refusal) +} + +/// A message's attachment: its size and SHA-256, then its parts from +/// `from_part`, sent here; or the refusal to send. An error (a part that +/// can't be read, the connection) closes the connection: the client asks +/// again from the part it lacks. +async fn get_attachment( + shared: &Arc, + peer: &Peer, + frames: &mut Frames, + get: GetAttachment, +) -> Result, String> { + if !peer.permissions.can_read(&get.topic) { + return Ok(Some(refused( + ErrorCode::NotAllowed, + format!("{} may not read '{}'", peer.node, get.topic), + ))); + } + if !shared.config.server.has_topic(&get.topic) { + return Ok(Some(refused( + ErrorCode::UnknownName, + format!("unknown topic '{}'", get.topic), + ))); + } + let message = format!("{}:{}#{}", get.topic, get.node, get.message_id); + let GetAttachment { + topic, + node, + message_id, + from_part, + } = get; + let found = shared + .read(move |reader| reader.attachment(&topic, &node, message_id)) + .await; + let stored = match found { + Ok(Some(stored)) => stored, + Ok(None) => { + return Ok(Some(refused( + ErrorCode::NotFound, + format!("no attachment for {message}"), + ))); + } + Err(refusal) => return Ok(Some(refusal.into())), + }; + let not_here = match stored.state { + AttachmentState::Ready => None, + AttachmentState::TooBig => Some(( + ErrorCode::TooBig, + "bigger than this server keeps: get it from another one", + )), + AttachmentState::Replicating => Some((ErrorCode::NotReady, "isn't on this server yet")), + AttachmentState::Uploading | AttachmentState::Deleting => { + Some((ErrorCode::NotFound, "isn't there any more")) + } + }; + if let Some((code, why)) = not_here { + return Ok(Some(refused( + code, + format!("the attachment of {message} {why}"), + ))); + } + let attachment = Attachment { + size: stored.size, + sha256: stored.sha256, + }; + let count = attachment.part_count(); + if from_part >= count { + return Ok(Some(refused( + ErrorCode::InvalidRequest, + format!("from part {from_part}: the attachment of {message} has {count}"), + ))); + } + send(frames, attachment.into()) + .await + .map_err(|error| error.to_string())?; + for part in from_part..count { + let data = shared + .read(move |reader| reader.read_part(stored.id, part)) + .await + .map_err(|refusal| format!("part {part} of {message}: {}", refusal.reason))?; + send(frames, AttachmentPart { data }.into()) + .await + .map_err(|error| error.to_string())?; + } + Ok(None) +} + +/// A push's answer. +fn pushed(outcome: crate::writer::Outcome) -> Packet { + match outcome { + Ok(message_id) => MessagePushed { message_id }.into(), + Err(refusal) => refusal.into(), + } +} + +async fn get_messages(shared: &Arc, peer: &Peer, get: GetMessages) -> Packet { + if !peer.permissions.can_read(&get.topic) { + return refused( + ErrorCode::NotAllowed, + format!("{} may not read '{}'", peer.node, get.topic), + ); + } + if !shared.config.server.has_topic(&get.topic) { + return refused( + ErrorCode::UnknownName, + format!("unknown topic '{}'", get.topic), + ); + } + let GetMessages { + topic, + node, + after, + limit, + } = get; + // Its own node is known even before its first push. + let own = names_equal(&node, &peer.node); + match shared + .read(move |reader| reader.messages(&topic, &node, after, limit)) + .await + { + Ok(messages) => messages.into(), + Err(refused) if own && refused.code == ErrorCode::UnknownName.code() => Messages { + more: false, + messages: Vec::new(), + } + .into(), + Err(refused) => refused.into(), + } +} + +/// Topics: the server's, those it may push to or read unless it may query +/// (queries read everything). Nodes: every one with messages. +async fn list_names(shared: &Arc, peer: &Peer, list: ListNames) -> Packet { + let mut names = match list.kind { + NameKind::Topic => shared + .config + .server + .topics + .iter() + .filter(|topic| { + peer.permissions.can_query() + || peer.permissions.can_push(topic) + || peer.permissions.can_read(topic) + }) + .cloned() + .collect(), + NameKind::Node => match shared.read(|reader| reader.nodes()).await { + Ok(nodes) => nodes, + Err(refused) => return refused.into(), + }, + }; + let truncated = names.len() > MAX_NAMES_LIST_ENTRIES; + names.truncate(MAX_NAMES_LIST_ENTRIES); + NamesList { + kind: list.kind, + truncated, + names, + } + .into() +} + +async fn query(shared: &Arc, peer: &Peer, query: Query) -> Packet { + if !peer.permissions.can_query() { + return refused( + ErrorCode::NotAllowed, + format!("{} may not run queries", peer.node), + ); + } + match shared.query(query.sql).await { + Ok(json) => QueryResult { json }.into(), + Err(refused) => refused.into(), + } +} + +pub(crate) fn refused(code: ErrorCode, reason: String) -> Packet { + RequestRefused::new(code, reason).into() +} + +pub(crate) async fn send(frames: &mut Frames, packet: Packet) -> std::io::Result<()> { + frames.send(bytes::Bytes::from(packet.encode())).await +} diff --git a/crates/bakashrot-server/src/lib.rs b/crates/bakashrot-server/src/lib.rs new file mode 100644 index 0000000..d8625f2 --- /dev/null +++ b/crates/bakashrot-server/src/lib.rs @@ -0,0 +1,316 @@ +//! BakaShrot's server: takes TLS connections from the CA's clients and +//! peers, knows each by its certificate (its node, its roles), and answers +//! their requests from the database. +//! +//! - [`Server::start`]: reads the certificates, opens the database, starts +//! the writer's thread. +//! - [`Server::serve`]: takes connections, a task each +//! (`connection.rs`); pushes go to the writer's thread (`writer.rs`), +//! reads and queries to pools of connections. +//! - [`Server::watch_revocations`]: reloads the CRL file when it changes; +//! a revoked certificate's connection is dropped at its next request. +//! - [`Server::apply_retention`]: deletes messages past their topic's age +//! (`retention.rs`). +//! - [`Server::replicate`]: sends what the servers of `push_to` lack +//! (`push_to.rs`); those dialing in, if in `accept_from`, are answered +//! by `accept_from.rs`. +//! - [`Server::stop`]: commits what was queued for the writer, refuses +//! the rest. + +mod accept_from; +mod connection; +mod push_to; +mod retention; +mod writer; + +use bakashrot_config::Config; +use bakashrot_pki::{Revocations, SharedRevocations, summarize, tls}; +use bakashrot_proto::ErrorCode; +use bakashrot_proto::packets::RequestRefused; +use bakashrot_storage::{Database, QueryRunner, Reader}; +use std::net::SocketAddr; +use std::path::Path; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; +use tokio::net::TcpListener; +use tokio_rustls::{TlsAcceptor, TlsConnector}; +use tracing::{info, warn}; +use writer::Pushes; + +/// How often the CRL file is looked at. +const CRL_POLL: Duration = Duration::from_secs(5); + +/// How often the WAL is checkpointed. +const CHECKPOINT_INTERVAL: Duration = Duration::from_secs(1); + +/// A server, ready to take connections. +#[derive(Clone)] +pub struct Server { + shared: Arc, +} + +/// What every connection uses. +struct Shared { + config: Config, + /// The server's own name: its certificate's. + name: String, + acceptor: TlsAcceptor, + /// To dial the servers of `push_to`. + connector: TlsConnector, + revocations: SharedRevocations, + /// The CA's certificate, to check CRLs with. + ca: String, + database: Database, + pushes: Pushes, + /// Read connections not in use. + readers: Mutex>, + /// Query connections not in use. + queries: Mutex>, +} + +impl Server { + /// Reads the server's certificates and CRL, opens its database, starts + /// its writer. Errors say which file and why. + pub fn start(config: Config) -> Result { + let server = &config.server; + let ca = read(&server.ca)?; + let certificate = read(&server.certificate)?; + let key = read(&server.key)?; + let name = summarize(&certificate) + .ok() + .and_then(|summary| summary.identity) + .map(|identity| identity.name) + .ok_or_else(|| { + format!( + "{}: not a BakaShrot certificate", + server.certificate.display() + ) + })?; + let revocations = load_revocations(server.crl.as_deref(), &ca)?.shared(); + let tls = tls::server_config(&ca, &certificate, &key, revocations.clone()) + .map_err(|error| format!("the server's TLS: {error}"))?; + let dialing = tls::client_config(&ca, &certificate, &key, revocations.clone()) + .map_err(|error| format!("the TLS to peers: {error}"))?; + let database = Database::open(&server.database, server.synchronous) + .map_err(|error| error.to_string())?; + let pushes = Pushes::start(database.writer().map_err(|error| error.to_string())?) + .map_err(|error| format!("the writer's thread: {error}"))?; + start_checkpoints(&database)?; + Ok(Server { + shared: Arc::new(Shared { + name, + acceptor: TlsAcceptor::from(tls), + connector: TlsConnector::from(dialing), + revocations, + ca, + database, + pushes, + readers: Mutex::new(Vec::new()), + queries: Mutex::new(Vec::new()), + config, + }), + }) + } + + /// The server's name: its certificate's. + pub fn name(&self) -> &str { + &self.shared.name + } + + /// Where the config says to listen. + pub fn listen(&self) -> SocketAddr { + self.shared.config.server.listen + } + + /// Takes connections on `listener`, each in a task of its own, until + /// the listener fails. + pub async fn serve(&self, listener: TcpListener) -> std::io::Result<()> { + loop { + let (tcp, peer) = listener.accept().await?; + tokio::spawn(connection::handle(self.shared.clone(), tcp, peer)); + } + } + + /// Reloads the CRL file whenever it changes (its time or size, looked + /// at every few seconds). A CRL that can't be read or isn't the CA's is + /// refused: the previous one stays. Never returns. + pub async fn watch_revocations(&self) { + let Some(path) = self.shared.config.server.crl.clone() else { + return std::future::pending().await; + }; + let mut seen = stamp(&path); + loop { + tokio::time::sleep(CRL_POLL).await; + let now = stamp(&path); + if now != seen { + seen = now; + match self.reload_revocations() { + Ok(count) => info!("{}: reloaded, {count} revoked", path.display()), + Err(error) => warn!("{error}: the previous CRL stays"), + } + } + } + } + + /// Deletes each topic's messages past its age (`[retention]`), then + /// their attachments: right away, then every `retention_interval`. + /// Never returns. + pub async fn apply_retention(&self) { + retention::run(&self.shared).await + } + + /// Keeps a link to each server of `[replication] push_to`, sending + /// each what it lacks (again at once after sending, after `sync_interval` + /// when there was nothing). Never returns. + pub async fn replicate(&self) { + push_to::run(self.shared.clone()).await + } + + /// Stops writing: every write queued before is committed (and so + /// answered), the ones after are refused (`ServerError`, the server + /// stopping). Then the server can be dropped, its runtime stopped. + pub async fn stop(&self) { + self.shared.pushes.stop().await; + } + + /// Reloads the CRL file now: how many certificates it revokes. + pub fn reload_revocations(&self) -> Result { + let shared = &self.shared; + let revocations = load_revocations(shared.config.server.crl.as_deref(), &shared.ca)?; + let count = revocations.len(); + // A poisoned lock: the TLS checks refuse everyone, replace it all. + match shared.revocations.write() { + Ok(mut current) => *current = revocations, + Err(poisoned) => *poisoned.into_inner() = revocations, + } + Ok(count) + } +} + +impl Shared { + /// Runs `read` on a read connection, off the async threads. + async fn read( + self: &Arc, + read: impl FnOnce(&Reader) -> bakashrot_storage::Result + Send + 'static, + ) -> Result { + self.pooled(|shared| &shared.readers, Database::reader, read) + .await + } + + /// The SHA-256 of an attachment's stored `parts`, read back one at a + /// time (to go on with more, or to compare). + async fn hash_parts( + self: &Arc, + attachment_id: i64, + parts: std::ops::Range, + ) -> Result { + let mut sha256 = aws_lc_rs::digest::Context::new(&aws_lc_rs::digest::SHA256); + for part in parts { + let data = self + .read(move |reader| reader.read_part(attachment_id, part)) + .await?; + sha256.update(&data); + } + Ok(sha256) + } + + /// Runs a client's SQL on a query connection, off the async threads. + async fn query(self: &Arc, sql: String) -> Result { + self.pooled( + |shared| &shared.queries, + Database::query_runner, + move |runner: &QueryRunner| runner.run(&sql), + ) + .await + } + + /// Runs `work` on an idle connection of `pool`, or a new one, then + /// puts it back. + async fn pooled( + self: &Arc, + pool: fn(&Shared) -> &Mutex>, + open: fn(&Database) -> bakashrot_storage::Result, + work: impl FnOnce(&C) -> bakashrot_storage::Result + Send + 'static, + ) -> Result { + let shared = self.clone(); + tokio::task::spawn_blocking(move || { + let idle = pool(&shared).lock().ok().and_then(|mut idle| idle.pop()); + let connection = match idle { + Some(connection) => connection, + None => open(&shared.database).map_err(refusal)?, + }; + let value = work(&connection).map_err(refusal); + if let Ok(mut idle) = pool(&shared).lock() { + idle.push(connection); + } + value + }) + .await + .unwrap_or_else(|_| Err(server_error("a read failed"))) + } +} + +/// Checkpoints the WAL every second, on a thread and a connection of its +/// own, so the writer doesn't do it in the middle of a commit (2.5 times +/// the pushes: `docs/storage.md`, "Against the old storage"). +fn start_checkpoints(database: &Database) -> Result<(), String> { + let checkpointer = database.checkpointer().map_err(|error| error.to_string())?; + std::thread::Builder::new() + .name("checkpoints".into()) + .spawn(move || { + loop { + std::thread::sleep(CHECKPOINT_INTERVAL); + if let Err(error) = checkpointer.checkpoint() { + warn!("checkpointing the database: {error}"); + } + } + }) + .map(|_| ()) + .map_err(|error| format!("the checkpoints' thread: {error}")) +} + +/// A storage error as the refusal clients get. +fn refusal(error: bakashrot_storage::Error) -> RequestRefused { + use bakashrot_storage::Error; + let code = match &error { + Error::Invalid(_) => ErrorCode::InvalidRequest, + Error::NotFound(_) => ErrorCode::NotFound, + Error::UnknownName(_) => ErrorCode::UnknownName, + Error::TooBig(_) => ErrorCode::TooBig, + Error::Query(_) => ErrorCode::QueryFailed, + Error::Sqlite(_) | Error::Unusable(_) => { + warn!("the database: {error}"); + return server_error("the database failed"); + } + }; + RequestRefused::new(code, error.to_string()) +} + +fn server_error(reason: &str) -> RequestRefused { + RequestRefused::new(ErrorCode::ServerError, reason) +} + +fn read(path: &Path) -> Result { + std::fs::read_to_string(path).map_err(|error| format!("{}: {error}", path.display())) +} + +/// The CRL file's revocations; none without one (no file, or not set). +fn load_revocations(path: Option<&Path>, ca: &str) -> Result { + let Some(path) = path.filter(|path| path.exists()) else { + return Ok(Revocations::none()); + }; + Revocations::load(&read(path)?, ca).map_err(|error| format!("{}: {error}", path.display())) +} + +/// Now, in ms since 1970 UTC: when a message is pushed. +fn now() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |since| since.as_millis() as u64) +} + +/// A file's time and size, to see it changed. +fn stamp(path: &Path) -> Option<(SystemTime, u64)> { + let metadata = std::fs::metadata(path).ok()?; + Some((metadata.modified().ok()?, metadata.len())) +} diff --git a/crates/bakashrot-server/src/main.rs b/crates/bakashrot-server/src/main.rs new file mode 100644 index 0000000..6315b28 --- /dev/null +++ b/crates/bakashrot-server/src/main.rs @@ -0,0 +1,95 @@ +//! `bakashrot-server `: runs a server until it's told to stop +//! (SIGTERM or SIGINT on Linux; Ctrl+C, Ctrl+Break or its console closed +//! on Windows), then stops cleanly: what was queued for the database is +//! committed first. +//! +//! Logs go to the console (stdout), `BAKASHROT_LOG` sets their level +//! (`error`, `warn`, `info` by default, `debug`, `trace`). + +use bakashrot_config::Config; +use bakashrot_server::Server; +use std::io::IsTerminal; +use std::path::PathBuf; +use std::process::ExitCode; +use tokio::net::TcpListener; +use tracing::level_filters::LevelFilter; +use tracing::{error, info}; + +#[tokio::main] +async fn main() -> ExitCode { + let level = std::env::var("BAKASHROT_LOG").ok(); + let filter = level.as_deref().map_or(Ok(LevelFilter::INFO), str::parse); + tracing_subscriber::fmt() + .with_target(false) + .with_max_level(*filter.as_ref().unwrap_or(&LevelFilter::INFO)) + // No colour codes in a file or a journal. + .with_ansi(std::io::stdout().is_terminal()) + .init(); + if filter.is_err() { + error!("BAKASHROT_LOG: not a level (error, warn, info, debug, trace), logging info"); + } + let Some(path) = std::env::args_os().nth(1).map(PathBuf::from) else { + eprintln!("usage: bakashrot-server "); + return ExitCode::from(2); + }; + match run(&path).await { + Ok(()) => ExitCode::SUCCESS, + Err(why) => { + error!("{why}"); + ExitCode::FAILURE + } + } +} + +async fn run(path: &std::path::Path) -> Result<(), String> { + let config = Config::load(path).map_err(|error| error.to_string())?; + let server = Server::start(config)?; + let listener = TcpListener::bind(server.listen()) + .await + .map_err(|error| format!("listening on {}: {error}", server.listen()))?; + info!("{} listening on {}", server.name(), server.listen()); + let outcome = tokio::select! { + served = server.serve(listener) => served.map_err(|error| format!("accepting: {error}")), + _ = server.watch_revocations() => Ok(()), + _ = server.apply_retention() => Ok(()), + _ = server.replicate() => Ok(()), + signal = stop_signal() => { + info!("{}, stopping", signal?); + Ok(()) + } + }; + server.stop().await; + info!("stopped"); + outcome +} + +/// The first stop signal: its name. +#[cfg(unix)] +async fn stop_signal() -> Result<&'static str, String> { + use tokio::signal::unix::{SignalKind, signal}; + let listen = |kind| signal(kind).map_err(|error| format!("listening for signals: {error}")); + let (mut terminate, mut interrupt) = ( + listen(SignalKind::terminate())?, + listen(SignalKind::interrupt())?, + ); + Ok(tokio::select! { + _ = terminate.recv() => "SIGTERM", + _ = interrupt.recv() => "SIGINT", + }) +} + +/// The first stop signal: its name. Closing the console leaves a few +/// seconds before Windows ends the process, enough to commit. +#[cfg(windows)] +async fn stop_signal() -> Result<&'static str, String> { + use tokio::signal::windows; + let failed = |error: std::io::Error| format!("listening for Ctrl+C: {error}"); + let mut c = windows::ctrl_c().map_err(failed)?; + let mut r#break = windows::ctrl_break().map_err(failed)?; + let mut close = windows::ctrl_close().map_err(failed)?; + Ok(tokio::select! { + _ = c.recv() => "Ctrl+C", + _ = r#break.recv() => "Ctrl+Break", + _ = close.recv() => "the console closed", + }) +} diff --git a/crates/bakashrot-server/src/push_to.rs b/crates/bakashrot-server/src/push_to.rs new file mode 100644 index 0000000..5a66e3a --- /dev/null +++ b/crates/bakashrot-server/src/push_to.rs @@ -0,0 +1,351 @@ +//! Replication's sending end: a link to each server of +//! `[replication] push_to`, kept up (dialed again after `retry_delay`). +//! It checks in: asks what the other server takes and has (`SyncState`), +//! sends the messages it lacks, by topic and node name, then the +//! attachments it lacks; again at once if it sent any (it keeps up under +//! load), after `sync_interval` otherwise. Only what the other server's roles' +//! `send_*` allow. `accept_from.rs` is the other end. + +use crate::Shared; +use crate::writer::Write; +use bakashrot_config::Permissions; +use bakashrot_pki::tls; +use bakashrot_proto::limits::{ALPN, MAX_PACKET_SIZE}; +use bakashrot_proto::names::{names_equal, pattern_matches}; +use bakashrot_proto::packets::{ + Attachment, AttachmentPart, MissingAttachment, ReplicateAttachment, ReplicateMessages, + SyncState, SyncStateRequest, +}; +use bakashrot_proto::{ErrorCode, Packet, frame}; +use bakashrot_storage::AttachmentState; +use futures_util::{SinkExt, StreamExt}; +use std::collections::HashMap; +use std::sync::Arc; +use std::time::Duration; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::TcpStream; +use tokio::task::JoinSet; +use tokio::time::{sleep, timeout}; +use tokio_rustls::client::TlsStream; +use tokio_util::codec::{Framed, LengthDelimitedCodec}; +use tracing::{debug, info, warn}; + +/// How long connecting may take: TCP, TLS, the versions, the welcome. +const CONNECT_TIMEOUT: Duration = Duration::from_secs(10); + +/// How long an answer may take. +const ANSWER_TIMEOUT: Duration = Duration::from_secs(30); + +/// Keeps a link to each server of `push_to`. Never returns. +pub(crate) async fn run(shared: Arc) { + let mut links = JoinSet::new(); + for address in &shared.config.replication.push_to { + links.spawn(keep_linked(shared.clone(), address.clone())); + } + while links.join_next().await.is_some() {} + std::future::pending().await +} + +/// Links to `address`, checks in until the link fails, then again after +/// `retry_delay`. A failure is logged once until it changes. +async fn keep_linked(shared: Arc, address: String) { + let replication = &shared.config.replication; + let mut last_failure = String::new(); + loop { + let failure = match Link::open(&shared, &address).await { + Ok(mut link) => { + info!("{address}: linked to {}", link.name); + last_failure.clear(); + loop { + match link.check_in(&shared).await { + Ok(true) => {} + Ok(false) => sleep(replication.sync_interval).await, + Err(why) => break format!("{} ({address}): {why}", link.name), + } + } + } + Err(why) => format!("{address}: {why}"), + }; + if failure != last_failure { + warn!("{failure}"); + last_failure = failure; + } + sleep(replication.retry_delay).await; + } +} + +/// A link to a server: what it is, what it may be sent. +struct Link { + frames: Framed, LengthDelimitedCodec>, + name: String, + permissions: Permissions, + /// Whether this check-in sent something it took. + sent: bool, +} + +impl Link { + async fn open(shared: &Shared, address: &str) -> Result { + timeout(CONNECT_TIMEOUT, Link::connect(shared, address)) + .await + .map_err(|_| "too slow to connect".to_owned())? + } + + /// TCP, TLS, the versions, its roles here, the welcome. + async fn connect(shared: &Shared, address: &str) -> Result { + let text = |error: std::io::Error| error.to_string(); + let tcp = TcpStream::connect(address).await.map_err(text)?; + tcp.set_nodelay(true).map_err(text)?; + let mut stream = shared + .connector + .connect(tls::server_name(), tcp) + .await + .map_err(|error| format!("TLS: {error}"))?; + if stream.get_ref().1.alpn_protocol() != Some(ALPN) { + return Err("not a BakaShrot server".into()); + } + stream + .write_all(&frame::version_bytes()) + .await + .map_err(text)?; + stream.flush().await.map_err(text)?; + let mut theirs = [0; frame::VERSION_SIZE]; + stream.read_exact(&mut theirs).await.map_err(text)?; + frame::check_version(theirs).map_err(|version| format!("speaks protocol {version}"))?; + + let identity = tls::peer_identity(stream.get_ref().1.peer_certificates()) + .map_err(|error| error.to_string())?; + let permissions = shared.config.permissions(&identity.roles).ok_or_else(|| { + format!( + "{}: none of its roles ({}) is in this server's config", + identity.name, + identity.roles.join(", ") + ) + })?; + let mut link = Link { + frames: Framed::new(stream, frame::codec(MAX_PACKET_SIZE)), + name: identity.name, + permissions, + sent: false, + }; + match link.receive().await? { + Packet::Welcome(_) => Ok(link), + Packet::RequestRefused(refused) => Err(format!("refused: {}", refused.reason)), + other => Err(unexpected(&other)), + } + } + + /// One check-in: what it lacks, the messages then the attachments. + /// Whether it sent something it took. + async fn check_in(&mut self, shared: &Arc) -> Result { + self.sent = false; + let state = match self.ask(SyncStateRequest {}.into()).await? { + Packet::SyncState(state) => state, + Packet::RequestRefused(refused) => return Err(format!("refused: {}", refused.reason)), + other => return Err(unexpected(&other)), + }; + let heads = shared + .read(|reader| reader.heads()) + .await + .map_err(|refused| refused.reason)?; + let theirs: HashMap<(String, String), u64> = state + .heads + .iter() + .map(|head| (key(&head.topic, &head.node), head.last_id)) + .collect(); + for head in heads { + let (topic, node) = (head.topic, head.node); + if !self.sends(&state, &topic, &node) { + continue; + } + let after = theirs.get(&key(&topic, &node)).copied().unwrap_or(0); + if after < head.last_id { + self.send_messages(shared, topic, node, after).await?; + } + } + for missing in state.missing { + if self.permissions.sends(&missing.topic, &missing.node) { + self.send_attachment(shared, missing).await?; + } + } + Ok(self.sent) + } + + /// Whether it takes `node`'s messages in `topic` (its `SyncState`) and + /// may be sent them (its roles here). + fn sends(&self, state: &SyncState, topic: &str, node: &str) -> bool { + let listed = |list: &[String], name: &str| { + list.iter() + .any(|entry| names_equal(entry, name) || pattern_matches(entry, name)) + }; + listed(&state.topics, topic) + && listed(&state.nodes, node) + && self.permissions.sends(topic, node) + } + + /// A topic and node's messages after `after`, in batches. A refusal + /// leaves them for the next check-in. + async fn send_messages( + &mut self, + shared: &Arc, + topic: String, + node: String, + mut after: u64, + ) -> Result<(), String> { + let limit = shared.config.replication.batch_size; + loop { + let (t, n) = (topic.clone(), node.clone()); + let messages = shared + .read(move |reader| reader.to_replicate(&t, &n, after, limit)) + .await + .map_err(|refused| refused.reason)?; + let Some(last) = messages.last().map(|message| message.id) else { + return Ok(()); + }; + let batch = ReplicateMessages { + topic: topic.clone(), + node: node.clone(), + messages, + }; + match self.ask(batch.into()).await? { + Packet::MessagePushed(_) => { + after = last; + self.sent = true; + } + Packet::RequestRefused(refused) => { + debug!("{}: {topic}:{node} refused: {}", self.name, refused.reason); + return Ok(()); + } + other => return Err(unexpected(&other)), + } + } + } + + /// An attachment it lacks, from the part it needs, if this server has + /// it. One it says doesn't match its SHA-256 is checked here: a + /// damaged copy is asked for again from this server's own peers. + async fn send_attachment( + &mut self, + shared: &Arc, + missing: MissingAttachment, + ) -> Result<(), String> { + let message = format!("{}:{}#{}", missing.topic, missing.node, missing.message_id); + let (topic, node, id) = ( + missing.topic.clone(), + missing.node.clone(), + missing.message_id, + ); + let stored = shared + .read(move |reader| reader.attachment(&topic, &node, id)) + .await + .map_err(|refused| refused.reason)?; + let Some(stored) = stored.filter(|stored| stored.state == AttachmentState::Ready) else { + return Ok(()); + }; + let attachment = Attachment { + size: stored.size, + sha256: stored.sha256, + }; + let from_part = missing.next_part; + if from_part >= attachment.part_count() { + return Ok(()); + } + let request = ReplicateAttachment { + topic: missing.topic, + node: missing.node, + message_id: missing.message_id, + from_part, + }; + match self.ask(request.into()).await? { + Packet::Continue(_) => {} + Packet::RequestRefused(refused) => { + debug!( + "{}: {message}'s attachment refused: {}", + self.name, refused.reason + ); + return Ok(()); + } + other => return Err(unexpected(&other)), + } + for part in from_part..attachment.part_count() { + // A part that can't be read: the link closes, it asks again. + let data = shared + .read(move |reader| reader.read_part(stored.id, part)) + .await + .map_err(|refused| format!("part {part} of {message}: {}", refused.reason))?; + self.send(AttachmentPart { data }.into()).await?; + } + match self.receive().await? { + Packet::MessagePushed(_) => { + debug!("{}: sent {message}'s attachment", self.name); + self.sent = true; + } + Packet::RequestRefused(refused) if refused.code == ErrorCode::DataMismatch.code() => { + check_own_copy(shared, stored.id, &attachment, &message).await + } + Packet::RequestRefused(refused) => debug!( + "{}: {message}'s attachment refused: {}", + self.name, refused.reason + ), + other => return Err(unexpected(&other)), + } + Ok(()) + } + + async fn ask(&mut self, packet: Packet) -> Result { + self.send(packet).await?; + self.receive().await + } + + async fn send(&mut self, packet: Packet) -> Result<(), String> { + self.frames + .send(bytes::Bytes::from(packet.encode())) + .await + .map_err(|error| error.to_string()) + } + + async fn receive(&mut self) -> Result { + match timeout(ANSWER_TIMEOUT, self.frames.next()).await { + Err(_) => Err("no answer in time".into()), + Ok(None) => Err("closed the link".into()), + Ok(Some(bytes)) => { + let bytes = bytes.map_err(|error| error.to_string())?; + Packet::decode(&bytes).map_err(|error| error.to_string()) + } + } + } +} + +/// The other server said this server's copy doesn't match its SHA-256: +/// read it back; damaged, it's asked for again from this server's peers +/// (and not served meanwhile), instead of sent again and again. +async fn check_own_copy( + shared: &Arc, + attachment_id: i64, + attachment: &Attachment, + message: &str, +) { + let read = shared.hash_parts(attachment_id, 0..attachment.part_count()); + if let Ok(sha256) = read.await + && sha256.finish().as_ref() == attachment.sha256 + { + return; + } + let damaged = Write::Damaged { + attachment: attachment_id as u64, + }; + match shared.pushes.send(damaged).await { + Ok(_) => { + warn!("{message}: this server's copy of its attachment is damaged, asked for again") + } + Err(refused) => warn!("{message}: a damaged attachment: {}", refused.reason), + } +} + +/// A topic and node, to compare without case. +fn key(topic: &str, node: &str) -> (String, String) { + (topic.to_ascii_lowercase(), node.to_ascii_lowercase()) +} + +fn unexpected(packet: &Packet) -> String { + format!("answered {}", packet.packet_type().name()) +} diff --git a/crates/bakashrot-server/src/retention.rs b/crates/bakashrot-server/src/retention.rs new file mode 100644 index 0000000..da1833a --- /dev/null +++ b/crates/bakashrot-server/src/retention.rs @@ -0,0 +1,69 @@ +//! Retention: right away, then every `retention_interval`, each topic's +//! messages past its age (`[retention]`) are deleted, then their +//! attachments' parts. Every topic in the database, by its name (one no +//! longer in `topics` too). Through the writer's queue, a batch at a time, +//! so pushes go on in between. + +use crate::Shared; +use crate::writer::Write; +use bakashrot_proto::packets::RequestRefused; +use std::sync::Arc; +use tracing::{info, warn}; + +/// Most messages deleted in one write. +const MESSAGES_PER_WRITE: usize = 10_000; + +/// Most attachment parts (1 MiB each) deleted in one write. +const PARTS_PER_WRITE: usize = 64; + +/// Deletes what's past its age at every interval. Never returns. +pub(crate) async fn run(shared: &Arc) { + loop { + if let Err(refused) = once(shared).await { + warn!("retention: {}", refused.reason); + } + tokio::time::sleep(shared.config.server.retention_interval).await; + } +} + +/// One pass: every topic, then the attachments (also what a pass cut short +/// left). +async fn once(shared: &Arc) -> Result<(), RequestRefused> { + let now = crate::now(); + for topic in shared.read(|reader| reader.topics()).await? { + let Some(age) = shared.config.retention.age(&topic) else { + continue; + }; + let cutoff = now.saturating_sub(age.as_millis() as u64); + let deleted = repeat(shared, MESSAGES_PER_WRITE, |limit| Write::DeleteBefore { + topic: topic.clone(), + cutoff, + limit, + }) + .await?; + if deleted > 0 { + info!("deleted {deleted} messages of topic '{topic}'"); + } + } + repeat(shared, PARTS_PER_WRITE, |max_parts| { + Write::PurgeAttachments { max_parts } + }) + .await?; + Ok(()) +} + +/// Sends `write(limit)` until one does less than `limit`: how many in all. +async fn repeat( + shared: &Shared, + limit: usize, + write: impl Fn(usize) -> Write, +) -> Result { + let mut total = 0; + loop { + let count = shared.pushes.send(write(limit)).await?; + total += count; + if count < limit as u64 { + return Ok(total); + } + } +} diff --git a/crates/bakashrot-server/src/writer.rs b/crates/bakashrot-server/src/writer.rs new file mode 100644 index 0000000..2ec3b4d --- /dev/null +++ b/crates/bakashrot-server/src/writer.rs @@ -0,0 +1,218 @@ +//! The writer's thread: every write goes through one queue, and the thread +//! writes whatever is queued in one transaction (a group commit): the +//! busier, the bigger the groups. [`Pushes::stop`] ends it once what was +//! queued before is committed. + +use crate::refusal; +use bakashrot_proto::packets::{ReplicatedMessage, RequestRefused}; +use bakashrot_storage::{Batch, Writer}; +use std::sync::mpsc; +use tokio::sync::oneshot; + +/// Most writes in one transaction. +const MAX_GROUP: usize = 1000; + +/// A write's outcome: a number (a message's id, an upload's), or the +/// refusal to answer. +pub(crate) type Outcome = Result; + +/// What the writer does (`bakashrot_storage::Batch`'s). +pub(crate) enum Write { + /// A message: its id. + Push { + topic: String, + node: String, + pushed_at: u64, + data: String, + }, + /// An attachment's upload: its id. + StartUpload { size: u64, sha256: [u8; 32] }, + /// An upload's next part: 1 if it was the last, 0 otherwise. + Part { + upload: u64, + part: u64, + data: Vec, + }, + /// A message with its whole, checked upload: its id. + PushWithUpload { + upload: u64, + topic: String, + node: String, + pushed_at: u64, + data: String, + }, + /// Drops an upload: 0. + CancelUpload { upload: u64 }, + /// Retention: deletes a topic's messages pushed before `cutoff`, + /// `limit` at most: how many. + DeleteBefore { + topic: String, + cutoff: u64, + limit: usize, + }, + /// Deletes deleted messages' attachment parts, `max_parts` at most: + /// how many. + PurgeAttachments { max_parts: usize }, + /// A peer's messages: the topic and node's last id. + Replicate { + topic: String, + node: String, + messages: Vec, + max_attachment_size: u64, + skip_before: u64, + }, + /// A replicated attachment all of whose parts came: ready if it + /// `matches` its SHA-256, started over otherwise. 0. + FinishReplicated { attachment: u64, matches: bool }, + /// This server's own copy found damaged: asked for again. 0. + Damaged { attachment: u64 }, +} + +impl Write { + fn run(&self, batch: &mut Batch<'_>) -> bakashrot_storage::Result { + // Upload ids are SQLite rowids: positive. + match self { + Write::Push { + topic, + node, + pushed_at, + data, + } => batch.push(topic, node, *pushed_at, data), + Write::StartUpload { size, sha256 } => { + batch.start_upload(*size, sha256).map(|id| id as u64) + } + Write::Part { upload, part, data } => { + batch.write_part(*upload as i64, *part, data).map(u64::from) + } + Write::PushWithUpload { + upload, + topic, + node, + pushed_at, + data, + } => batch.push_with_attachment(*upload as i64, topic, node, *pushed_at, data), + Write::CancelUpload { upload } => batch.cancel_upload(*upload as i64).map(|()| 0), + Write::DeleteBefore { + topic, + cutoff, + limit, + } => batch + .delete_before(topic, *cutoff, *limit) + .map(|count| count as u64), + Write::PurgeAttachments { max_parts } => batch + .purge_attachments(*max_parts) + .map(|count| count as u64), + Write::Replicate { + topic, + node, + messages, + max_attachment_size, + skip_before, + } => batch.replicate(topic, node, messages, *max_attachment_size, *skip_before), + Write::FinishReplicated { + attachment, + matches, + } => batch + .finish_replicated(*attachment as i64, *matches) + .map(|()| 0), + Write::Damaged { attachment } => batch.damaged(*attachment as i64).map(|()| 0), + } + } +} + +/// What the writer's thread is sent. +enum Job { + Write { + write: Write, + done: oneshot::Sender, + }, + /// Stop once the writes queued before are committed, then say so. + Stop(oneshot::Sender<()>), +} + +/// The queue to the writer's thread. +pub(crate) struct Pushes { + queue: mpsc::Sender, +} + +impl Pushes { + /// Starts the writer's thread on `writer`. It ends with the queue, or + /// at [`Pushes::stop`]. + pub(crate) fn start(mut writer: Writer) -> std::io::Result { + let (queue, pending) = mpsc::channel::(); + std::thread::Builder::new() + .name("writer".into()) + .spawn(move || { + while let Ok(first) = pending.recv() { + let (mut group, mut stopped) = (Vec::new(), None); + for job in std::iter::once(first).chain(pending.try_iter()) { + match job { + Job::Write { write, done } => group.push((write, done)), + Job::Stop(done) => stopped = Some(done), + } + if stopped.is_some() || group.len() == MAX_GROUP { + break; + } + } + write(&mut writer, group); + if let Some(done) = stopped { + // Writes queued after are dropped with the queue, + // refused as the server stopping. + let _ = done.send(()); + return; + } + } + })?; + Ok(Pushes { queue }) + } + + /// Stops the writer's thread once every write queued before is + /// committed; the ones after are refused, the server stopping. + pub(crate) async fn stop(&self) { + let (done, stopped) = oneshot::channel(); + if self.queue.send(Job::Stop(done)).is_ok() { + let _ = stopped.await; + } + } + + /// Queues a write now (writes are done in the order queued), its + /// outcome once its group is committed. Dropping the future doesn't + /// take the write back. + pub(crate) fn send(&self, write: Write) -> impl Future + use<> { + let (done, outcome) = oneshot::channel(); + let queued = self.queue.send(Job::Write { write, done }); + async move { + queued.map_err(|_| stopped())?; + outcome.await.unwrap_or_else(|_| Err(stopped())) + } + } +} + +/// Writes a group in one transaction, then answers each write. +fn write(writer: &mut Writer, group: Vec<(Write, oneshot::Sender)>) { + if group.is_empty() { + return; + } + let mut outcomes = Vec::with_capacity(group.len()); + let committed = writer.batch(|batch| { + for (write, _) in &group { + outcomes.push(write.run(batch).map_err(refusal)); + } + Ok(()) + }); + if let Err(error) = committed { + let refused = refusal(error); + outcomes = group.iter().map(|_| Err(refused.clone())).collect(); + } + for ((_, done), outcome) in group.into_iter().zip(outcomes) { + // Its connection may be gone: nothing to answer then. + let _ = done.send(outcome); + } +} + +fn stopped() -> RequestRefused { + RequestRefused::new( + bakashrot_proto::ErrorCode::ServerError, + "the server is stopping", + ) +} diff --git a/crates/bakashrot-server/tests/end_to_end.rs b/crates/bakashrot-server/tests/end_to_end.rs new file mode 100644 index 0000000..c8c32dc --- /dev/null +++ b/crates/bakashrot-server/tests/end_to_end.rs @@ -0,0 +1,1524 @@ +//! A server on a free port, clients over TLS: pushes and reads, runs of +//! messages, big ones, names, queries, attachments, retention, replication +//! between servers, refusals, certificates refused, revoked ones dropped, +//! pushes at once. + +use bakashrot_client::{Client, Settings}; +use bakashrot_config::Config; +use bakashrot_pki::{Ca, Identity, Issued, Revocations, Usage, summarize, tls}; +use bakashrot_proto::limits::{ATTACHMENT_PART_SIZE, MAX_MESSAGE_SIZE, MAX_PACKET_SIZE}; +use bakashrot_proto::packets::{ + Attachment, AttachmentPart, GetAttachment, MessagePushed, Messages, NameKind, PushMessage, + ReplicateAttachment, ReplicateMessages, ReplicatedMessage, StoredAttachment, SyncState, + SyncStateRequest, +}; +use bakashrot_proto::{ErrorCode, Packet, frame}; +use bakashrot_server::Server; +use std::io::{Cursor, Read, Seek, SeekFrom, Write}; +use std::net::TcpStream; +use std::path::PathBuf; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::{Duration, Instant}; +use tokio_rustls::rustls::{ClientConnection, StreamOwned}; + +const CONFIG: &str = r#" +[server] +listen = "127.0.0.1:0" +ca = "ca.crt" +certificate = "server.crt" +key = "server.key" +crl = "ca.crl" +topics = ["logs", "sensors"] + +[roles.sensor] +push_topics = ["logs", "sensors"] + +[roles.reader] +read_topics = ["*"] + +[roles.logs] +read_topics = ["logs"] + +[roles.analyst] +query = true + +[roles.peer] +send_topics = ["*"] +accept_topics = ["*"] +"#; + +/// A server running on a free port, its CA and folder. +struct Running { + folder: PathBuf, + ca: Ca, + ca_issued: Issued, + ca_certificate: String, + server: Server, + address: String, + // Kept for the server's tasks to run. + runtime: tokio::runtime::Runtime, +} + +fn folder(name: &str) -> PathBuf { + static COUNT: AtomicUsize = AtomicUsize::new(0); + let folder = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(format!( + "server-{}-{}-{name}", + std::process::id(), + COUNT.fetch_add(1, Ordering::Relaxed) + )); + let _ = std::fs::remove_dir_all(&folder); + std::fs::create_dir_all(&folder).unwrap(); + folder +} + +impl Running { + fn start(name: &str) -> Running { + Running::start_with(name, "") + } + + /// With more `[server]` settings (and sections after them). + fn start_with(name: &str, settings: &str) -> Running { + let ca = Ca::create("Test CA", 10).unwrap(); + Running::start_in(folder(name), ca, "server-1", settings, "127.0.0.1:0") + } + + /// Another server with the same CA, named `server`. + fn peer(&self, name: &str, server: &str, settings: &str) -> Running { + let ca = self.ca_issued.clone(); + Running::start_in(folder(name), ca, server, settings, "127.0.0.1:0") + } + + fn start_in( + folder: PathBuf, + ca_issued: Issued, + name: &str, + settings: &str, + bind: &str, + ) -> Running { + let ca = Ca::load(&ca_issued.certificate, &ca_issued.key).unwrap(); + let server = ca + .issue(&Identity::new(name, &["peer"]).unwrap(), Usage::Server, 10) + .unwrap(); + std::fs::write(folder.join("ca.crt"), &ca_issued.certificate).unwrap(); + std::fs::write(folder.join("server.crt"), &server.certificate).unwrap(); + std::fs::write(folder.join("server.key"), &server.key).unwrap(); + let config = CONFIG.replace( + "[roles.sensor]", + &format!( + "{settings} +[roles.sensor]" + ), + ); + std::fs::write(folder.join("server.toml"), config).unwrap(); + Running::run(folder, ca, ca_issued, bind) + } + + /// Stopped as `bakashrot-server` stops, `meanwhile` run, then started + /// again on the same database and address. + fn restart_after(self, meanwhile: impl FnOnce()) -> Running { + let Running { + folder, + ca, + ca_issued, + server, + address, + runtime, + .. + } = self; + runtime.block_on(server.stop()); + runtime.shutdown_background(); + meanwhile(); + Running::run(folder, ca, ca_issued, &address) + } + + /// Its `server.toml` served on `bind`, retention and replication going. + fn run(folder: PathBuf, ca: Ca, ca_issued: Issued, bind: &str) -> Running { + let config = Config::load(&folder.join("server.toml")).unwrap(); + let server = Server::start(config).unwrap(); + let runtime = tokio::runtime::Runtime::new().unwrap(); + let listener = runtime + .block_on(tokio::net::TcpListener::bind(bind)) + .unwrap(); + let address = listener.local_addr().unwrap().to_string(); + let serving = server.clone(); + runtime.spawn(async move { serving.serve(listener).await }); + let retaining = server.clone(); + runtime.spawn(async move { retaining.apply_retention().await }); + let replicating = server.clone(); + runtime.spawn(async move { replicating.replicate().await }); + Running { + folder, + ca, + ca_certificate: ca_issued.certificate.clone(), + ca_issued, + server, + address, + runtime, + } + } + + fn issue(&self, name: &str, roles: &[&str]) -> Issued { + self.ca + .issue(&Identity::new(name, roles).unwrap(), Usage::Client, 10) + .unwrap() + } + + fn connect(&self, issued: &Issued) -> Result { + Client::connect( + &self.address, + &Settings { + ca: &self.ca_certificate, + certificate: &issued.certificate, + key: &issued.key, + crl: None, + }, + ) + } +} + +fn code(error: bakashrot_client::Error) -> u32 { + error.code() +} + +#[test] +fn push_and_read_back() { + let running = Running::start("push"); + let kitchen = running.issue("kitchen", &["sensor", "reader"]); + let mut client = running.connect(&kitchen).unwrap(); + assert_eq!((client.server(), client.node()), ("server-1", "kitchen")); + + assert_eq!(client.push("logs", r#"{"t": 21}"#).unwrap(), 1); + assert_eq!(client.push("Logs", "not json").unwrap(), 2); + assert_eq!(client.push("sensors", "{}").unwrap(), 1); + + let all = client.get_messages("logs", "kitchen", Some(0), 10).unwrap(); + let ids: Vec = all.messages.iter().map(|m| m.id).collect(); + assert_eq!(ids, [1, 2]); + assert_eq!(all.messages[0].data, r#"{"t": 21}"#); + assert!(all.messages[0].pushed_at > 1_700_000_000_000); + let latest = client.get_messages("logs", "kitchen", None, 1).unwrap(); + assert_eq!(latest.messages[0].data, "not json"); + // A node without any message: unknown. + assert_eq!( + code(client.get_messages("logs", "nobody", None, 1).unwrap_err()), + ErrorCode::UnknownName.code() + ); + + // Another connection sees them. + let mut other = running.connect(&kitchen).unwrap(); + assert_eq!( + other + .get_messages("logs", "kitchen", Some(1), 10) + .unwrap() + .messages + .len(), + 1 + ); +} + +#[test] +fn refusals_keep_the_connection() { + let running = Running::start("refusals"); + let mut sensor = running + .connect(&running.issue("sensor-1", &["sensor"])) + .unwrap(); + let mut reader = running + .connect(&running.issue("screen", &["reader"])) + .unwrap(); + + fn refused(result: Result) -> u32 { + code(result.unwrap_err()) + } + assert_eq!( + refused(sensor.get_messages("logs", "sensor-1", None, 1)), + ErrorCode::NotAllowed.code() + ); + assert_eq!( + refused(reader.push("logs", "{}")), + ErrorCode::NotAllowed.code() + ); + assert_eq!( + refused(sensor.push("nope", "{}")), + ErrorCode::UnknownName.code() + ); + // The client checks names before sending. + assert_eq!( + refused(sensor.push("a b", "{}")), + ErrorCode::InvalidArgument.code() + ); + // Still connected. + assert_eq!(sensor.push("logs", "{}").unwrap(), 1); + assert_eq!( + reader + .get_messages("logs", "sensor-1", None, 1) + .unwrap() + .messages + .len(), + 1 + ); +} + +#[test] +fn certificates_refused() { + let running = Running::start("certificates"); + // None of its roles is in the config: refused, saying so. + let error = running + .connect(&running.issue("visitor", &["guest"])) + .unwrap_err(); + assert_eq!(error.code(), ErrorCode::NotAllowed.code(), "{error}"); + assert!(error.message().contains("guest"), "{error}"); + + // Another CA's client: the server refuses it in the handshake. + let other = Ca::create("Other CA", 10).unwrap(); + let stranger = Ca::load(&other.certificate, &other.key) + .unwrap() + .issue( + &Identity::new("kitchen", &["sensor"]).unwrap(), + Usage::Client, + 10, + ) + .unwrap(); + let error = running.connect(&stranger).unwrap_err(); + assert_eq!(error.code(), ErrorCode::AuthRejected.code(), "{error}"); + + // A client trusting another CA: the server isn't verified. + let error = Client::connect( + &running.address, + &Settings { + ca: &other.certificate, + certificate: &stranger.certificate, + key: &stranger.key, + crl: None, + }, + ) + .unwrap_err(); + assert_eq!(error.code(), ErrorCode::ServerNotVerified.code(), "{error}"); + + // Nothing listening. + let error = Client::connect( + "127.0.0.1:1", + &Settings { + ca: &running.ca_certificate, + certificate: &stranger.certificate, + key: &stranger.key, + crl: None, + }, + ) + .unwrap_err(); + assert_eq!(error.code(), ErrorCode::ConnectFailed.code(), "{error}"); +} + +#[test] +fn revoked_certificates_are_dropped() { + let running = Running::start("revoked"); + let kitchen = running.issue("kitchen", &["sensor"]); + let garage = running.issue("garage", &["sensor"]); + let mut connected = running.connect(&kitchen).unwrap(); + let mut kept = running.connect(&garage).unwrap(); + assert_eq!(connected.push("logs", "{}").unwrap(), 1); + + let serial = summarize(&kitchen.certificate).unwrap().serial; + let crl = running.ca.revocation_list(&[serial], 30).unwrap(); + std::fs::write(running.folder.join("ca.crl"), crl).unwrap(); + assert_eq!(running.server.reload_revocations().unwrap(), 1); + + // Its open connection goes at its next request, a new one is refused. + let error = connected.push("logs", "{}").unwrap_err(); + assert_eq!(error.code(), ErrorCode::ConnectionLost.code(), "{error}"); + let error = running.connect(&kitchen).unwrap_err(); + assert_eq!(error.code(), ErrorCode::AuthRejected.code(), "{error}"); + // Others go on. + assert_eq!(kept.push("logs", "{}").unwrap(), 1); + + // A CRL that isn't the CA's is refused, the previous one stays. + std::fs::write(running.folder.join("ca.crl"), "not a CRL").unwrap(); + assert!(running.server.reload_revocations().is_err()); + assert!(running.connect(&kitchen).is_err()); +} + +#[test] +fn pushes_at_once() { + let running = Running::start("concurrent"); + let nodes = ["n1", "n2", "n3"]; + let threads: Vec<_> = nodes + .iter() + .flat_map(|node| { + let issued = running.issue(node, &["sensor"]); + // Two connections per node: one stream of ids between them. + (0..2).map(move |_| issued.clone()) + }) + .map(|issued| { + let mut client = running.connect(&issued).unwrap(); + std::thread::spawn(move || { + (0..200) + .map(|i| client.push("logs", &format!("{{\"i\": {i}}}")).unwrap()) + .collect::>() + }) + }) + .collect(); + let mut ids: Vec> = threads.into_iter().map(|t| t.join().unwrap()).collect(); + let reader = running.issue("screen", &["reader"]); + let mut reader = running.connect(&reader).unwrap(); + for (node, pair) in nodes.iter().zip(ids.chunks_mut(2)) { + let mut all: Vec = pair.concat(); + all.sort_unstable(); + assert_eq!(all, (1..=400).collect::>(), "{node}"); + let latest = reader.get_messages("logs", node, None, 1).unwrap(); + assert_eq!(latest.messages[0].id, 400); + } +} + +/// Pushes per second through a whole server: 10 clients over TLS, each +/// its own node, one push at a time each (the group commit gathers them). +/// Not run by default: `PUSHES=20000 cargo test --release -p +/// bakashrot-server -- --ignored --nocapture` (pushes per client; `SYNC` +/// `full`, the default, or `normal`; `CLIENTS`, 10 by default). +#[test] +#[ignore] +fn push_rate() { + let per_client: usize = std::env::var("PUSHES").map_or(20_000, |n| n.parse().unwrap()); + let sync = std::env::var("SYNC").unwrap_or_else(|_| "full".into()); + let count: usize = std::env::var("CLIENTS").map_or(10, |n| n.parse().unwrap()); + let running = Running::start_with("rate", &format!("synchronous = \"{sync}\"")); + let json = format!( + r#"{{"kind":"temp","value":21.37,"pad":"{}"}}"#, + "x".repeat(160) + ); + let clients: Vec = (0..count) + .map(|n| { + running + .connect(&running.issue(&format!("node{n}"), &["sensor"])) + .unwrap() + }) + .collect(); + let start = std::time::Instant::now(); + let threads: Vec<_> = clients + .into_iter() + .map(|mut client| { + let json = json.clone(); + std::thread::spawn(move || { + let mut slowest = std::time::Duration::ZERO; + for _ in 0..per_client { + let push = std::time::Instant::now(); + client.push("logs", &json).unwrap(); + slowest = slowest.max(push.elapsed()); + } + slowest + }) + }) + .collect(); + let slowest = threads + .into_iter() + .map(|t| t.join().unwrap()) + .max() + .unwrap(); + let took = start.elapsed().as_secs_f64(); + let total = per_client * count; + println!( + "{sync}: {total} pushes from {count} clients in {took:.1} s: {:.0}/s, slowest push {} ms", + total as f64 / took, + slowest.as_millis() + ); +} + +fn ids(messages: &Messages) -> Vec { + messages.messages.iter().map(|message| message.id).collect() +} + +/// `OldSource/Tests/GetMessages-Test.ps1`, the server's part (the tool's +/// is step 8). +#[test] +fn runs_of_messages() { + let running = Running::start("runs"); + let mut kitchen = running + .connect(&running.issue("kitchen", &["sensor", "reader"])) + .unwrap(); + + // Nothing yet: none, not a refusal, once the node is known. + kitchen.push("sensors", "{}").unwrap(); + let none = kitchen + .get_messages("logs", "kitchen", Some(0), 100) + .unwrap(); + assert!(none.messages.is_empty() && !none.more); + assert!( + kitchen + .get_messages("logs", "kitchen", None, 1) + .unwrap() + .messages + .is_empty() + ); + + for i in 1..=120 { + assert_eq!(kitchen.push("logs", &format!(r#"{{"i":{i}}}"#)).unwrap(), i); + } + let run = |client: &mut Client, after, limit| { + client + .get_messages("logs", "kitchen", after, limit) + .unwrap() + }; + let first = run(&mut kitchen, Some(0), 100); + assert_eq!(ids(&first), (1..=100).collect::>()); + assert!(first.more); + assert_eq!(first.messages[99].data, r#"{"i":100}"#); + let rest = run(&mut kitchen, Some(100), 100); + assert_eq!(ids(&rest), (101..=120).collect::>()); + assert!(!rest.more); + assert_eq!( + ids(&run(&mut kitchen, Some(115), 100)), + [116, 117, 118, 119, 120] + ); + let some = run(&mut kitchen, Some(10), 7); + assert_eq!(ids(&some), (11..=17).collect::>()); + assert!(some.more); + let past = run(&mut kitchen, Some(120), 100); + assert!(past.messages.is_empty() && !past.more); + // The last ones, in order; `more` is only for runs after an id. + let latest = run(&mut kitchen, None, 2); + assert_eq!(ids(&latest), [119, 120]); + assert!(!latest.more); + + // Another client allowed to read logs only. + let mut screen = running + .connect(&running.issue("screen", &["logs"])) + .unwrap(); + assert_eq!(ids(&run(&mut screen, Some(100), 100)).len(), 20); + let refused = |result: Result| code(result.unwrap_err()); + assert_eq!( + refused(screen.get_messages("sensors", "kitchen", None, 1)), + ErrorCode::NotAllowed.code() + ); + assert_eq!( + refused(kitchen.get_messages("nothing", "kitchen", None, 1)), + ErrorCode::UnknownName.code() + ); + assert_eq!( + refused(kitchen.get_messages("logs", "nobody", None, 1)), + ErrorCode::UnknownName.code() + ); + // Names without case. + assert_eq!( + ids(&screen.get_messages("LOGS", "Kitchen", None, 1).unwrap()), + [120] + ); + + // Data that isn't one line of JSON comes back as stored. + let text = "not JSON\r\nover two lines\twith a tab, ünïcode"; + assert_eq!(kitchen.push("logs", text).unwrap(), 121); + assert_eq!(run(&mut kitchen, None, 1).messages[0].data, text); +} + +/// `OldSource/Tests/BigMessages-Test.ps1`, one server's part (replicating +/// them is step 11): up to the limit, answers split at about 1 MB. +#[test] +fn big_messages() { + let running = Running::start("big"); + let mut kitchen = running + .connect(&running.issue("kitchen", &["sensor", "reader", "analyst"])) + .unwrap(); + let message = |size: usize, n: &str| { + let head = format!(r#"{{"n":"{n}","pad":""#); + format!("{head}{}\"}}", "x".repeat(size - head.len() - 2)) + }; + + // 5 of 600 KB and the biggest: one per answer, the biggest alone. + let mut pushed: Vec = (0..5) + .map(|i| message(600 * 1024, &format!("m{i}"))) + .collect(); + pushed.push(message(MAX_MESSAGE_SIZE, "max")); + for (i, data) in pushed.iter().enumerate() { + assert_eq!(kitchen.push("logs", data).unwrap(), i as u64 + 1); + } + let (mut read, mut answers, mut after) = (Vec::new(), 0, 0); + loop { + let answer = kitchen + .get_messages("logs", "kitchen", Some(after), 100) + .unwrap(); + answers += 1; + assert_eq!(answer.messages.len(), 1); + after = answer.messages[0].id; + read.extend(answer.messages.into_iter().map(|message| message.data)); + if !answer.more { + break; + } + } + assert_eq!(answers, 6); + assert!(read == pushed, "read back whole"); + + // One byte over: the client refuses it, the connection stays. + let error = kitchen + .push("logs", &message(MAX_MESSAGE_SIZE + 1, "over")) + .unwrap_err(); + assert_eq!(error.code(), ErrorCode::InvalidArgument.code(), "{error}"); + assert_eq!(kitchen.push("logs", r#"{"n":"small"}"#).unwrap(), 7); + let latest = kitchen.get_messages("logs", "kitchen", None, 1).unwrap(); + assert_eq!(latest.messages[0].data, r#"{"n":"small"}"#); + + // Stored as pushed; a result over the limit is refused, not cut. + let sizes = kitchen + .query( + "SELECT message_id, length(message_data) AS size FROM messages WHERE message_id >= 5", + ) + .unwrap(); + assert_eq!( + sizes, + format!( + r#"{{"columns":["message_id","size"],"rows":[["5","{}"],["6","{MAX_MESSAGE_SIZE}"],["7","13"]]}}"#, + 600 * 1024 + ) + ); + let error = kitchen + .query("SELECT message_data, message_data FROM messages WHERE message_id = 6") + .unwrap_err(); + assert_eq!(error.code(), ErrorCode::TooBig.code(), "{error}"); +} + +#[test] +fn names() { + let running = Running::start("names"); + let mut sensor = running + .connect(&running.issue("kitchen", &["sensor"])) + .unwrap(); + sensor.push("logs", "{}").unwrap(); + let mut garage = running + .connect(&running.issue("garage", &["sensor"])) + .unwrap(); + garage.push("sensors", "{}").unwrap(); + let mut screen = running + .connect(&running.issue("screen", &["logs"])) + .unwrap(); + let mut analyst = running + .connect(&running.issue("analyst-1", &["analyst"])) + .unwrap(); + + let names = |client: &mut Client, kind| { + let list = client.list_names(kind).unwrap(); + assert_eq!(list.kind, kind); + assert!(!list.truncated); + list.names + }; + // Topics: those it may push to or read; every one for a query role. + assert_eq!(names(&mut sensor, NameKind::Topic), ["logs", "sensors"]); + assert_eq!(names(&mut screen, NameKind::Topic), ["logs"]); + assert_eq!(names(&mut analyst, NameKind::Topic), ["logs", "sensors"]); + // Nodes: every one with messages. + assert_eq!(names(&mut screen, NameKind::Node), ["garage", "kitchen"]); +} + +/// The query parts of `OldSource/Tests/BigMessages-Test.ps1`. +#[test] +fn queries() { + let running = Running::start("queries"); + let mut sensor = running + .connect(&running.issue("kitchen", &["sensor"])) + .unwrap(); + for data in [r#"{"n":"small"}"#, "plain text", r#"{"n":"other"}"#] { + sensor.push("logs", data).unwrap(); + } + let error = sensor.query("SELECT 1").unwrap_err(); + assert_eq!(error.code(), ErrorCode::NotAllowed.code(), "{error}"); + + let mut analyst = running + .connect(&running.issue("analyst-1", &["analyst"])) + .unwrap(); + assert_eq!( + analyst + .query("SELECT message_id, is_json FROM messages ORDER BY message_id") + .unwrap(), + r#"{"columns":["message_id","is_json"],"rows":[["1","1"],["2","0"],["3","1"]]}"# + ); + assert_eq!( + analyst + .query("SELECT COUNT(*) AS n FROM messages WHERE is_json = 1 AND message_data ->> '$.n' = 'small'") + .unwrap(), + r#"{"columns":["n"],"rows":[["1"]]}"# + ); + assert_eq!( + analyst + .query("SELECT message_id FROM messages WHERE message_id < 0") + .unwrap(), + r#"{"columns":["message_id"],"rows":[]}"# + ); + let failed = |result: Result| { + let error = result.unwrap_err(); + assert_eq!(error.code(), ErrorCode::QueryFailed.code(), "{error}"); + error.message().to_owned() + }; + // A non-JSON row fails the query, never a partial answer. + let why = failed( + analyst.query("SELECT COUNT(*) FROM messages WHERE message_data ->> '$.n' = 'small'"), + ); + assert!( + why.contains("malformed JSON") && why.contains("is_json = 1"), + "{why}" + ); + let why = failed(analyst.query("SELECT nope FROM data")); + assert!(why.contains("nope"), "{why}"); + failed(analyst.query("DELETE FROM data")); + failed(analyst.query("SELECT 1; SELECT 2")); + // Still connected, nothing deleted. + assert_eq!( + analyst.query("SELECT COUNT(*) AS n FROM data").unwrap(), + r#"{"columns":["n"],"rows":[["3"]]}"# + ); +} + +const MIB: usize = ATTACHMENT_PART_SIZE as usize; + +/// `size` bytes that differ with `seed`. +fn bytes(size: usize, seed: u8) -> Vec { + (0..size) + .map(|i| (i as u8).wrapping_mul(31).wrapping_add(seed)) + .collect() +} + +fn sha256(data: &[u8]) -> [u8; 32] { + let mut digest = [0; 32]; + digest.copy_from_slice(aws_lc_rs::digest::digest(&aws_lc_rs::digest::SHA256, data).as_ref()); + digest +} + +#[test] +fn attachments() { + let running = Running::start_with("attachments", "max_attachment_size = \"8M\""); + let mut kitchen = running + .connect(&running.issue("kitchen", &["sensor", "reader"])) + .unwrap(); + let sizes = [100 * 1024, 5 * MIB + 123, 2 * MIB, 1, MIB]; + let files: Vec> = (0..sizes.len()).map(|i| bytes(sizes[i], i as u8)).collect(); + for (i, file) in files.iter().enumerate() { + let id = kitchen + .push_with_attachment( + "logs", + &format!(r#"{{"n":{}}}"#, i + 1), + &mut Cursor::new(file), + ) + .unwrap(); + assert_eq!(id, i as u64 + 1); + } + assert_eq!(kitchen.push("logs", r#"{"n":6}"#).unwrap(), 6); + + let read = kitchen + .get_messages("logs", "kitchen", Some(0), 10) + .unwrap(); + let attachments: Vec<_> = read.messages.iter().map(|m| m.attachment.clone()).collect(); + let mut expected: Vec<_> = sizes + .iter() + .map(|&size| { + Some(StoredAttachment { + size: size as u64, + ready: true, + }) + }) + .collect(); + expected.push(None); + assert_eq!(attachments, expected); + + for (i, file) in files.iter().enumerate() { + let mut out = Vec::new(); + let size = kitchen + .get_attachment("logs", "kitchen", i as u64 + 1, &mut out) + .unwrap(); + assert_eq!((size, &out), (file.len() as u64, file), "#{}", i + 1); + } + let saved = running.folder.join("saved.bin"); + assert_eq!( + kitchen + .save_attachment("logs", "kitchen", 2, &saved) + .unwrap(), + sizes[1] as u64 + ); + assert_eq!(std::fs::read(&saved).unwrap(), files[1]); + assert!(!running.folder.join("saved.bin.download").exists()); + + // None, or none to give: refused, no file left. + let none = running.folder.join("none.bin"); + for id in [6, 99] { + let error = kitchen + .save_attachment("logs", "kitchen", id, &none) + .unwrap_err(); + assert_eq!(error.code(), ErrorCode::NotFound.code(), "{error}"); + assert!( + error.message().contains(&format!("logs:kitchen#{id}")), + "{error}" + ); + } + assert!(!none.exists() && !running.folder.join("none.bin.download").exists()); + let error = kitchen + .get_attachment("nothing", "kitchen", 1, &mut Vec::new()) + .unwrap_err(); + assert_eq!(error.code(), ErrorCode::UnknownName.code(), "{error}"); + let mut logs_only = running + .connect(&running.issue("lounge", &["logs"])) + .unwrap(); + let mut out = Vec::new(); + assert_eq!( + logs_only + .get_attachment("logs", "kitchen", 3, &mut out) + .unwrap(), + 2 * MIB as u64 + ); + kitchen + .push_with_attachment("sensors", "{}", &mut Cursor::new(b"s")) + .unwrap(); + let error = logs_only + .get_attachment("sensors", "kitchen", 1, &mut Vec::new()) + .unwrap_err(); + assert_eq!(error.code(), ErrorCode::NotAllowed.code(), "{error}"); + + // Over the server's limit, or empty: refused, nothing stored. + let big = bytes(8 * MIB + 1, 9); + let error = kitchen + .push_with_attachment("logs", "{}", &mut Cursor::new(&big)) + .unwrap_err(); + assert_eq!(error.code(), ErrorCode::TooBig.code(), "{error}"); + let error = kitchen + .push_with_attachment("logs", "{}", &mut Cursor::new(b"")) + .unwrap_err(); + assert_eq!(error.code(), ErrorCode::InvalidArgument.code(), "{error}"); + assert_eq!(kitchen.push("logs", "{}").unwrap(), 7); + + let mut analyst = running + .connect(&running.issue("analyst-1", &["analyst"])) + .unwrap(); + assert_eq!( + analyst + .query("SELECT COUNT(*), SUM(state = 'ready') FROM attachments") + .unwrap(), + r#"{"columns":["COUNT(*)","SUM(state = 'ready')"],"rows":[["6","6"]]}"# + ); + assert_eq!( + analyst + .query("SELECT COUNT(*) FROM attachment_parts") + .unwrap(), + r#"{"columns":["COUNT(*)"],"rows":[["12"]]}"#, + "1 + 6 + 2 + 1 + 1 + 1 parts" + ); + + let none = Running::start_with("no-attachments", "max_attachment_size = 0"); + let mut client = none.connect(&none.issue("kitchen", &["sensor"])).unwrap(); + let error = client + .push_with_attachment("logs", "{}", &mut Cursor::new(b"x")) + .unwrap_err(); + assert_eq!(error.code(), ErrorCode::TooBig.code(), "{error}"); +} + +/// A source read twice: `first`, then `second` (as if it changed in +/// between), the second time failing after `fail_after` bytes if set. +struct Changing { + first: Vec, + second: Vec, + fail_after: Option, + pass: usize, + at: usize, +} + +impl Read for Changing { + fn read(&mut self, buffer: &mut [u8]) -> std::io::Result { + let data = if self.pass == 1 { + &self.first + } else { + &self.second + }; + let mut end = data.len().min(self.at + buffer.len()); + if self.pass > 1 + && let Some(fail) = self.fail_after + { + if self.at >= fail { + return Err(std::io::Error::other("the disk is gone")); + } + end = end.min(fail); + } + let read = end - self.at; + buffer[..read].copy_from_slice(&data[self.at..end]); + self.at = end; + Ok(read) + } +} + +impl Seek for Changing { + fn seek(&mut self, to: SeekFrom) -> std::io::Result { + assert_eq!(to, SeekFrom::Start(0), "only rewound"); + self.pass += 1; + self.at = 0; + Ok(0) + } +} + +/// A connection speaking the protocol itself, for what the client never +/// sends. +struct Raw(StreamOwned); + +impl Raw { + fn connect(running: &Running, issued: &Issued) -> Raw { + let config = tls::client_config( + &running.ca_certificate, + &issued.certificate, + &issued.key, + Revocations::none().shared(), + ) + .unwrap(); + let tcp = TcpStream::connect(&running.address).unwrap(); + tcp.set_read_timeout(Some(Duration::from_secs(10))).unwrap(); + let connection = ClientConnection::new(config, tls::server_name()).unwrap(); + let mut raw = Raw(StreamOwned::new(connection, tcp)); + frame::write_version(&mut raw.0).unwrap(); + raw.0.flush().unwrap(); + frame::read_version(&mut raw.0).unwrap(); + assert!(matches!(raw.receive(), Some(Packet::Welcome(_)))); + raw + } + + fn send(&mut self, packet: impl Into) { + frame::write(&mut self.0, &packet.into().encode()).unwrap(); + self.0.flush().unwrap(); + } + + /// The next packet, none once the server closed the connection. + fn receive(&mut self) -> Option { + let bytes = frame::read(&mut self.0, MAX_PACKET_SIZE).ok()??; + Some(Packet::decode(&bytes).unwrap()) + } + + #[track_caller] + fn refused(&mut self, code: ErrorCode) { + match self.receive() { + Some(Packet::RequestRefused(refused)) => { + assert_eq!(refused.code, code.code(), "{refused:?}") + } + other => panic!("expected {code}, got {other:?}"), + } + } + + /// Pushes with an attachment of `size` bytes and `sha256`, then the + /// parts given. + fn push(&mut self, size: usize, sha256: [u8; 32], parts: &[&[u8]]) { + self.send(PushMessage { + topic: "logs".into(), + data: "{}".into(), + attachment: Some(Attachment { + size: size as u64, + sha256, + }), + }); + assert!(matches!(self.receive(), Some(Packet::Continue(_)))); + for part in parts { + self.send(AttachmentPart { + data: part.to_vec(), + }); + } + } +} + +#[test] +fn attachment_edges() { + let running = Running::start("attachment-edges"); + let issued = running.issue("kitchen", &["sensor", "reader"]); + let mut kitchen = running.connect(&issued).unwrap(); + let mut analyst = running + .connect(&running.issue("analyst-1", &["analyst"])) + .unwrap(); + let uploads = |analyst: &mut Client| { + analyst + .query("SELECT COUNT(*) FROM attachments WHERE state = 'uploading'") + .unwrap() + }; + let none_left = r#"{"columns":["COUNT(*)"],"rows":[["0"]]}"#; + + // Changed between its SHA-256 and its sending: refused, dropped, the + // connection still there. + let file = bytes(3 * MIB, 1); + let mut changed = Changing { + first: file.clone(), + second: bytes(3 * MIB, 2), + fail_after: None, + pass: 0, + at: 0, + }; + let error = kitchen + .push_with_attachment("logs", "{}", &mut changed) + .unwrap_err(); + assert_eq!(error.code(), ErrorCode::DataMismatch.code(), "{error}"); + assert_eq!( + kitchen + .push_with_attachment("logs", "{}", &mut Cursor::new(&file)) + .unwrap(), + 1 + ); + + // Failing in the middle: the client closes, the server drops the upload. + let mut failing = Changing { + first: file.clone(), + second: file.clone(), + fail_after: Some(MIB + 10), + pass: 0, + at: 0, + }; + let error = kitchen + .push_with_attachment("logs", "{}", &mut failing) + .unwrap_err(); + assert_eq!(error.code(), ErrorCode::FileError.code(), "{error}"); + let error = kitchen.push("logs", "{}").unwrap_err(); + assert_eq!(error.code(), ErrorCode::ConnectionLost.code(), "{error}"); + let started = Instant::now(); + while uploads(&mut analyst) != none_left { + assert!( + started.elapsed() < Duration::from_secs(10), + "the cut upload stays" + ); + std::thread::sleep(Duration::from_millis(50)); + } + + // A part of the wrong size: refused once all came, the connection kept. + let mut raw = Raw::connect(&running, &issued); + let size = 2 * MIB + 1; + let file = bytes(size, 3); + raw.push( + size, + sha256(&file), + &[&file[..1000], &file[MIB..2 * MIB], &file[2 * MIB..]], + ); + raw.refused(ErrorCode::InvalidRequest); + raw.push( + size, + sha256(&file), + &[&file[..MIB], &file[MIB..2 * MIB], &file[2 * MIB..]], + ); + assert!(matches!(raw.receive(), Some(Packet::MessagePushed(pushed)) if pushed.message_id == 2)); + // A wrong SHA-256, sent by the client. + raw.push( + size, + [7; 32], + &[&file[..MIB], &file[MIB..2 * MIB], &file[2 * MIB..]], + ); + raw.refused(ErrorCode::DataMismatch); + + // From a part on, as a cut download goes on. + let get = |from_part| GetAttachment { + topic: "logs".into(), + node: "kitchen".into(), + message_id: 2, + from_part, + }; + raw.send(get(1)); + match raw.receive() { + Some(Packet::Attachment(attachment)) => assert_eq!(attachment.sha256, sha256(&file)), + other => panic!("{other:?}"), + } + let mut rest = Vec::new(); + for _ in 1..3 { + let Some(Packet::AttachmentPart(part)) = raw.receive() else { + panic!("a part") + }; + rest.extend(part.data); + } + assert_eq!(rest, file[MIB..]); + raw.send(get(3)); + raw.refused(ErrorCode::InvalidRequest); + + // Something else than a part: the connection is closed, the upload + // dropped. + raw.push(size, sha256(&file), &[&file[..MIB]]); + raw.send(PushMessage { + topic: "logs".into(), + data: "{}".into(), + attachment: None, + }); + assert!(raw.receive().is_none(), "closed"); + let started = Instant::now(); + while uploads(&mut analyst) != none_left { + assert!( + started.elapsed() < Duration::from_secs(10), + "the upload stays" + ); + std::thread::sleep(Duration::from_millis(50)); + } + let messages = analyst + .query("SELECT message_id FROM messages ORDER BY 1") + .unwrap(); + assert_eq!( + messages, + r#"{"columns":["message_id"],"rows":[["1"],["2"]]}"# + ); +} + +#[test] +fn stops_cleanly() { + // 8 nodes pushing flat out, the server stopped under them: every push + // answered is stored, the ones after refused as the server stopping. + let running = Running::start("stop"); + let threads: Vec<_> = (0..8) + .map(|n| { + let mut client = running + .connect(&running.issue(&format!("n{n}"), &["sensor"])) + .unwrap(); + std::thread::spawn(move || { + let mut answered = 0; + loop { + match client.push("logs", "{}") { + Ok(id) => answered = id, + Err(error) => return (answered, error.code()), + } + } + }) + }) + .collect(); + std::thread::sleep(Duration::from_millis(300)); + running.runtime.block_on(running.server.stop()); + let stopped: Vec<(u64, u32)> = threads.into_iter().map(|t| t.join().unwrap()).collect(); + + let running = running.restart_after(|| {}); + let mut reader = running + .connect(&running.issue("reader", &["reader"])) + .unwrap(); + for (n, (answered, code)) in stopped.into_iter().enumerate() { + assert_eq!(code, ErrorCode::ServerError.code(), "n{n}"); + assert!(answered > 0, "n{n} pushed nothing"); + let latest = reader.get_messages("logs", &format!("n{n}"), None, 1); + // The last push may have been committed after its answer was lost. + assert!(latest.unwrap().messages[0].id >= answered, "n{n}"); + } +} + +#[test] +fn retention() { + // logs kept 2 s, sensors forever; looked at every second. + let running = Running::start_with( + "retention", + "retention_interval = \"1s\"\n\n[retention]\nlogs = \"2s\"\n", + ); + let mut kitchen = running + .connect(&running.issue("kitchen", &["sensor", "reader"])) + .unwrap(); + let mut analyst = running + .connect(&running.issue("analyst", &["analyst"])) + .unwrap(); + let mut count = |sql: &str| { + let result = analyst.query(sql).unwrap(); + result + .strip_prefix(r#"{"columns":["n"],"rows":[[""#) + .and_then(|rest| rest.strip_suffix(r#""]]}"#)) + .unwrap_or_else(|| panic!("{result}")) + .parse::() + .unwrap() + }; + let logs = "SELECT COUNT(*) AS n FROM messages WHERE topic = 'logs'"; + let attachments = "SELECT (SELECT COUNT(*) FROM attachments) \ + + (SELECT COUNT(*) FROM attachment_parts) AS n"; + + let file = bytes(2 * MIB + 5, 7); + kitchen + .push_with_attachment("logs", "{}", &mut Cursor::new(&file)) + .unwrap(); + kitchen.push("logs", "{}").unwrap(); + assert_eq!(kitchen.push("logs", "{}").unwrap(), 3); + kitchen.push("sensors", "{}").unwrap(); + assert_eq!((count(logs), count(attachments)), (3, 4)); + + // Gone past their age, the attachment with them; sensors' kept. + let deadline = Instant::now() + Duration::from_secs(15); + while (count(logs), count(attachments)) != (0, 0) { + assert!(Instant::now() < deadline, "logs not deleted"); + std::thread::sleep(Duration::from_millis(100)); + } + assert_eq!( + count("SELECT COUNT(*) AS n FROM messages WHERE topic = 'sensors'"), + 1 + ); + + // Ids go on; a younger message stays through a pass. + assert_eq!(kitchen.push("logs", "{}").unwrap(), 4); + std::thread::sleep(Duration::from_millis(1100)); + assert_eq!(count(logs), 1); + let latest = kitchen.get_messages("logs", "kitchen", None, 1).unwrap(); + assert_eq!(latest.messages[0].id, 4); +} + +/// Replication flat out, as the old `Tests/Bench/Bench-Replication.ps1` +/// (`-Parts Ramp -Ramp 10x0`): 4 servers in a Y (a hub pushing to 3 +/// leaves, each pushing to the hub), `NODES` nodes (10) pushing to each +/// as fast as they're answered for `SECONDS` (30), then how far behind +/// each server is and how long until every one has every message. Run +/// with `cargo test --release -p bakashrot-server --test end_to_end +/// replication_rate -- --ignored --nocapture` (`SYNC`: `full`, the +/// default, or `normal`). +#[test] +#[ignore] +fn replication_rate() { + let env = + |name: &str, default: u64| std::env::var(name).map_or(default, |v| v.parse().unwrap()); + let (nodes, seconds) = (env("NODES", 10), env("SECONDS", 30)); + let sync = std::env::var("SYNC").unwrap_or_else(|_| "full".into()); + let batch = env("BATCH", 1000); + // Free ports first: every server's push_to names the others. + let addresses: Vec = (0..4) + .map(|_| { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + listener.local_addr().unwrap().to_string() + }) + .collect(); + let ca = Ca::create("Bench CA", 10).unwrap(); + let servers: Vec = (0..4) + .map(|n| { + let push_to = match n { + 0 => addresses[1..].join("\", \""), + _ => addresses[0].clone(), + }; + let settings = format!( + "synchronous = \"{sync}\"\n\n[replication]\npush_to = [\"{push_to}\"]\n\ + accept_from = [\"127.0.0.1\"]\nbatch_size = {batch}\n" + ); + let name = format!("server-{n}"); + Running::start_in(folder(&name), ca.clone(), &name, &settings, &addresses[n]) + }) + .collect(); + let json = format!( + r#"{{"kind":"temp","value":21.37,"pad":"{}"}}"#, + "x".repeat(160) + ); + let clients: Vec = servers + .iter() + .enumerate() + .flat_map(|(s, server)| { + (0..nodes).map(move |n| { + server + .connect(&server.issue(&format!("s{s}n{n}"), &["sensor"])) + .unwrap() + }) + }) + .collect(); + let mut analysts: Vec = servers + .iter() + .map(|server| { + server + .connect(&server.issue("analyst", &["analyst"])) + .unwrap() + }) + .collect(); + let mut counts = || -> Vec { + analysts + .iter_mut() + .map(|analyst| { + let result = analyst.query("SELECT COUNT(*) AS n FROM data").unwrap(); + result[r#"{"columns":["n"],"rows":[[""#.len()..result.len() - 4] + .parse() + .unwrap() + }) + .collect() + }; + + let start = Instant::now(); + let until = start + Duration::from_secs(seconds); + let threads: Vec<_> = clients + .into_iter() + .map(|mut client| { + let json = json.clone(); + std::thread::spawn(move || { + let (mut pushed, mut slowest) = (0u64, Duration::ZERO); + while Instant::now() < until { + let push = Instant::now(); + client.push("logs", &json).unwrap(); + slowest = slowest.max(push.elapsed()); + pushed += 1; + } + (pushed, slowest) + }) + }) + .collect(); + let results: Vec<(u64, Duration)> = threads.into_iter().map(|t| t.join().unwrap()).collect(); + let pushing = start.elapsed().as_secs_f64(); + let total: u64 = results.iter().map(|(pushed, _)| pushed).sum(); + let slowest = results.iter().map(|(_, slowest)| *slowest).max().unwrap(); + let at_end = counts(); + let drain = Instant::now(); + while counts().iter().any(|&count| count < total) { + assert!(drain.elapsed() < Duration::from_secs(300), "not drained"); + std::thread::sleep(Duration::from_millis(200)); + } + let drained = drain.elapsed().as_secs_f64(); + let behind: Vec = at_end + .iter() + .map(|&count| format!("{:.1} s", (total - count) as f64 / (total as f64 / pushing))) + .collect(); + println!( + "{sync}, 4 servers x {nodes} nodes, {seconds} s: {total} pushes, {:.0}/s, slowest {} ms; \ + behind at the end (s of pushes; hub, leaves): {}; all everywhere {drained:.1} s later", + total as f64 / pushing, + slowest.as_millis(), + behind.join(", ") + ); +} + +/// Waits up to 15 s for `done`, every 100 ms. +fn wait_for(what: &str, mut done: impl FnMut() -> bool) { + let deadline = Instant::now() + Duration::from_secs(15); + while !done() { + assert!(Instant::now() < deadline, "{what}: not in time"); + std::thread::sleep(Duration::from_millis(100)); + } +} + +#[test] +fn replication() { + // a pushes to b (and c); b takes from 127.0.0.1, c from elsewhere only. + let b = Running::start_with( + "replication-b", + "\n[replication]\naccept_from = [\"127.0.0.1\"]\n", + ); + let c = b.peer( + "replication-c", + "server-c", + "\n[replication]\naccept_from = [\"10.9.9.9\"]\n", + ); + let a = b.peer( + "replication-a", + "server-a", + &format!( + "\n[replication]\npush_to = [\"{}\", \"{}\"]\nsync_interval = \"1s\"\n\ + retry_delay = \"1s\"\n", + b.address, c.address + ), + ); + let kitchen = a.issue("kitchen", &["sensor", "reader"]); + let mut on_a = a.connect(&kitchen).unwrap(); + let file = bytes(2 * MIB + 5, 9); + on_a.push_with_attachment("logs", "{\"n\":1}", &mut Cursor::new(&file)) + .unwrap(); + on_a.push("logs", "{\"n\":2}").unwrap(); + on_a.push("logs", "not json").unwrap(); + on_a.push("sensors", "{}").unwrap(); + + // b gets them all, by name, with their ids, times and attachment. + let mut on_b = b.connect(&b.issue("watcher", &["reader"])).unwrap(); + let read = |client: &mut Client, topic: &str| { + client + .get_messages(topic, "kitchen", Some(0), 100) + .map(|answer| answer.messages) + .unwrap_or_default() + }; + wait_for("the messages on b", || { + read(&mut on_b, "logs").len() == 3 && read(&mut on_b, "sensors").len() == 1 + }); + let (sent, got) = (read(&mut on_a, "logs"), read(&mut on_b, "logs")); + let fields = |m: &bakashrot_proto::packets::MessageEntry| (m.id, m.pushed_at, m.data.clone()); + assert_eq!( + sent.iter().map(fields).collect::>(), + got.iter().map(fields).collect::>() + ); + wait_for("the attachment on b", || { + let mut out = Vec::new(); + on_b.get_attachment("logs", "kitchen", 1, &mut out).is_ok() && out == file + }); + + // c doesn't take from a: not in its accept_from. + let mut analyst = c.connect(&c.issue("analyst", &["analyst"])).unwrap(); + assert_eq!( + analyst.query("SELECT COUNT(*) AS n FROM messages").unwrap(), + r#"{"columns":["n"],"rows":[["0"]]}"# + ); + + // One way: b's own pushes don't go to a (b has no push_to). + let mut garage = b.connect(&b.issue("garage", &["sensor"])).unwrap(); + garage.push("logs", "{}").unwrap(); + std::thread::sleep(Duration::from_millis(2500)); + assert_eq!( + code( + on_a.get_messages("logs", "garage", Some(0), 10) + .unwrap_err() + ), + ErrorCode::UnknownName.code() + ); + + // b stopped: a links again once it's back, sends what came meanwhile, + // ids go on. Meanwhile a's copy of #6's attachment got damaged. + drop((on_b, garage)); + let b = b.restart_after(|| { + assert_eq!(on_a.push("logs", "{\"n\":4}").unwrap(), 4); + assert_eq!(on_a.push("logs", "{\"n\":5}").unwrap(), 5); + let other = bytes(MIB + 1, 3); + let id = on_a + .push_with_attachment("logs", "{\"n\":6}", &mut Cursor::new(&other)) + .unwrap(); + assert_eq!(id, 6); + let raw = rusqlite::Connection::open(a.folder.join("bakashrot.sqlite")).unwrap(); + raw.execute( + "UPDATE attachment_parts SET part_data = zeroblob(length(part_data)) \ + WHERE key = (SELECT max(key) FROM attachment_parts)", + [], + ) + .unwrap(); + }); + let mut on_b = b.connect(&b.issue("watcher", &["reader"])).unwrap(); + wait_for("the messages on b, restarted", || { + read(&mut on_b, "logs") + .iter() + .map(|m| m.id) + .collect::>() + == [1, 2, 3, 4, 5, 6] + }); + + // b refuses the damaged copy; a finds its own damaged and asks for it + // again, instead of sending it again and again. + wait_for("a's damaged copy noticed", || { + on_a.get_attachment("logs", "kitchen", 6, &mut Vec::new()) + .is_err_and(|error| error.code() == ErrorCode::NotReady.code()) + }); + assert_eq!( + code( + on_b.get_attachment("logs", "kitchen", 6, &mut Vec::new()) + .unwrap_err() + ), + ErrorCode::NotReady.code() + ); +} + +/// A server's `SyncState`, asked over `raw`. +fn sync_state(raw: &mut Raw) -> SyncState { + raw.send(SyncStateRequest {}); + match raw.receive() { + Some(Packet::SyncState(state)) => state, + other => panic!("expected a SyncState, got {other:?}"), + } +} + +#[test] +fn replication_edges() { + // The test plays the peer, over a raw connection. + let running = Running::start_with( + "replication-edges", + "\n[replication]\naccept_from = [\"127.0.0.1\"]\n\n[retention]\nold = \"1h\"\n", + ); + let peer = running.issue("server-x", &["peer"]); + let mut raw = Raw::connect(&running, &peer); + let state = sync_state(&mut raw); + assert_eq!( + (state.topics, state.nodes), + (vec!["*".into()], vec!["*".into()]) + ); + assert!(state.heads.is_empty() && state.missing.is_empty()); + + let file = bytes(2 * MIB + 1, 5); + let message = |id, pushed_at, attachment| ReplicatedMessage { + id, + pushed_at, + data: format!("m{id}"), + attachment, + }; + let now = 1_800_000_000_000; + raw.send(ReplicateMessages { + topic: "logs".into(), + node: "far".into(), + messages: vec![ + message( + 3, + now, + Some(Attachment { + size: file.len() as u64, + sha256: sha256(&file), + }), + ), + message(7, now, None), + ], + }); + assert_eq!(raw.receive(), Some(MessagePushed { message_id: 7 }.into())); + // Past its age here: not stored, but counted as received. + raw.send(ReplicateMessages { + topic: "old".into(), + node: "far".into(), + messages: vec![message(1, 1000, None)], + }); + assert_eq!(raw.receive(), Some(MessagePushed { message_id: 1 }.into())); + let mut analyst = running + .connect(&running.issue("analyst", &["analyst"])) + .unwrap(); + assert_eq!( + analyst + .query("SELECT group_concat(topic || '#' || message_id) AS n FROM messages") + .unwrap(), + r#"{"columns":["n"],"rows":[["logs#3,logs#7"]]}"# + ); + let state = sync_state(&mut raw); + let heads: Vec<_> = state + .heads + .iter() + .map(|head| (head.topic.as_str(), head.last_id)) + .collect(); + assert_eq!(heads, [("logs", 7), ("old", 1)]); + let missing: Vec<_> = state + .missing + .iter() + .map(|missing| (missing.message_id, missing.next_part)) + .collect(); + assert_eq!(missing, [(3, 0)]); + + // From the part it needs only. + let ask = |raw: &mut Raw, message_id, from_part| { + raw.send(ReplicateAttachment { + topic: "logs".into(), + node: "far".into(), + message_id, + from_part, + }) + }; + ask(&mut raw, 3, 1); + raw.refused(ErrorCode::InvalidRequest); + ask(&mut raw, 7, 0); + raw.refused(ErrorCode::NotFound); + + // Cut after its first part: it goes on from the second. + ask(&mut raw, 3, 0); + assert!(matches!(raw.receive(), Some(Packet::Continue(_)))); + raw.send(AttachmentPart { + data: file[..MIB].to_vec(), + }); + drop(raw); + let mut raw = Raw::connect(&running, &peer); + wait_for("the first part kept", || { + sync_state(&mut raw).missing[0].next_part == 1 + }); + ask(&mut raw, 3, 1); + assert!(matches!(raw.receive(), Some(Packet::Continue(_)))); + for part in file[MIB..].chunks(MIB) { + raw.send(AttachmentPart { + data: part.to_vec(), + }); + } + assert_eq!(raw.receive(), Some(MessagePushed { message_id: 3 }.into())); + let mut reader = running + .connect(&running.issue("watcher", &["reader"])) + .unwrap(); + let mut out = Vec::new(); + reader.get_attachment("logs", "far", 3, &mut out).unwrap(); + assert!(out == file); + assert!(sync_state(&mut raw).missing.is_empty()); + + // Not matching its SHA-256: refused, asked for again from the start. + raw.send(ReplicateMessages { + topic: "logs".into(), + node: "far".into(), + messages: vec![message( + 8, + now, + Some(Attachment { + size: 10, + sha256: [0; 32], + }), + )], + }); + assert_eq!(raw.receive(), Some(MessagePushed { message_id: 8 }.into())); + ask(&mut raw, 8, 0); + assert!(matches!(raw.receive(), Some(Packet::Continue(_)))); + raw.send(AttachmentPart { data: vec![1; 10] }); + raw.refused(ErrorCode::DataMismatch); + assert_eq!(sync_state(&mut raw).missing[0].next_part, 0); + + // A certificate whose roles take nothing: refused. + let mut other = Raw::connect(&running, &running.issue("nosy", &["reader"])); + let state = sync_state(&mut other); + assert!(state.topics.is_empty() && state.heads.is_empty()); + other.send(ReplicateMessages { + topic: "logs".into(), + node: "far".into(), + messages: vec![message(9, now, None)], + }); + other.refused(ErrorCode::NotAllowed); +} diff --git a/crates/bakashrot-storage/Cargo.toml b/crates/bakashrot-storage/Cargo.toml new file mode 100644 index 0000000..8e016c0 --- /dev/null +++ b/crates/bakashrot-storage/Cargo.toml @@ -0,0 +1,28 @@ +[package] +name = "bakashrot-storage" +description = "BakaShrot's database: SQLite, schema v9, messages by stream, attachments, read-only queries." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +authors.workspace = true +repository.workspace = true +publish.workspace = true + +[dependencies] +# The limits (message ids, attachment parts). +bakashrot-proto = { path = "../bakashrot-proto" } +# Synchronous, as the config says it. +bakashrot-config = { path = "../bakashrot-config" } +# SQLite itself compiled in (`bundled`): the same version everywhere, with +# its JSON functions, no system library to install. `fallible_uint`: u64 +# in and out, an error past i64::MAX instead of a wrap. +rusqlite = { version = "0.42.0", features = ["bundled", "fallible_uint"] } +# Query results as JSON. +serde_json = "1.0.154" + +[lints] +workspace = true + +[dev-dependencies] +serde_json = "1.0.154" diff --git a/crates/bakashrot-storage/src/batch.rs b/crates/bakashrot-storage/src/batch.rs new file mode 100644 index 0000000..166bffa --- /dev/null +++ b/crates/bakashrot-storage/src/batch.rs @@ -0,0 +1,435 @@ +//! Writing: the writer's connection, and what a batch (one transaction) +//! does. + +use crate::{ + AttachmentState, Error, MAX_STREAMS, Result, find_stream, message_key, part_key, part_keys, + stream_keys, +}; +use bakashrot_proto::limits::{ + ATTACHMENT_PART_SIZE, MAX_ATTACHMENT_SIZE, MAX_MESSAGE_ID, attachment_part_len, +}; +use bakashrot_proto::packets::ReplicatedMessage; +use rusqlite::{Connection, OptionalExtension, Transaction, TransactionBehavior}; + +/// The connection that writes (one per database). +#[derive(Debug)] +pub struct Writer { + connection: Connection, +} + +impl Writer { + pub(crate) fn new(connection: Connection) -> Writer { + Writer { connection } + } + + /// Runs `write` in one transaction, committed if it returns `Ok`, + /// rolled back otherwise. Each operation of a [`Batch`] is all or + /// nothing on its own, so `write` may go on after one fails: many + /// pushes in one batch are a group commit, one disk flush for all. + pub fn batch(&mut self, write: impl FnOnce(&mut Batch<'_>) -> Result) -> Result { + let mut batch = Batch { + transaction: self + .connection + .transaction_with_behavior(TransactionBehavior::Immediate)?, + }; + let value = write(&mut batch)?; + batch.transaction.commit()?; + Ok(value) + } + + /// Gives the space of deleted messages back to the disk: rewrites the + /// database (`VACUUM`), then empties the WAL. SQLite reuses that space + /// by itself; this only shrinks the file. Slow on a big database, and + /// every other write waits meanwhile: the old server's `vacuum` + /// command. + pub fn vacuum(&mut self) -> Result<()> { + self.connection.execute_batch("VACUUM")?; + self.connection + .query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(()))?; + Ok(()) + } +} + +/// What's written in one transaction ([`Writer::batch`]). Names come +/// checked (`bakashrot_proto`'s decoding). Attachment ids are this +/// database's own, from [`Batch::start_upload`] or +/// [`Reader::attachment`](crate::Reader::attachment). +#[derive(Debug)] +pub struct Batch<'c> { + transaction: Transaction<'c>, +} + +impl Batch<'_> { + /// Stores a pushed message: the next id of its topic and node (from 1), + /// which it returns. Without a savepoint, the hot path: a push that + /// fails leaves at most its topic and node's (empty) stream. + pub fn push(&mut self, topic: &str, node: &str, pushed_at: u64, data: &str) -> Result { + Ok(insert_pushed(&self.transaction, topic, node, pushed_at, data)?.0) + } + + /// Stores a pushed message with its attachment, an upload all of whose + /// parts came ([`Batch::write_part`] said so) and whose SHA-256 the + /// caller checked: the attachment is then `ready`. + pub fn push_with_attachment( + &mut self, + upload: i64, + topic: &str, + node: &str, + pushed_at: u64, + data: &str, + ) -> Result { + self.atomic(|db| { + let (state, size, received) = attachment(db, upload)?; + if state != AttachmentState::Uploading || received != size { + return Err(Error::Invalid(format!( + "attachment {upload} isn't a complete upload" + ))); + } + let (id, key) = insert_pushed(db, topic, node, pushed_at, data)?; + set_attachment(db, upload, "message_key = ?2, state = 'ready'", key)?; + Ok(id) + }) + } + + /// Starts an upload: an attachment pushed with its message, whose parts + /// come next. Returns its id. + pub fn start_upload(&mut self, size: u64, sha256: &[u8; 32]) -> Result { + if !(1..=MAX_ATTACHMENT_SIZE).contains(&size) { + return Err(Error::TooBig(format!( + "an attachment of {size} bytes: 1 to {MAX_ATTACHMENT_SIZE}" + ))); + } + self.atomic(|db| { + db.execute( + "INSERT INTO attachments (size, sha256, state) VALUES (?1, ?2, 'uploading')", + (size, sha256), + )?; + Ok(db.last_insert_rowid()) + }) + } + + /// Stores the next part of an upload or of a replicated attachment: in + /// order, each of its exact size (`attachment_part_len`). Returns + /// whether that was the last one. + pub fn write_part(&mut self, attachment_id: i64, part: u64, data: &[u8]) -> Result { + self.atomic(|db| { + let (state, size, received) = attachment(db, attachment_id)?; + if state != AttachmentState::Uploading && state != AttachmentState::Replicating { + return Err(Error::Invalid(format!( + "attachment {attachment_id} is {state}, it takes no parts" + ))); + } + // Every part but the last is whole: what came is whole parts. + let next = received / ATTACHMENT_PART_SIZE; + if received == size || part != next { + return Err(Error::Invalid(format!( + "part {part} of attachment {attachment_id}: part {next} is next" + ))); + } + let expected = attachment_part_len(size, part); + if data.len() as u64 != expected { + return Err(Error::Invalid(format!( + "part {part} of attachment {attachment_id}: {} bytes, {expected} expected", + data.len() + ))); + } + db.prepare_cached("INSERT INTO attachment_parts (key, part_data) VALUES (?1, ?2)")? + .execute((part_key(attachment_id, part), data))?; + set_attachment(db, attachment_id, "received = received + ?2", expected)?; + Ok(received + expected == size) + }) + } + + /// Drops an upload that won't be pushed: cut short, or not matching its + /// SHA-256. + pub fn cancel_upload(&mut self, upload: i64) -> Result<()> { + self.atomic(|db| { + if attachment(db, upload)?.0 != AttachmentState::Uploading { + return Err(Error::Invalid(format!( + "attachment {upload} isn't an upload" + ))); + } + delete_attachment(db, upload) + }) + } + + /// Stores messages a peer sent for `topic` and `node`, with their own + /// ids, in order; ones already here are kept as they are. Their + /// attachments are noted, to be asked for (`replicating`), or never if + /// bigger than `max_attachment_size` (`too_big`). Ones pushed before + /// `skip_before` (ms, past their age here) aren't stored, but count as + /// received. Returns the topic and node's last id. + pub fn replicate( + &mut self, + topic: &str, + node: &str, + messages: &[ReplicatedMessage], + max_attachment_size: u64, + skip_before: u64, + ) -> Result { + self.atomic(|db| { + let (stream, mut last_id) = stream(db, topic, node)?; + let mut insert = db.prepare_cached( + "INSERT OR IGNORE INTO data (key, pushed_at, message_data) VALUES (?1, ?2, ?3)", + )?; + let mut attach = db.prepare_cached( + "INSERT INTO attachments (message_key, size, sha256, state) VALUES (?1, ?2, ?3, ?4)", + )?; + for message in messages { + if !(1..=MAX_MESSAGE_ID).contains(&message.id) { + return Err(Error::Invalid(format!("message id {}", message.id))); + } + // What the trigger keeps: one ignored was here, below it. + last_id = last_id.max(message.id); + if message.pushed_at < skip_before { + continue; + } + let key = message_key(stream, message.id); + let stored = insert.execute((key, message.pushed_at, &message.data))? == 1; + if let (true, Some(attachment)) = (stored, &message.attachment) { + let state = if attachment.size > max_attachment_size { + AttachmentState::TooBig + } else { + AttachmentState::Replicating + }; + attach.execute((key, attachment.size, &attachment.sha256, state))?; + } + } + // The skipped ones move it too. + db.prepare_cached("UPDATE streams SET last_id = ?2 WHERE stream_id = ?1")? + .execute((stream, last_id))?; + Ok(last_id) + }) + } + + /// A replicated attachment all of whose parts came: `matches` its + /// SHA-256 (the caller checked), it's `ready`; otherwise its parts are + /// dropped and it's asked for again from the start. + pub fn finish_replicated(&mut self, attachment_id: i64, matches: bool) -> Result<()> { + self.atomic(|db| { + let (state, size, received) = attachment(db, attachment_id)?; + if state != AttachmentState::Replicating || received != size { + return Err(Error::Invalid(format!( + "attachment {attachment_id} isn't a complete replicated one" + ))); + } + if matches { + set_attachment(db, attachment_id, "state = ?2", AttachmentState::Ready) + } else { + delete_parts(db, attachment_id, None)?; + set_attachment(db, attachment_id, "received = ?2", 0) + } + }) + } + + /// A ready attachment found not to match its SHA-256 (a damaged + /// disk, a bug): its parts go, it's asked for again from its peers + /// (`replicating`), and not served meanwhile. + pub fn damaged(&mut self, attachment_id: i64) -> Result<()> { + self.atomic(|db| { + if attachment(db, attachment_id)?.0 != AttachmentState::Ready { + return Err(Error::Invalid(format!( + "attachment {attachment_id} isn't a ready one" + ))); + } + delete_parts(db, attachment_id, None)?; + db.prepare_cached( + "UPDATE attachments SET state = 'replicating', received = 0 \ + WHERE attachment_id = ?1", + )? + .execute([attachment_id])?; + Ok(()) + }) + } + + /// Retention: deletes `topic`'s messages pushed before `cutoff` (ms), + /// `limit` at most (call again while it returns `limit`). Each stream + /// is read from its oldest message and stops at the first one it keeps: + /// only what's deleted is read. So messages go in id order: one stamped + /// earlier than the one before it (a clock set back) waits for it. + pub fn delete_before(&mut self, topic: &str, cutoff: u64, limit: usize) -> Result { + self.atomic(|db| { + let streams: Vec = db + .prepare_cached("SELECT stream_id FROM streams WHERE topic = ?1")? + .query_map([topic], |row| row.get(0))? + .collect::>()?; + let mut oldest = db.prepare_cached( + "SELECT key, pushed_at FROM data WHERE key BETWEEN ?1 AND ?2 ORDER BY key", + )?; + let mut deleted = 0; + for stream in streams { + let (first, last) = stream_keys(stream); + let mut up_to = None; + let mut rows = oldest.query((first, last))?; + while deleted < limit { + let Some(row) = rows.next()? else { break }; + if row.get::<_, u64>(1)? >= cutoff { + break; + } + up_to = Some(row.get::<_, i64>(0)?); + deleted += 1; + } + drop(rows); + if let Some(up_to) = up_to { + db.execute( + "DELETE FROM data WHERE key BETWEEN ?1 AND ?2", + (first, up_to), + )?; + } + if deleted == limit { + break; + } + } + Ok(deleted) + }) + } + + /// Deletes the parts of attachments whose message was deleted, + /// `max_parts` at most (call again while it returns `max_parts`), and + /// their rows once they have none left. + pub fn purge_attachments(&mut self, max_parts: usize) -> Result { + self.atomic(|db| { + let deleting: Vec = db + .prepare_cached( + "SELECT attachment_id FROM attachments WHERE state = 'deleting' \ + ORDER BY attachment_id", + )? + .query_map([], |row| row.get(0))? + .collect::>()?; + let mut purged = 0; + for attachment_id in deleting { + purged += delete_parts(db, attachment_id, Some(max_parts - purged))?; + if purged == max_parts { + break; + } + db.execute( + "DELETE FROM attachments WHERE attachment_id = ?1", + [attachment_id], + )?; + } + Ok(purged) + }) + } + + /// Runs one operation all or nothing (a savepoint), so the batch can go + /// on after it fails. + fn atomic(&mut self, operation: impl FnOnce(&Connection) -> Result) -> Result { + let savepoint = self.transaction.savepoint()?; + let value = operation(&savepoint)?; + savepoint.commit()?; + Ok(value) + } +} + +/// A topic and node's stream, made if new: its id and last id. +fn stream(db: &Connection, topic: &str, node: &str) -> Result<(i64, u64)> { + if let Some(found) = find_stream(db, topic, node)? { + return Ok(found); + } + let next: i64 = db.query_row( + "SELECT coalesce(max(stream_id), 0) + 1 FROM streams", + [], + |row| row.get(0), + )?; + if next > MAX_STREAMS { + return Err(Error::TooBig(format!( + "{topic}/{node}: this database has {MAX_STREAMS} topic and node pairs already" + ))); + } + db.execute( + "INSERT INTO streams (stream_id, topic, node) VALUES (?1, ?2, ?3)", + (next, topic, node), + )?; + Ok((next, 0)) +} + +/// Inserts a pushed message with the next id of its stream: the id and the +/// message's key. +fn insert_pushed( + db: &Connection, + topic: &str, + node: &str, + pushed_at: u64, + data: &str, +) -> Result<(u64, i64)> { + let (stream, last_id) = stream(db, topic, node)?; + let id = last_id + 1; + if id > MAX_MESSAGE_ID { + return Err(Error::TooBig(format!("{topic}/{node}: no message id left"))); + } + let key = message_key(stream, id); + db.prepare_cached("INSERT INTO data (key, pushed_at, message_data) VALUES (?1, ?2, ?3)")? + .execute((key, pushed_at, data))?; + Ok((id, key)) +} + +/// An attachment's state, size and bytes received. +fn attachment(db: &Connection, attachment_id: i64) -> Result<(AttachmentState, u64, u64)> { + db.prepare_cached("SELECT state, size, received FROM attachments WHERE attachment_id = ?1")? + .query_row([attachment_id], |row| { + Ok((row.get(0)?, row.get(1)?, row.get(2)?)) + }) + .optional()? + .ok_or_else(|| Error::NotFound(format!("no attachment {attachment_id}"))) +} + +/// `UPDATE attachments SET ` of one, `?2` being `value`. +fn set_attachment( + db: &Connection, + attachment_id: i64, + set: &str, + value: impl rusqlite::ToSql, +) -> Result<()> { + db.prepare_cached(&format!( + "UPDATE attachments SET {set} WHERE attachment_id = ?1" + ))? + .execute((attachment_id, value))?; + Ok(()) +} + +/// Deletes an attachment's parts, `limit` at most: how many. +fn delete_parts(db: &Connection, attachment_id: i64, limit: Option) -> Result { + let (first, last) = part_keys(attachment_id); + let limit = limit.map_or(-1, |limit| limit as i64); + Ok(db + .prepare_cached( + "DELETE FROM attachment_parts WHERE key IN \ + (SELECT key FROM attachment_parts WHERE key BETWEEN ?1 AND ?2 LIMIT ?3)", + )? + .execute((first, last, limit))?) +} + +/// Deletes an attachment and its parts. +fn delete_attachment(db: &Connection, attachment_id: i64) -> Result<()> { + delete_parts(db, attachment_id, None)?; + db.execute( + "DELETE FROM attachments WHERE attachment_id = ?1", + [attachment_id], + )?; + Ok(()) +} + +/// At start: deletes every upload (none of them can be pushed any more), +/// and starts over the replicated attachments all of whose parts came but +/// weren't checked (stopped in between). +pub(crate) fn clean_up(db: &Connection) -> Result<()> { + let unchecked: Vec = db + .prepare( + "SELECT attachment_id FROM attachments \ + WHERE state = 'replicating' AND received = size", + )? + .query_map([], |row| row.get(0))? + .collect::>()?; + for attachment_id in unchecked { + delete_parts(db, attachment_id, None)?; + set_attachment(db, attachment_id, "received = ?2", 0)?; + } + let uploads: Vec = db + .prepare("SELECT attachment_id FROM attachments WHERE state = 'uploading'")? + .query_map([], |row| row.get(0))? + .collect::>()?; + for upload in uploads { + delete_attachment(db, upload)?; + } + Ok(()) +} diff --git a/crates/bakashrot-storage/src/database.rs b/crates/bakashrot-storage/src/database.rs new file mode 100644 index 0000000..c94ad1a --- /dev/null +++ b/crates/bakashrot-storage/src/database.rs @@ -0,0 +1,194 @@ +//! Opening a database: making a new one, or checking and migrating one, +//! and the connections to it. + +use crate::{Error, QueryRunner, Reader, Result, SCHEMA_VERSION, Writer}; +use bakashrot_config::Synchronous; +use rusqlite::{Connection, OptionalExtension, TransactionBehavior}; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +/// `PRAGMA application_id` of a BakaShrot database: "BSHT". +const APPLICATION_ID: i64 = 0x4253_4854; + +/// The schema, made in one go. +const SCHEMA: &str = include_str!("schema_v9.sql"); + +/// Migrations from v9 on: the version each makes, and its SQL. Applied in +/// order from the database's version, each in one transaction with +/// `schema_version` set. None yet. +const MIGRATIONS: &[(i64, &str)] = &[]; + +/// How long a connection waits for another's lock before failing. +const BUSY_TIMEOUT: Duration = Duration::from_secs(5); + +/// The WAL's size, in pages, past which the writer checkpoints it itself +/// (SQLite's default is 1000): a backstop when the [`Checkpointer`] can't +/// keep up. +pub const WRITER_CHECKPOINT_PAGES: u32 = 10_000; + +/// Copies the WAL into the database on a connection of its own, so the +/// writer doesn't do it in the middle of a commit (the old server's way: +/// `OldSource/Server/Storage/Writer.pbi`). +#[derive(Debug)] +pub struct Checkpointer { + connection: Connection, +} + +impl Checkpointer { + /// Copies what it can without waiting for anyone (`PASSIVE`). + pub fn checkpoint(&self) -> Result<()> { + self.connection + .query_row("PRAGMA wal_checkpoint(PASSIVE)", [], |_| Ok(()))?; + Ok(()) + } +} + +/// A database, opened and checked once: hands out connections to it. +#[derive(Debug, Clone)] +pub struct Database { + path: PathBuf, + synchronous: Synchronous, +} + +impl Database { + /// Opens the database at `path`: makes it if there's none (or it's an + /// empty file), migrates an older one, refuses one that isn't a + /// BakaShrot database of a version this one reads. Then deletes the + /// uploads left over (their pushes never finished). + pub fn open(path: &Path, synchronous: Synchronous) -> Result { + let database = Database { + path: path.to_owned(), + synchronous, + }; + let mut connection = database.connect()?; + let transaction = connection.transaction_with_behavior(TransactionBehavior::Immediate)?; + let application_id: i64 = + transaction.query_row("PRAGMA application_id", [], |row| row.get(0))?; + let tables: i64 = + transaction.query_row("SELECT count(*) FROM sqlite_schema", [], |row| row.get(0))?; + if application_id == 0 && tables == 0 { + transaction.execute_batch(SCHEMA)?; + transaction.execute( + "INSERT INTO metadata (name, value) VALUES ('created_by', ?1)", + [concat!("bakashrot-storage ", env!("CARGO_PKG_VERSION"))], + )?; + } else if application_id != APPLICATION_ID { + return Err(Error::Unusable(unusable(&transaction, path)?)); + } + let mut version = schema_version(&transaction)?; + if version > SCHEMA_VERSION { + return Err(Error::Unusable(format!( + "{}: schema v{version}, made by a newer version (this one reads v{SCHEMA_VERSION})", + path.display() + ))); + } + for (made, sql) in MIGRATIONS { + if *made == version + 1 { + transaction.execute_batch(sql)?; + transaction.execute( + "UPDATE metadata SET value = ?1 WHERE name = 'schema_version'", + [made], + )?; + version = *made; + } + } + if version != SCHEMA_VERSION { + return Err(Error::Unusable(format!( + "{}: schema v{version}, which this version can't migrate", + path.display() + ))); + } + crate::batch::clean_up(&transaction)?; + transaction.commit()?; + Ok(database) + } + + /// The connection that writes. Only one at a time should: a second + /// waits for the first's transactions (up to 5 s, then fails). It only + /// checkpoints the WAL itself past [`WRITER_CHECKPOINT_PAGES`]: a + /// [`Checkpointer`] keeps that off its way. + pub fn writer(&self) -> Result { + let connection = self.connect()?; + connection.pragma_update(None, "wal_autocheckpoint", WRITER_CHECKPOINT_PAGES)?; + Ok(Writer::new(connection)) + } + + /// A connection that copies the WAL into the database, off the + /// writer's way: call [`Checkpointer::checkpoint`] every second or so. + pub fn checkpointer(&self) -> Result { + Ok(Checkpointer { + connection: self.connect()?, + }) + } + + /// A connection that reads, as many as needed. + pub fn reader(&self) -> Result { + Ok(Reader::new(self.connect()?)) + } + + /// A connection for clients' queries: read-only (`query_only`). + pub fn query_runner(&self) -> Result { + let connection = self.connect()?; + connection.pragma_update(None, "query_only", true)?; + Ok(QueryRunner::new(connection)) + } + + /// A connection with this database's settings: WAL, `synchronous`, the + /// busy timeout. + fn connect(&self) -> Result { + let connection = Connection::open(&self.path)?; + connection.busy_timeout(BUSY_TIMEOUT)?; + let mode: String = + connection.query_row("PRAGMA journal_mode = WAL", [], |row| row.get(0))?; + if !mode.eq_ignore_ascii_case("wal") { + return Err(Error::Unusable(format!( + "{}: can't be put in WAL mode (it's in {mode})", + self.path.display() + ))); + } + let synchronous = match self.synchronous { + Synchronous::Full => "FULL", + Synchronous::Normal => "NORMAL", + }; + connection.pragma_update(None, "synchronous", synchronous)?; + Ok(connection) + } +} + +/// `metadata`'s `schema_version`. +fn schema_version(connection: &Connection) -> Result { + let has_metadata: bool = connection.query_row( + "SELECT count(*) > 0 FROM sqlite_schema WHERE type = 'table' AND name = 'metadata'", + [], + |row| row.get(0), + )?; + let version = if has_metadata { + connection + .query_row( + "SELECT value FROM metadata WHERE name = 'schema_version'", + [], + |row| row.get(0), + ) + .optional()? + } else { + None + }; + version.ok_or_else(|| Error::Unusable("a BakaShrot database without its schema version".into())) +} + +/// Why a database that isn't ours can't be opened, in words. +fn unusable(connection: &Connection, path: &Path) -> Result { + let old: bool = connection.query_row( + "SELECT count(*) > 0 FROM sqlite_schema WHERE type = 'table' AND name = 'node_heads'", + [], + |row| row.get(0), + )?; + Ok(if old { + format!( + "{}: made by the old server (schema v8), which this one doesn't read: start a new database", + path.display() + ) + } else { + format!("{}: not a BakaShrot database", path.display()) + }) +} diff --git a/crates/bakashrot-storage/src/lib.rs b/crates/bakashrot-storage/src/lib.rs new file mode 100644 index 0000000..cd8adba --- /dev/null +++ b/crates/bakashrot-storage/src/lib.rs @@ -0,0 +1,265 @@ +//! BakaShrot's database: SQLite, schema v9 (`schema_v9.sql`). +//! +//! - [`Database`]: opens one (creating it, or checking it's a v9 one), +//! and hands out connections. +//! - [`Writer`]: the one connection that writes. Everything is written in +//! a [`Batch`], one transaction: pushes, replication, attachments, +//! retention. Many pushes in one batch is a group commit. And +//! [`Writer::vacuum`], to shrink the file. +//! - [`Reader`]: as many as needed, reading while the writer writes (WAL). +//! - [`QueryRunner`]: clients' read-only SQL, on a read-only connection. +//! +//! **Everything is by name:** topics, nodes, message ids, times, as on the +//! wire. Streams (one node's messages in one topic) and the packed keys +//! that store them stay inside this crate: `docs/storage.md`. +//! +//! **Blocking:** SQLite is. The server runs these on threads of their own +//! (the writer on one, readers on a pool), not on its async tasks. + +mod batch; +mod database; +mod query; +mod reader; + +pub use batch::{Batch, Writer}; +pub use database::{Checkpointer, Database, WRITER_CHECKPOINT_PAGES}; +pub use query::{MAX_QUERY_BYTES, MAX_QUERY_ROWS, QueryRunner}; +pub use reader::{Attachment, MESSAGES_BYTES, Reader}; + +use bakashrot_proto::limits::{MAX_ATTACHMENT_PARTS, MAX_MESSAGE_ID}; +use rusqlite::types::{FromSql, FromSqlError, FromSqlResult, ToSql, ToSqlOutput, ValueRef}; +use rusqlite::{Connection, OptionalExtension}; +use std::fmt; + +/// The schema version this crate makes and reads. +pub const SCHEMA_VERSION: i64 = 9; + +/// The most streams (topic and node pairs) a database holds: 2^20 - 1. +pub const MAX_STREAMS: i64 = (1 << STREAM_BITS) - 1; + +/// What went wrong. The server answers each with its own refusal code. +#[derive(Debug)] +pub enum Error { + /// SQLite failed (the disk, a lock held too long...): `ServerError`. + Sqlite(rusqlite::Error), + /// A database this version doesn't open: another program's, the old + /// server's, a newer schema's. Said at start. + Unusable(String), + /// A request that doesn't fit what's stored: a part out of order or of + /// the wrong size, an attachment in the wrong state: `InvalidRequest`. + Invalid(String), + /// No such attachment: `NotFound`. + NotFound(String), + /// A node without any message, in any topic: `UnknownName`. + UnknownName(String), + /// Over a limit: streams, message ids, a query's result: `TooBig`. + TooBig(String), + /// A client's query that failed or isn't read-only: `QueryFailed`. + Query(String), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::Sqlite(error) => write!(f, "database: {error}"), + Error::Unusable(what) + | Error::Invalid(what) + | Error::NotFound(what) + | Error::UnknownName(what) + | Error::TooBig(what) + | Error::Query(what) => f.write_str(what), + } + } +} + +impl std::error::Error for Error { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Error::Sqlite(error) => Some(error), + _ => None, + } + } +} + +impl From for Error { + fn from(error: rusqlite::Error) -> Self { + Error::Sqlite(error) + } +} + +/// A result of this crate. +pub type Result = std::result::Result; + +/// Where an attachment is at (`docs/storage.md`, "Attachments"). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AttachmentState { + /// Pushed, its parts coming, no message yet. + Uploading, + /// Its message came from a peer, its parts come after. + Replicating, + /// All here, checked. + Ready, + /// Bigger than this server keeps: never asked for. + TooBig, + /// Its message was deleted, its parts go in the background. + Deleting, +} + +impl AttachmentState { + const ALL: [AttachmentState; 5] = [ + AttachmentState::Uploading, + AttachmentState::Replicating, + AttachmentState::Ready, + AttachmentState::TooBig, + AttachmentState::Deleting, + ]; + + /// As the database writes it. + pub fn as_str(self) -> &'static str { + match self { + AttachmentState::Uploading => "uploading", + AttachmentState::Replicating => "replicating", + AttachmentState::Ready => "ready", + AttachmentState::TooBig => "too_big", + AttachmentState::Deleting => "deleting", + } + } +} + +impl fmt::Display for AttachmentState { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) + } +} + +impl ToSql for AttachmentState { + fn to_sql(&self) -> rusqlite::Result> { + Ok(self.as_str().into()) + } +} + +impl FromSql for AttachmentState { + fn column_result(value: ValueRef<'_>) -> FromSqlResult { + let text = value.as_str()?; + Self::ALL + .into_iter() + .find(|state| state.as_str() == text) + .ok_or(FromSqlError::InvalidType) + } +} + +/// A topic and node's stream, if it has one: its id and last id. +fn find_stream(db: &Connection, topic: &str, node: &str) -> rusqlite::Result> { + db.prepare_cached("SELECT stream_id, last_id FROM streams WHERE topic = ?1 AND node = ?2")? + .query_row((topic, node), |row| Ok((row.get(0)?, row.get(1)?))) + .optional() +} + +// The packed keys (storage.md, "Keys"). Only these know the layout (and +// the schema's generated columns, which a test checks against them). + +/// Bits of a message id in `data.key`, below the stream's. +const ID_BITS: u32 = 43; +/// Bits of a stream id above them: 43 + 20 = 63, a positive i64. +const STREAM_BITS: u32 = 20; +/// Bits of a part's index in `attachment_parts.key`. +const PART_BITS: u32 = 20; +const ID_MASK: i64 = (1 << ID_BITS) - 1; + +const _: () = assert!(MAX_MESSAGE_ID == ID_MASK as u64, "ids fill their bits"); +const _: () = assert!(MAX_ATTACHMENT_PARTS == 1 << PART_BITS, "parts fill theirs"); + +/// `data.key` of a stream's message. +fn message_key(stream: i64, id: u64) -> i64 { + (stream << ID_BITS) | id as i64 +} + +/// The message id in a `data.key`. +fn message_id(key: i64) -> u64 { + (key & ID_MASK) as u64 +} + +/// The first and last `data.key` a stream can have. +fn stream_keys(stream: i64) -> (i64, i64) { + (message_key(stream, 1), message_key(stream, MAX_MESSAGE_ID)) +} + +/// `attachment_parts.key` of an attachment's part. +fn part_key(attachment: i64, part: u64) -> i64 { + (attachment << PART_BITS) | part as i64 +} + +/// The first and last `attachment_parts.key` an attachment can have. +fn part_keys(attachment: i64) -> (i64, i64) { + ( + part_key(attachment, 0), + part_key(attachment, MAX_ATTACHMENT_PARTS - 1), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn keys() { + let key = message_key(MAX_STREAMS, MAX_MESSAGE_ID); + assert_eq!(key, i64::MAX); + assert_eq!(message_id(key), MAX_MESSAGE_ID); + assert_eq!(key >> ID_BITS, MAX_STREAMS); + assert_eq!(message_id(message_key(5, 42)), 42); + let (first, last) = stream_keys(2); + assert!(stream_keys(1).1 < first && last < stream_keys(3).0); + let (first, last) = part_keys(7); + assert_eq!(last - first + 1, MAX_ATTACHMENT_PARTS as i64); + assert!(part_keys(6).1 < first); + } + + #[test] + fn the_schema_unpacks_keys_the_same() { + let db = Connection::open_in_memory().unwrap(); + db.execute_batch(include_str!("schema_v9.sql")).unwrap(); + db.execute( + "INSERT INTO streams (stream_id, topic, node) VALUES (?1, 't', 'n')", + [MAX_STREAMS], + ) + .unwrap(); + for (stream, id) in [(1, 1), (MAX_STREAMS, MAX_MESSAGE_ID), (77, 123_456_789)] { + let key = message_key(stream, id); + db.execute( + "INSERT INTO data (key, pushed_at, message_data) VALUES (?1, 1, '')", + [key], + ) + .unwrap(); + let (sql_stream, sql_id): (i64, u64) = db + .query_row( + "SELECT stream_id, message_id FROM data WHERE key = ?1", + [key], + |r| Ok((r.get(0)?, r.get(1)?)), + ) + .unwrap(); + assert_eq!((sql_stream, sql_id), (stream, id)); + } + // The trigger reads the same id. + let last: u64 = db + .query_row( + "SELECT last_id FROM streams WHERE stream_id = ?1", + [MAX_STREAMS], + |r| r.get(0), + ) + .unwrap(); + assert_eq!(last, MAX_MESSAGE_ID); + } + + #[test] + fn states_round_trip() { + let db = Connection::open_in_memory().unwrap(); + for state in AttachmentState::ALL { + let back: AttachmentState = db.query_row("SELECT ?1", [state], |r| r.get(0)).unwrap(); + assert_eq!(back, state); + } + let wrong: rusqlite::Result = + db.query_row("SELECT 'lost'", [], |r| r.get(0)); + assert!(wrong.is_err()); + } +} diff --git a/crates/bakashrot-storage/src/query.rs b/crates/bakashrot-storage/src/query.rs new file mode 100644 index 0000000..e0667ab --- /dev/null +++ b/crates/bakashrot-storage/src/query.rs @@ -0,0 +1,95 @@ +//! Clients' read-only SQL (`Query`), as the old server ran it. +//! +//! Read-only three ways: the connection has `query_only` on (SQLite +//! refuses any write), the statement must be one SQLite says only reads +//! (`sqlite3_stmt_readonly`), and only one statement runs (more is an +//! error, not ignored). The result is JSON, every value a string or null +//! (as in protocol 6): `{"columns":[...],"rows":[[...],...]}`. + +use crate::{Error, Result}; +use bakashrot_proto::limits::MAX_MESSAGE_SIZE; +use rusqlite::Connection; +use rusqlite::types::ValueRef; +use serde_json::Value; + +/// The most rows a query returns, as before. +pub const MAX_QUERY_ROWS: usize = 10_000; + +/// The biggest result, in bytes of JSON: what a packet carries. +pub const MAX_QUERY_BYTES: usize = MAX_MESSAGE_SIZE; + +/// A read-only connection for clients' queries. +#[derive(Debug)] +pub struct QueryRunner { + connection: Connection, +} + +impl QueryRunner { + pub(crate) fn new(connection: Connection) -> QueryRunner { + QueryRunner { connection } + } + + /// Runs one read-only statement: its result as JSON. Refused + /// ([`Error::Query`]) if it isn't one, or fails (SQLite's message, a + /// failing row included: never a partial result); [`Error::TooBig`] + /// past [`MAX_QUERY_ROWS`] or [`MAX_QUERY_BYTES`]. + pub fn run(&self, sql: &str) -> Result { + let failed = |error: rusqlite::Error| Error::Query(explain(error.to_string())); + let mut statement = self.connection.prepare(sql).map_err(failed)?; + if !statement.readonly() || statement.column_count() == 0 { + return Err(Error::Query("only queries that read are allowed".into())); + } + let columns: Vec = statement.column_names().map(str::to_owned).collect(); + let width = columns.len(); + let mut rows: Vec> = Vec::new(); + let mut bytes = 0; + let mut results = statement.query([]).map_err(failed)?; + while let Some(row) = results.next().map_err(failed)? { + if rows.len() == MAX_QUERY_ROWS { + return Err(Error::TooBig(format!( + "more than {MAX_QUERY_ROWS} rows: narrow the query (LIMIT)" + ))); + } + let mut values = Vec::with_capacity(width); + for column in 0..width { + let value = text(row.get_ref(column).map_err(failed)?); + // Its JSON's size, about: quotes, escapes aside. + bytes += value.as_str().map_or(5, |text| text.len() + 3); + values.push(value); + } + if bytes > MAX_QUERY_BYTES { + return Err(Error::TooBig(format!( + "a result over {MAX_QUERY_BYTES} bytes: narrow the query" + ))); + } + rows.push(values); + } + let json = serde_json::json!({ "columns": columns, "rows": rows }).to_string(); + if json.len() > MAX_QUERY_BYTES { + return Err(Error::TooBig(format!( + "a result over {MAX_QUERY_BYTES} bytes: narrow the query" + ))); + } + Ok(json) + } +} + +/// SQLite's error, with a hint where the old server gave one. +fn explain(why: String) -> String { + if why.contains("malformed JSON") { + format!("{why} (a row isn't JSON: add is_json = 1 to the WHERE)") + } else { + why + } +} + +/// A value as text, or null: numbers as SQLite writes them, blobs in hex. +fn text(value: ValueRef<'_>) -> Value { + match value { + ValueRef::Null => Value::Null, + ValueRef::Integer(number) => Value::String(number.to_string()), + ValueRef::Real(number) => Value::String(format!("{number:?}")), + ValueRef::Text(text) => Value::String(String::from_utf8_lossy(text).into_owned()), + ValueRef::Blob(bytes) => Value::String(bytes.iter().map(|b| format!("{b:02x}")).collect()), + } +} diff --git a/crates/bakashrot-storage/src/reader.rs b/crates/bakashrot-storage/src/reader.rs new file mode 100644 index 0000000..1e4acef --- /dev/null +++ b/crates/bakashrot-storage/src/reader.rs @@ -0,0 +1,275 @@ +//! Reading: messages, names, what replication compares, attachments. +//! Answers are the protocol's own types where it has them. + +use crate::{ + AttachmentState, Error, Result, find_stream, message_id, message_key, part_key, stream_keys, +}; +use bakashrot_proto::limits::{ATTACHMENT_PART_SIZE, MAX_MESSAGE_ID}; +use bakashrot_proto::packets::{ + Attachment as Sent, Head, MessageEntry, Messages, MissingAttachment, ReplicatedMessage, + StoredAttachment, +}; +use rusqlite::{Connection, OptionalExtension, Row}; + +/// About how many bytes of messages one answer carries: past it, the rest +/// is left for the next request (`more`). A bigger message goes alone. +pub const MESSAGES_BYTES: usize = 1024 * 1024; + +/// A stream's messages after a key, in order (`?1` that key, `?2` the +/// stream's last possible one), with their attachments. +const AFTER: &str = "SELECT d.key, d.pushed_at, d.message_data, a.size, a.state \ + FROM data d LEFT JOIN attachments a ON a.message_key = d.key \ + WHERE d.key > ?1 AND d.key <= ?2 ORDER BY d.key LIMIT ?3"; + +/// A stream's last messages, newest first (`?1`, `?2`: its key range). +const LATEST: &str = "SELECT d.key, d.pushed_at, d.message_data, a.size, a.state \ + FROM data d LEFT JOIN attachments a ON a.message_key = d.key \ + WHERE d.key >= ?1 AND d.key <= ?2 ORDER BY d.key DESC LIMIT ?3"; + +/// A stream's messages after a key, as replication sends them. +const TO_REPLICATE: &str = "SELECT d.key, d.pushed_at, d.message_data, a.size, a.sha256 \ + FROM data d LEFT JOIN attachments a ON a.message_key = d.key \ + WHERE d.key > ?1 AND d.key <= ?2 ORDER BY d.key LIMIT ?3"; + +/// A connection that reads. +#[derive(Debug)] +pub struct Reader { + connection: Connection, +} + +/// A message's attachment, as stored. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Attachment { + /// Its id in this database, for [`Reader::read_part`] and the writer. + pub id: i64, + /// Its size. + pub size: u64, + /// Its SHA-256. + pub sha256: [u8; 32], + /// The bytes of it here so far. + pub received: u64, + /// Where it's at. + pub state: AttachmentState, +} + +impl Reader { + pub(crate) fn new(connection: Connection) -> Reader { + Reader { connection } + } + + /// A topic and node's messages: `after` an id (0 for the first ones), + /// in order, or the last ones (`None`); `limit` at most, about + /// [`MESSAGES_BYTES`] at most. `more` if others follow (asking `after` + /// the last one gets them). None for a topic and node without any, + /// [`Error::UnknownName`] for a node without any in every topic. + pub fn messages( + &self, + topic: &str, + node: &str, + after: Option, + limit: u32, + ) -> Result { + let mut answer = Messages { + more: false, + messages: Vec::new(), + }; + let Some((stream, _)) = find_stream(&self.connection, topic, node)? else { + return match self.has_node(node)? { + true => Ok(answer), + false => Err(Error::UnknownName(format!("unknown node '{node}'"))), + }; + }; + let (first, last) = stream_keys(stream); + let (sql, from) = match after { + Some(after) => (AFTER, message_key(stream, after.min(MAX_MESSAGE_ID))), + None => (LATEST, first), + }; + let mut statement = self.connection.prepare_cached(sql)?; + // One more than asked: whether more follow. + let mut rows = statement.query((from, last, i64::from(limit) + 1))?; + let mut bytes = 0; + while let Some(row) = rows.next()? { + let message = entry(row)?; + let full = answer.messages.len() == limit as usize + || (!answer.messages.is_empty() && bytes + message.data.len() > MESSAGES_BYTES); + if full { + answer.more = after.is_some(); + break; + } + bytes += message.data.len(); + answer.messages.push(message); + } + if after.is_none() { + answer.messages.reverse(); + } + Ok(answer) + } + + /// A topic and node's messages after an id, as replication sends them: + /// `limit` at most, about [`MESSAGES_BYTES`] at most (a bigger one + /// alone). None once there are no more. + pub fn to_replicate( + &self, + topic: &str, + node: &str, + after: u64, + limit: u32, + ) -> Result> { + let mut messages = Vec::new(); + let Some((stream, _)) = find_stream(&self.connection, topic, node)? else { + return Ok(messages); + }; + let (_, last) = stream_keys(stream); + let mut statement = self.connection.prepare_cached(TO_REPLICATE)?; + let from = message_key(stream, after.min(MAX_MESSAGE_ID)); + let mut rows = statement.query((from, last, i64::from(limit)))?; + let mut bytes = 0; + while let Some(row) = rows.next()? { + let data: String = row.get(2)?; + if !messages.is_empty() && bytes + data.len() > MESSAGES_BYTES { + break; + } + bytes += data.len(); + let attachment = match row.get::<_, Option>(3)? { + Some(size) => Some(Sent { + size, + sha256: row.get(4)?, + }), + None => None, + }; + messages.push(ReplicatedMessage { + id: message_id(row.get(0)?), + pushed_at: row.get(1)?, + data, + attachment, + }); + } + Ok(messages) + } + + /// Every topic with messages (or that had some), in order. + pub fn topics(&self) -> Result> { + self.strings("SELECT DISTINCT topic FROM streams ORDER BY topic") + } + + /// Every node with messages (or that had some), in order. + pub fn nodes(&self) -> Result> { + self.strings("SELECT DISTINCT node FROM streams ORDER BY node") + } + + /// Whether `node` has messages in any topic (or had some). + fn has_node(&self, node: &str) -> Result { + self.connection + .prepare_cached("SELECT EXISTS (SELECT 1 FROM streams WHERE node = ?1)")? + .query_row([node], |row| row.get(0)) + .map_err(Error::from) + } + + /// Every topic and node's last id: what `SyncState` compares. + pub fn heads(&self) -> Result> { + self.connection + .prepare_cached("SELECT topic, node, last_id FROM streams ORDER BY topic, node")? + .query_map([], |row| { + Ok(Head { + topic: row.get(0)?, + node: row.get(1)?, + last_id: row.get(2)?, + }) + })? + .collect::>() + .map_err(Error::from) + } + + /// A topic and node's last id: 0 if it has none. + pub fn last_id(&self, topic: &str, node: &str) -> Result { + Ok(find_stream(&self.connection, topic, node)?.map_or(0, |(_, last_id)| last_id)) + } + + /// The replicated attachments not all here yet, oldest first, `limit` + /// at most: what `SyncState` asks for, and from which part. + pub fn missing_attachments(&self, limit: usize) -> Result> { + self.connection + .prepare_cached( + "SELECT s.topic, s.node, d.message_id, a.received FROM attachments a \ + JOIN data d ON d.key = a.message_key \ + JOIN streams s ON s.stream_id = d.stream_id \ + WHERE a.state = 'replicating' ORDER BY a.attachment_id LIMIT ?1", + )? + .query_map([limit as i64], |row| { + Ok(MissingAttachment { + topic: row.get(0)?, + node: row.get(1)?, + message_id: row.get(2)?, + next_part: row.get::<_, u64>(3)? / ATTACHMENT_PART_SIZE, + }) + })? + .collect::>() + .map_err(Error::from) + } + + /// A message's attachment, if it has one (none once the message was + /// deleted). + pub fn attachment( + &self, + topic: &str, + node: &str, + message_id: u64, + ) -> Result> { + let Some((stream, _)) = find_stream(&self.connection, topic, node)? else { + return Ok(None); + }; + self.connection + .prepare_cached( + "SELECT attachment_id, size, sha256, received, state FROM attachments \ + WHERE message_key = ?1 AND state <> 'deleting'", + )? + .query_row( + [message_key(stream, message_id.min(MAX_MESSAGE_ID))], + |row| { + Ok(Attachment { + id: row.get(0)?, + size: row.get(1)?, + sha256: row.get(2)?, + received: row.get(3)?, + state: row.get(4)?, + }) + }, + ) + .optional() + .map_err(Error::from) + } + + /// One part of an attachment, if it's here. + pub fn read_part(&self, attachment_id: i64, part: u64) -> Result> { + self.connection + .prepare_cached("SELECT part_data FROM attachment_parts WHERE key = ?1")? + .query_row([part_key(attachment_id, part)], |row| row.get(0)) + .optional()? + .ok_or_else(|| Error::NotFound(format!("part {part} of attachment {attachment_id}"))) + } + + fn strings(&self, sql: &str) -> Result> { + self.connection + .prepare_cached(sql)? + .query_map([], |row| row.get(0))? + .collect::>() + .map_err(Error::from) + } +} + +/// A row of `messages()`'s query, as the protocol carries it. +fn entry(row: &Row<'_>) -> rusqlite::Result { + let attachment = match row.get::<_, Option>(3)? { + Some(size) => Some(StoredAttachment { + size, + ready: row.get::<_, AttachmentState>(4)? == AttachmentState::Ready, + }), + None => None, + }; + Ok(MessageEntry { + id: message_id(row.get(0)?), + pushed_at: row.get(1)?, + data: row.get(2)?, + attachment, + }) +} diff --git a/crates/bakashrot-storage/src/schema_v9.sql b/crates/bakashrot-storage/src/schema_v9.sql new file mode 100644 index 0000000..68ed02d --- /dev/null +++ b/crates/bakashrot-storage/src/schema_v9.sql @@ -0,0 +1,146 @@ +-- BakaShrot's database, schema v9. Read docs/storage.md first: the +-- keys below are packed integers, on purpose, and only bakashrot-storage +-- packs and unpacks them. +-- +-- Not compatible with v8 (OldSource/Server/Storage/db_schema_v8.dbml): a +-- database of the old server isn't opened, its data isn't carried over. +-- Needs SQLite 3.38+ (JSON functions, ->>), bundled with the crate. +-- +-- Run once, in one transaction, on an empty database (Database::open). +-- Every connection then sets journal_mode = WAL, synchronous (the +-- config's) and busy_timeout. No foreign keys: one writer keeps the tables +-- consistent, the CHECKs keep the values valid. +-- +-- Packed keys (storage.md, "Keys"): +-- data.key = stream_id << 43 | message_id +-- attachment_parts.key = attachment_id << 20 | part +-- 8796093022207 below is 2^43 - 1, a message id's mask. + +PRAGMA application_id = 1112754260; -- 'BSHT': a BakaShrot database + +-- About the database itself. schema_version drives migrations: a database +-- without it, or of a version the server doesn't know, is refused; an older +-- one is migrated a version at a time, each step in one transaction that +-- also sets schema_version. +CREATE TABLE metadata ( + name TEXT PRIMARY KEY, + value ANY NOT NULL +) WITHOUT ROWID; + +INSERT INTO metadata (name, value) VALUES + ('schema_version', 9), + ('created_at', CAST(strftime('%s', 'now') AS INTEGER) * 1000); +-- Database::open adds ('created_by', 'bakashrot-storage '). + +-- A stream: one node's messages in one topic. Message ids count per +-- stream, replication compares streams' last ids, GetMessages reads one. +-- Topics and nodes are only names here: a topic's streams are its rows. +-- last_id is the highest id the stream ever had: deleting messages +-- (retention) leaves it, so ids never go back. Kept by trg_data_last_id. +CREATE TABLE streams ( + stream_id INTEGER PRIMARY KEY CHECK (stream_id BETWEEN 1 AND 1048575), + topic TEXT NOT NULL COLLATE NOCASE CHECK (length(topic) BETWEEN 1 AND 64), + node TEXT NOT NULL COLLATE NOCASE CHECK (length(node) BETWEEN 1 AND 64), + last_id INTEGER NOT NULL DEFAULT 0, + UNIQUE (topic, node) +); + +-- The messages, in ONE b-tree ordered by (stream, message id): key packs +-- both. A stream's messages sit together, a range of them is a range of +-- keys; no other index to write at every push. stream_id, message_id and +-- is_json are computed when read, never stored. pushed_at: ms since +-- 1970-01-01 UTC, stamped by the server it was pushed to, kept by +-- replication. +CREATE TABLE data ( + key INTEGER PRIMARY KEY, + pushed_at INTEGER NOT NULL, + message_data TEXT NOT NULL, + stream_id INTEGER GENERATED ALWAYS AS (key >> 43) VIRTUAL, + message_id INTEGER GENERATED ALWAYS AS (key & 8796093022207) VIRTUAL, + is_json INTEGER GENERATED ALWAYS AS (json_valid(message_data)) VIRTUAL, + CHECK (key & 8796093022207 >= 1) +); + +-- A message's attachment (one at most), or one being pushed (no message +-- yet). The states (storage.md, "Attachments"): +-- uploading pushed, its parts coming; message_key is NULL until all +-- came and the message is stored with it, in one +-- transaction. Cut short: deleted, and at every start. +-- replicating its message came from a peer, its parts come after +-- (asked from part received / 1 MiB on). +-- ready all here, its SHA-256 checked. +-- too_big bigger than max_attachment_size: its message is kept, +-- its parts never asked for. +-- deleting its message was deleted: its parts go in the background, +-- then the row. +CREATE TABLE attachments ( + attachment_id INTEGER PRIMARY KEY, + message_key INTEGER, -- data.key of its message, NULL while uploading + size INTEGER NOT NULL CHECK (size BETWEEN 1 AND 1099511627776), + sha256 BLOB NOT NULL CHECK (length(sha256) = 32), + received INTEGER NOT NULL DEFAULT 0 CHECK (received BETWEEN 0 AND size), + state TEXT NOT NULL + CHECK (state IN ('uploading', 'replicating', 'ready', 'too_big', 'deleting')), + CHECK ((message_key IS NULL) = (state = 'uploading')) +); +-- A message's attachment, by its message. +CREATE UNIQUE INDEX attachments_message ON attachments (message_key) + WHERE message_key IS NOT NULL; +-- What's left to do: uploads to clean up, parts to ask for, parts to delete. +CREATE INDEX attachments_state ON attachments (state) WHERE state <> 'ready'; + +-- Its parts, 1 MiB each (ATTACHMENT_PART_SIZE), the last one what's left, +-- in ONE b-tree: key packs the attachment and the part (2^20 parts of +-- 1 MiB is exactly the 1 TiB limit). An attachment's parts are a range of +-- keys, in order. +CREATE TABLE attachment_parts ( + key INTEGER PRIMARY KEY, + part_data BLOB NOT NULL +); + +-- A stored message moves its stream's last_id (pushes and replication +-- alike). +CREATE TRIGGER trg_data_last_id AFTER INSERT ON data BEGIN + UPDATE streams SET last_id = max(last_id, NEW.key & 8796093022207) + WHERE stream_id = NEW.key >> 43; +END; + +-- A deleted message's attachment goes too, in the background. +CREATE TRIGGER trg_data_attachment AFTER DELETE ON data BEGIN + UPDATE attachments SET state = 'deleting' WHERE message_key = OLD.key; +END; + +-- What queries read (Query, read-only): the messages by name, no keys. +-- Joined by key range: a topic's or a node's messages are ranges of the +-- table, read in order (storage.md, "The query surface"). +-- SELECT * FROM messages WHERE topic = 'logs' AND node = 'kitchen' +CREATE VIEW messages AS +SELECT s.topic, + s.node, + d.message_id, + d.message_data, + d.is_json, + d.pushed_at, + strftime('%Y-%m-%dT%H:%M:%fZ', d.pushed_at / 1000.0, 'unixepoch') AS pushed_utc, + a.size AS attachment_size, + a.state AS attachment_state +FROM streams s +JOIN data d ON d.key BETWEEN (s.stream_id << 43) AND (s.stream_id << 43) + 8796093022207 +LEFT JOIN attachments a ON a.message_key = d.key; + +-- What to browse with a database tool (v8's): set topic, and node or NULL +-- for all, in its one row, open browse_messages. Never written by the +-- server. +CREATE TABLE browse ( + id INTEGER PRIMARY KEY CHECK (id = 1), + topic TEXT COLLATE NOCASE, + node TEXT COLLATE NOCASE +); + +CREATE VIEW browse_messages AS +SELECT m.node, m.message_id, m.pushed_utc, m.message_data, m.is_json, + m.attachment_size, m.topic +FROM browse b +JOIN messages m ON m.topic = b.topic +WHERE b.id = 1 AND (b.node IS NULL OR m.node = b.node) +ORDER BY m.pushed_at DESC, m.node, m.message_id DESC; diff --git a/crates/bakashrot-storage/tests/storage.rs b/crates/bakashrot-storage/tests/storage.rs new file mode 100644 index 0000000..6c0f94a --- /dev/null +++ b/crates/bakashrot-storage/tests/storage.rs @@ -0,0 +1,920 @@ +//! The storage, end to end on database files: every request's SQL, the +//! limits, refused databases, and readers and writers at once. + +use bakashrot_config::Synchronous; +use bakashrot_proto::limits::{ATTACHMENT_PART_SIZE, MAX_MESSAGE_ID}; +use bakashrot_proto::packets::{Attachment as Sent, ReplicatedMessage}; +use bakashrot_storage::{AttachmentState, Database, Error, MAX_QUERY_ROWS, MAX_STREAMS}; +use std::path::PathBuf; +use std::sync::atomic::{AtomicUsize, Ordering}; + +const PART: usize = ATTACHMENT_PART_SIZE as usize; + +/// A fresh database file of its own (in target/, not the temp folder). +fn path(name: &str) -> PathBuf { + static COUNT: AtomicUsize = AtomicUsize::new(0); + let folder = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(format!( + "storage-{}-{}-{name}", + std::process::id(), + COUNT.fetch_add(1, Ordering::Relaxed) + )); + let _ = std::fs::remove_dir_all(&folder); + std::fs::create_dir_all(&folder).unwrap(); + folder.join("bakashrot.sqlite") +} + +fn open(name: &str) -> (Database, PathBuf) { + let path = path(name); + (Database::open(&path, Synchronous::Normal).unwrap(), path) +} + +fn ids(messages: &bakashrot_proto::packets::Messages) -> Vec { + messages.messages.iter().map(|m| m.id).collect() +} + +fn replicated(id: u64, pushed_at: u64, attachment: Option<(u64, [u8; 32])>) -> ReplicatedMessage { + ReplicatedMessage { + id, + pushed_at, + data: format!("r{id}"), + attachment: attachment.map(|(size, sha256)| Sent { size, sha256 }), + } +} + +#[test] +fn opening() { + let (database, path) = open("opening"); + let raw = rusqlite::Connection::open(&path).unwrap(); + let meta = |name: &str| -> String { + raw.query_row( + "SELECT CAST(value AS TEXT) FROM metadata WHERE name = ?1", + [name], + |r| r.get(0), + ) + .unwrap() + }; + assert_eq!(meta("schema_version"), "9"); + assert!(meta("created_by").starts_with("bakashrot-storage ")); + assert!(meta("created_at").parse::().unwrap() > 1_700_000_000_000); + let mode: String = raw + .query_row("PRAGMA journal_mode", [], |r| r.get(0)) + .unwrap(); + assert_eq!(mode, "wal"); + drop(database); + // Opened again as it is. + Database::open(&path, Synchronous::Full).unwrap(); + + // An empty file is made a database. + let empty = self::path("empty"); + std::fs::write(&empty, b"").unwrap(); + Database::open(&empty, Synchronous::Full).unwrap(); +} + +#[test] +fn refused_databases() { + let refused = |setup: &str, expected: &str| { + let path = path("refused"); + rusqlite::Connection::open(&path) + .unwrap() + .execute_batch(setup) + .unwrap(); + match Database::open(&path, Synchronous::Full) { + Err(Error::Unusable(why)) => assert!(why.contains(expected), "{why}"), + other => panic!("{setup}: {other:?}"), + } + }; + refused("CREATE TABLE other (x);", "not a BakaShrot database"); + refused( + "CREATE TABLE data (x); CREATE TABLE node_heads (y);", + "made by the old server (schema v8)", + ); + refused( + "PRAGMA application_id = 1112754260; CREATE TABLE x (y);", + "without its schema version", + ); + + // A newer version's. + let (database, path) = open("newer"); + drop(database); + rusqlite::Connection::open(&path) + .unwrap() + .execute( + "UPDATE metadata SET value = 10 WHERE name = 'schema_version'", + [], + ) + .unwrap(); + match Database::open(&path, Synchronous::Full) { + Err(Error::Unusable(why)) => assert!(why.contains("schema v10, made by a newer"), "{why}"), + other => panic!("{other:?}"), + } +} + +#[test] +fn pushing_and_reading() { + let (database, _) = open("push"); + let mut writer = database.writer().unwrap(); + let reader = database.reader().unwrap(); + + // A group commit: ids per topic and node, names without case. + let ids_pushed = writer + .batch(|batch| { + Ok(vec![ + batch.push("logs", "kitchen", 1000, "{\"t\":1}")?, + batch.push("logs", "kitchen", 1001, "not json")?, + batch.push("LOGS", "Kitchen", 1002, "{}")?, + batch.push("logs", "garage", 1003, "{}")?, + batch.push("sensors", "kitchen", 1004, "{}")?, + ]) + }) + .unwrap(); + assert_eq!(ids_pushed, [1, 2, 3, 1, 1]); + + let all = reader.messages("logs", "kitchen", Some(0), 100).unwrap(); + assert_eq!(ids(&all), [1, 2, 3]); + assert!(!all.more); + assert_eq!(all.messages[1].data, "not json"); + assert_eq!(all.messages[0].pushed_at, 1000); + assert!(all.messages[0].attachment.is_none()); + + // after, limit, more; the latest ones, in order. + let some = reader.messages("logs", "kitchen", Some(1), 1).unwrap(); + assert_eq!((ids(&some), some.more), (vec![2], true)); + let latest = reader.messages("Logs", "KITCHEN", None, 2).unwrap(); + assert_eq!((ids(&latest), latest.more), (vec![2, 3], false)); + assert!( + reader + .messages("logs", "kitchen", Some(3), 10) + .unwrap() + .messages + .is_empty() + ); + // A node without any message, in any topic: unknown. + assert!(matches!( + reader.messages("logs", "nobody", None, 10), + Err(Error::UnknownName(_)) + )); + assert!( + reader + .messages("logs", "kitchen", Some(MAX_MESSAGE_ID), 10) + .unwrap() + .messages + .is_empty() + ); + + // Names, heads. + assert_eq!(reader.topics().unwrap(), ["logs", "sensors"]); + assert_eq!(reader.nodes().unwrap(), ["garage", "kitchen"]); + let heads: Vec<_> = reader + .heads() + .unwrap() + .into_iter() + .map(|h| (h.topic, h.node, h.last_id)) + .collect(); + assert_eq!( + heads, + [ + ("logs".into(), "garage".into(), 1), + ("logs".into(), "kitchen".into(), 3), + ("sensors".into(), "kitchen".into(), 1) + ] + ); + assert_eq!(reader.last_id("logs", "kitchen").unwrap(), 3); + assert_eq!(reader.last_id("nope", "kitchen").unwrap(), 0); +} + +#[test] +fn answers_stop_at_about_a_megabyte() { + let (database, _) = open("bytes"); + let mut writer = database.writer().unwrap(); + let big = "x".repeat(400 * 1024); + writer + .batch(|batch| { + for _ in 0..5 { + batch.push("logs", "kitchen", 1, &big)?; + } + batch.push("logs", "kitchen", 1, &"y".repeat(3 * 1024 * 1024))?; + Ok(()) + }) + .unwrap(); + let reader = database.reader().unwrap(); + let first = reader.messages("logs", "kitchen", Some(0), 100).unwrap(); + assert_eq!((ids(&first), first.more), (vec![1, 2], true)); + let next = reader.messages("logs", "kitchen", Some(4), 100).unwrap(); + assert_eq!((ids(&next), next.more), (vec![5], true)); + // A bigger message goes alone. + let alone = reader.messages("logs", "kitchen", Some(5), 100).unwrap(); + assert_eq!((ids(&alone), alone.more), (vec![6], false)); +} + +#[test] +fn uploads() { + let (database, path) = open("uploads"); + let mut writer = database.writer().unwrap(); + let size = (2 * PART + 10) as u64; + let sha = [7; 32]; + let upload = writer.batch(|b| b.start_upload(size, &sha)).unwrap(); + + let part = |n: usize| vec![n as u8; if n == 2 { 10 } else { PART }]; + // Only in order, each its size. + assert!(matches!( + writer.batch(|b| b.write_part(upload, 1, &part(1))), + Err(Error::Invalid(_)) + )); + assert!(matches!( + writer.batch(|b| b.write_part(upload, 0, &[0; 10])), + Err(Error::Invalid(_)) + )); + assert!(!writer.batch(|b| b.write_part(upload, 0, &part(0))).unwrap()); + assert!(!writer.batch(|b| b.write_part(upload, 1, &part(1))).unwrap()); + // Not complete: no push with it, and the batch goes on after. + let pushed = writer + .batch(|b| { + assert!(matches!( + b.push_with_attachment(upload, "logs", "kitchen", 1, "{}"), + Err(Error::Invalid(_)) + )); + b.push("logs", "kitchen", 1, "without") + }) + .unwrap(); + assert_eq!(pushed, 1); + assert!(writer.batch(|b| b.write_part(upload, 2, &part(2))).unwrap()); + assert!(matches!( + writer.batch(|b| b.write_part(upload, 3, &[1])), + Err(Error::Invalid(_)) + )); + let id = writer + .batch(|b| b.push_with_attachment(upload, "logs", "kitchen", 2, "with")) + .unwrap(); + assert_eq!(id, 2); + + let reader = database.reader().unwrap(); + let message = &reader + .messages("logs", "kitchen", Some(1), 1) + .unwrap() + .messages[0]; + let stored = message.attachment.as_ref().unwrap(); + assert_eq!((stored.size, stored.ready), (size, true)); + let attachment = reader.attachment("logs", "kitchen", 2).unwrap().unwrap(); + assert_eq!( + (attachment.state, attachment.sha256, attachment.received), + (AttachmentState::Ready, sha, size) + ); + assert_eq!(reader.read_part(attachment.id, 1).unwrap(), part(1)); + assert_eq!(reader.read_part(attachment.id, 2).unwrap(), part(2)); + assert!(matches!( + reader.read_part(attachment.id, 3), + Err(Error::NotFound(_)) + )); + assert!(reader.attachment("logs", "kitchen", 1).unwrap().is_none()); + + // Cancelled, or left over at a restart: gone with their parts. + let cancelled = writer.batch(|b| b.start_upload(5, &sha)).unwrap(); + writer + .batch(|b| b.write_part(cancelled, 0, &[1; 5])) + .unwrap(); + writer.batch(|b| b.cancel_upload(cancelled)).unwrap(); + assert!(matches!( + writer.batch(|b| b.cancel_upload(cancelled)), + Err(Error::NotFound(_)) + )); + let left = writer.batch(|b| b.start_upload(5, &sha)).unwrap(); + writer.batch(|b| b.write_part(left, 0, &[1; 5])).unwrap(); + drop((writer, reader, database)); + Database::open(&path, Synchronous::Normal).unwrap(); + let raw = rusqlite::Connection::open(&path).unwrap(); + let count = |sql: &str| raw.query_row(sql, [], |r| r.get::<_, i64>(0)).unwrap(); + assert_eq!(count("SELECT count(*) FROM attachments"), 1); + assert_eq!(count("SELECT count(*) FROM attachment_parts"), 3); + + // Sizes. + let database = Database::open(&path, Synchronous::Normal).unwrap(); + let mut writer = database.writer().unwrap(); + assert!(matches!( + writer.batch(|b| b.start_upload(0, &sha)), + Err(Error::TooBig(_)) + )); + assert!(matches!( + writer.batch(|b| b.start_upload((1 << 40) + 1, &sha)), + Err(Error::TooBig(_)) + )); +} + +#[test] +fn replication() { + let (database, _) = open("replication"); + let mut writer = database.writer().unwrap(); + let reader = database.reader().unwrap(); + let sha = [3; 32]; + let last = writer + .batch(|b| { + b.replicate( + "logs", + "kitchen", + &[ + replicated(5, 100, None), + replicated(9, 200, Some((PART as u64 + 1, sha))), + replicated(12, 300, Some((50, sha))), + ], + 1000, + 0, + ) + }) + .unwrap(); + assert_eq!(last, 12); + // Ones already here are kept as they are; the head never goes back. + let again = writer + .batch(|b| { + b.replicate( + "logs", + "kitchen", + &[ReplicatedMessage { + data: "other".into(), + ..replicated(5, 1, None) + }], + 1000, + 0, + ) + }) + .unwrap(); + assert_eq!(again, 12); + let stored = reader.messages("logs", "kitchen", Some(0), 10).unwrap(); + assert_eq!(ids(&stored), [5, 9, 12]); + assert_eq!(stored.messages[0].data, "r5"); + // A push goes on after the replicated ids. + assert_eq!( + writer + .batch(|b| b.push("logs", "kitchen", 400, "{}")) + .unwrap(), + 13 + ); + + // Attachments: too big here, or to ask for. + let big = reader.attachment("logs", "kitchen", 9).unwrap().unwrap(); + assert_eq!(big.state, AttachmentState::TooBig); + assert!(!stored.messages[1].attachment.as_ref().unwrap().ready); + let missing = reader.missing_attachments(256).unwrap(); + assert_eq!(missing.len(), 1); + assert_eq!((missing[0].message_id, missing[0].next_part), (12, 0)); + + // Its parts; a mismatch starts it over; a match makes it ready. + let small = reader.attachment("logs", "kitchen", 12).unwrap().unwrap(); + assert!( + writer + .batch(|b| b.write_part(small.id, 0, &[1; 50])) + .unwrap() + ); + writer + .batch(|b| b.finish_replicated(small.id, false)) + .unwrap(); + assert_eq!( + reader + .attachment("logs", "kitchen", 12) + .unwrap() + .unwrap() + .received, + 0 + ); + assert_eq!(reader.missing_attachments(256).unwrap()[0].next_part, 0); + assert!( + writer + .batch(|b| b.write_part(small.id, 0, &[2; 50])) + .unwrap() + ); + writer + .batch(|b| b.finish_replicated(small.id, true)) + .unwrap(); + assert_eq!( + reader + .attachment("logs", "kitchen", 12) + .unwrap() + .unwrap() + .state, + AttachmentState::Ready + ); + assert!(reader.missing_attachments(256).unwrap().is_empty()); + assert!(matches!( + writer.batch(|b| b.finish_replicated(small.id, true)), + Err(Error::Invalid(_)) + )); + assert!(matches!( + writer.batch(|b| b.write_part(big.id, 0, &[0; PART])), + Err(Error::Invalid(_)) + )); + + // A resumed one: next_part follows what came. + writer + .batch(|b| { + b.replicate( + "logs", + "garage", + &[replicated(1, 1, Some((2 * PART as u64, sha)))], + u64::MAX, + 0, + ) + }) + .unwrap(); + let resumed = reader.attachment("logs", "garage", 1).unwrap().unwrap(); + writer + .batch(|b| b.write_part(resumed.id, 0, &[0; PART])) + .unwrap(); + let missing = reader.missing_attachments(256).unwrap(); + assert_eq!( + (missing[0].node.as_str(), missing[0].next_part), + ("garage", 1) + ); + + // What's sent on: after an id, with its attachments' SHA-256s. + let sent = reader.to_replicate("logs", "kitchen", 5, 10).unwrap(); + let sent_ids: Vec = sent.iter().map(|m| m.id).collect(); + assert_eq!(sent_ids, [9, 12, 13]); + assert_eq!( + sent[0].attachment, + Some(Sent { + size: PART as u64 + 1, + sha256: sha + }) + ); + assert_eq!(sent[2].attachment, None); + assert_eq!( + reader.to_replicate("logs", "kitchen", 9, 1).unwrap()[0].id, + 12 + ); + assert!( + reader + .to_replicate("logs", "kitchen", 13, 10) + .unwrap() + .is_empty() + ); + assert!( + reader + .to_replicate("logs", "nobody", 0, 10) + .unwrap() + .is_empty() + ); + + // A damaged ready copy: its parts go, asked for again. + writer.batch(|b| b.damaged(small.id)).unwrap(); + let again = reader.attachment("logs", "kitchen", 12).unwrap().unwrap(); + assert_eq!( + (again.state, again.received), + (AttachmentState::Replicating, 0) + ); + assert!(reader.read_part(small.id, 0).is_err()); + assert!(matches!( + writer.batch(|b| b.damaged(small.id)), + Err(Error::Invalid(_)) + )); + + // Past their age here: not stored, but counted. + let last = writer + .batch(|b| { + b.replicate( + "logs", + "attic", + &[ + replicated(1, 100, Some((50, sha))), + replicated(2, 200, None), + replicated(3, 300, None), + ], + 1000, + 201, + ) + }) + .unwrap(); + assert_eq!(last, 3); + assert_eq!( + ids(&reader.messages("logs", "attic", Some(0), 10).unwrap()), + [3] + ); + assert_eq!(reader.last_id("logs", "attic").unwrap(), 3); + let skipped = writer + .batch(|b| b.replicate("logs", "cellar", &[replicated(7, 100, None)], 1000, 201)) + .unwrap(); + assert_eq!((skipped, reader.last_id("logs", "cellar").unwrap()), (7, 7)); + + // Ids out of range. + assert!(matches!( + writer.batch(|b| b.replicate("logs", "kitchen", &[replicated(0, 1, None)], 0, 0)), + Err(Error::Invalid(_)) + )); +} + +#[test] +fn retention() { + let (database, _) = open("retention"); + let mut writer = database.writer().unwrap(); + let reader = database.reader().unwrap(); + writer + .batch(|b| { + for at in 1..=10 { + b.push("logs", "kitchen", at * 100, "{}")?; + b.push("logs", "garage", at * 100 + 50, "{}")?; + b.push("sensors", "kitchen", at * 100, "{}")?; + } + Ok(()) + }) + .unwrap(); + // An attachment on an old message. + let upload = writer + .batch(|b| b.start_upload(3 * PART as u64, &[1; 32])) + .unwrap(); + for part in 0..3 { + writer + .batch(|b| b.write_part(upload, part, &[0; PART])) + .unwrap(); + } + writer + .batch(|b| b.push_with_attachment(upload, "logs", "kitchen", 120, "{}")) + .unwrap(); + + // Before 500: kitchen 1-4 and 11 (pushed at 120, after 4: in id order, it + // waits for 5-10), garage 1-4. A limit, then the rest. + assert_eq!( + writer.batch(|b| b.delete_before("logs", 500, 5)).unwrap(), + 5 + ); + assert_eq!( + writer.batch(|b| b.delete_before("logs", 500, 100)).unwrap(), + 3 + ); + assert_eq!( + writer.batch(|b| b.delete_before("logs", 500, 100)).unwrap(), + 0 + ); + assert_eq!( + ids(&reader.messages("logs", "kitchen", Some(0), 100).unwrap()), + [5, 6, 7, 8, 9, 10, 11] + ); + assert_eq!( + ids(&reader.messages("logs", "garage", Some(0), 100).unwrap()).len(), + 6 + ); + assert_eq!( + ids(&reader.messages("sensors", "kitchen", Some(0), 100).unwrap()).len(), + 10 + ); + + // Everything: the heads stay, ids go on. + assert_eq!( + writer + .batch(|b| b.delete_before("logs", u64::MAX, 1000)) + .unwrap(), + 13 + ); + assert_eq!(reader.last_id("logs", "kitchen").unwrap(), 11); + assert_eq!( + writer + .batch(|b| b.push("logs", "kitchen", 2000, "{}")) + .unwrap(), + 12 + ); + + // The attachment's parts go in batches, then its row. + assert_eq!(reader.attachment("logs", "kitchen", 11).unwrap(), None); + assert_eq!(writer.batch(|b| b.purge_attachments(2)).unwrap(), 2); + assert_eq!(writer.batch(|b| b.purge_attachments(2)).unwrap(), 1); + assert_eq!(writer.batch(|b| b.purge_attachments(2)).unwrap(), 0); + assert!(matches!( + reader.read_part(upload, 2), + Err(Error::NotFound(_)) + )); +} + +#[test] +fn vacuum() { + let (database, path) = open("vacuum"); + let mut writer = database.writer().unwrap(); + let big = "x".repeat(10_000); + writer + .batch(|b| { + for _ in 0..1000 { + b.push("logs", "kitchen", 1, &big)?; + } + Ok(()) + }) + .unwrap(); + writer.vacuum().unwrap(); + let full = std::fs::metadata(&path).unwrap().len(); + writer + .batch(|b| b.delete_before("logs", u64::MAX, 10_000)) + .unwrap(); + writer.vacuum().unwrap(); + let emptied = std::fs::metadata(&path).unwrap().len(); + assert!(emptied * 10 < full, "{full} -> {emptied}"); + // Still the same database: ids go on. + assert_eq!( + writer + .batch(|b| b.push("logs", "kitchen", 2, "{}")) + .unwrap(), + 1001 + ); +} + +#[test] +fn limits() { + let (database, path) = open("limits"); + let mut writer = database.writer().unwrap(); + writer + .batch(|b| b.push("logs", "kitchen", 1, "{}")) + .unwrap(); + let raw = rusqlite::Connection::open(&path).unwrap(); + // A topic and node with no id left. + raw.execute("UPDATE streams SET last_id = ?1", [MAX_MESSAGE_ID as i64]) + .unwrap(); + assert!(matches!( + writer.batch(|b| b.push("logs", "kitchen", 1, "{}")), + Err(Error::TooBig(_)) + )); + // No stream left. + raw.execute( + "INSERT INTO streams (stream_id, topic, node) VALUES (?1, 'x', 'y')", + [MAX_STREAMS], + ) + .unwrap(); + assert!(matches!( + writer.batch(|b| b.push("new", "kitchen", 1, "{}")), + Err(Error::TooBig(_)) + )); + // The highest key there is. + raw.execute( + "UPDATE streams SET last_id = ?1 - 1 WHERE topic = 'x'", + [MAX_MESSAGE_ID as i64], + ) + .unwrap(); + assert_eq!( + writer.batch(|b| b.push("x", "y", 1, "last")).unwrap(), + MAX_MESSAGE_ID + ); + let reader = database.reader().unwrap(); + let last = reader.messages("x", "y", None, 1).unwrap(); + assert_eq!( + (last.messages[0].id, last.messages[0].data.as_str()), + (MAX_MESSAGE_ID, "last") + ); +} + +#[test] +fn queries() { + let (database, _) = open("queries"); + let mut writer = database.writer().unwrap(); + writer + .batch(|b| { + b.push("logs", "kitchen", 1_700_000_000_000, "{\"t\": 21.5}")?; + b.push("logs", "kitchen", 1_700_000_000_001, "not json")?; + b.push("logs", "garage", 1_700_000_000_002, "{\"t\": 3}") + }) + .unwrap(); + let runner = database.query_runner().unwrap(); + let json = |sql: &str| -> serde_json::Value { + serde_json::from_str(&runner.run(sql).unwrap()).unwrap() + }; + + let result = json( + "SELECT topic, node, message_id, is_json, pushed_utc, message_data ->> '$.t' AS t, \ + attachment_size FROM messages WHERE topic = 'logs' AND node = 'kitchen' AND is_json = 1", + ); + assert_eq!( + result, + serde_json::json!({ + "columns": ["topic", "node", "message_id", "is_json", "pushed_utc", "t", "attachment_size"], + "rows": [["logs", "kitchen", "1", "1", "2023-11-14T22:13:20.000Z", "21.5", null]] + }) + ); + assert_eq!( + json("SELECT x'00ff', 1.0, NULL")["rows"], + serde_json::json!([["00ff", "1.0", null]]) + ); + assert_eq!( + json("SELECT count(*) FROM messages")["rows"], + serde_json::json!([["3"]]) + ); + + // Refused: writes, whatever their form, more than one statement, no rows to give. + for sql in [ + "DELETE FROM data", + "WITH x AS (SELECT 1) DELETE FROM data", + "INSERT INTO browse VALUES (1, 'logs', NULL)", + "PRAGMA query_only = 0", + "SELECT 1; DELETE FROM data", + "CREATE TABLE t (x)", + "ATTACH 'other.sqlite' AS other", + "SELEKT 1", + ] { + assert!(matches!(runner.run(sql), Err(Error::Query(_))), "{sql}"); + } + // A failing row fails it all, with SQLite's message. + match runner.run("SELECT message_data ->> '$.t' FROM messages") { + Err(Error::Query(why)) => assert!(why.contains("malformed JSON"), "{why}"), + other => panic!("{other:?}"), + } + // Too big. + let rows = format!( + "WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i <= {MAX_QUERY_ROWS}) SELECT i FROM n" + ); + assert!(matches!(runner.run(&rows), Err(Error::TooBig(_)))); + assert!(matches!( + runner.run("WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 20) SELECT zeroblob(1000000) FROM n"), + Err(Error::TooBig(_)) + )); + // Still nothing written. + assert_eq!( + json("SELECT count(*) FROM data")["rows"], + serde_json::json!([["3"]]) + ); +} + +#[test] +fn the_view_reads_by_key_range() { + let (database, path) = open("plans"); + drop(database); + let raw = rusqlite::Connection::open(&path).unwrap(); + for sql in [ + "SELECT * FROM messages WHERE topic = 'logs' AND node = 'kitchen'", + "SELECT * FROM messages WHERE topic = 'logs' AND pushed_at > 5", + "SELECT * FROM messages WHERE topic = 'logs' AND node = 'kitchen' ORDER BY message_id DESC LIMIT 5", + ] { + let plan: Vec = raw + .prepare(&format!("EXPLAIN QUERY PLAN {sql}")) + .unwrap() + .query_map([], |r| r.get(3)) + .unwrap() + .collect::>() + .unwrap(); + let plan = plan.join(" | "); + assert!( + plan.contains("INTEGER PRIMARY KEY (rowid>? AND rowid = (0..3) + .map(|_| { + let database = database.clone(); + let stop = stop.clone(); + std::thread::spawn(move || { + let reader = database.reader().unwrap(); + let mut seen = 0; + let mut reads = 0; + while !stop.load(Ordering::Relaxed) { + let latest = match reader.messages("logs", "kitchen", None, 10) { + // Not pushed to yet. + Err(Error::UnknownName(_)) => continue, + latest => latest.unwrap(), + }; + let ids = ids(&latest); + assert!(ids.windows(2).all(|w| w[1] == w[0] + 1), "{ids:?}"); + let last = ids.last().copied().unwrap_or(0); + assert!(last >= seen, "went back: {last} < {seen}"); + seen = last; + reads += 1; + } + reads + }) + }) + .collect(); + // Two writers at once: the second waits for the first's transactions. + let writers: Vec<_> = ["kitchen", "garage"] + .into_iter() + .map(|node| { + let database = database.clone(); + std::thread::spawn(move || { + let mut writer = database.writer().unwrap(); + for batch in 0..100 { + writer + .batch(|b| { + for i in 0..20 { + b.push("logs", node, batch * 20 + i, "{}")?; + } + Ok(()) + }) + .unwrap(); + } + }) + }) + .collect(); + for writer in writers { + writer.join().unwrap(); + } + stop.store(true, Ordering::Relaxed); + for reader in readers { + assert!(reader.join().unwrap() > 0); + } + let reader = database.reader().unwrap(); + assert_eq!(reader.last_id("logs", "kitchen").unwrap(), 2000); + assert_eq!(reader.last_id("logs", "garage").unwrap(), 2000); +} + +/// The same workload as the old storage's benchmark +/// (`OldSource\Build\Bench\StorageBenchOld.exe`), to compare them: pushes +/// over 100 topics x 5 nodes (an LCG picks them), 100 per batch, 200-byte +/// JSON; 2000 latest-message reads, 500 reads of 1000 messages after the +/// middle id, the file's size, retention of 10% of one topic. Not run by +/// default: `PUSHES=1000000 SYNC=normal cargo test --release -p +/// bakashrot-storage -- --ignored --nocapture`. +#[test] +#[ignore] +fn compare_with_old() { + use std::time::Instant; + let count: u64 = std::env::var("PUSHES").map_or(1_000_000, |n| n.parse().unwrap()); + let sync = std::env::var("SYNC").unwrap_or_else(|_| "normal".into()); + let synchronous = if sync == "full" { + Synchronous::Full + } else { + Synchronous::Normal + }; + let path = path("compare"); + let database = Database::open(&path, synchronous).unwrap(); + let mut writer = database.writer().unwrap(); + + let prefix = r#"{"kind":"temp","value":21.37,"ts":1700000000,"pad":""#; + let json = format!("{prefix}{}\"}}", "x".repeat(200 - prefix.len() - 2)); + assert_eq!(json.len(), 200); + let topics: Vec = (0..100).map(|t| format!("topic{t}")).collect(); + let nodes: Vec = (0..5).map(|n| format!("node{n}")).collect(); + + // Checkpoints every second on their own connection, as the server's + // (and the old server's) thread does. + let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let checkpoints = { + let checkpointer = database.checkpointer().unwrap(); + let stop = stop.clone(); + std::thread::spawn(move || { + while !stop.load(Ordering::Relaxed) { + std::thread::sleep(std::time::Duration::from_secs(1)); + checkpointer.checkpoint().unwrap(); + } + }) + }; + + let mut state: u64 = 1; + let start = Instant::now(); + for batch in 0..count / 100 { + writer + .batch(|b| { + for i in 0..100 { + state = state + .wrapping_mul(6_364_136_223_846_793_005) + .wrapping_add(1_442_695_040_888_963_407); + let x = (state >> 33) & 0x7FFF_FFFF; + let at = 1_700_000_000_000 + (batch * 100 + i) * 10; + b.push( + &topics[(x % 100) as usize], + &nodes[(x / 100 % 5) as usize], + at, + &json, + )?; + } + Ok(()) + }) + .unwrap(); + } + let pushing = start.elapsed().as_secs_f64(); + stop.store(true, Ordering::Relaxed); + checkpoints.join().unwrap(); + + let reader = database.reader().unwrap(); + let pick = |i: usize| (&topics[i * 37 % 100], &nodes[i * 3 % 5]); + let middle: Vec = (0..500) + .map(|i| reader.last_id(pick(i).0, pick(i).1).unwrap() / 2) + .collect(); + let start = Instant::now(); + for i in 0..2000 { + reader.messages(pick(i).0, pick(i).1, None, 1).unwrap(); + } + let latest = start.elapsed().as_secs_f64() * 1000.0 / 2000.0; + let start = Instant::now(); + let mut read = 0; + for (i, after) in middle.iter().enumerate() { + read += reader + .messages(pick(i).0, pick(i).1, Some(*after), 1000) + .unwrap() + .messages + .len(); + } + let after = start.elapsed().as_secs_f64() * 1000.0 / 500.0; + + rusqlite::Connection::open(&path) + .unwrap() + .query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(())) + .unwrap(); + let size = std::fs::metadata(&path).unwrap().len(); + + let start = Instant::now(); + let cutoff = 1_700_000_000_000 + count / 10 * 10; + let deleted = writer + .batch(|b| b.delete_before("topic0", cutoff, 100_000_000)) + .unwrap(); + let retention = start.elapsed().as_secs_f64() * 1000.0; + + println!( + "new {sync}: {count} pushes in {pushing:.1} s = {:.0}/s | file {:.0} MB | latest {latest:.3} ms | 1000 after {after:.3} ms ({read} read) | retention {deleted} in {retention:.0} ms", + count as f64 / pushing, + size as f64 / 1e6 + ); +} diff --git a/crates/bakashrot-tools/Cargo.toml b/crates/bakashrot-tools/Cargo.toml new file mode 100644 index 0000000..c74036f --- /dev/null +++ b/crates/bakashrot-tools/Cargo.toml @@ -0,0 +1,34 @@ +[package] +name = "bakashrot-tools" +description = "BakaShrot's command-line tools: bakashrot pushes and reads messages, bakashrot-cert issues certificates and revokes them." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +authors.workspace = true +repository.workspace = true +publish.workspace = true + +# No API to document, and its name is the DLL's library's (cargo doc would +# collide). +[[bin]] +name = "bakashrot" +doc = false + +[dependencies] +bakashrot-client = { path = "../bakashrot-client" } +bakashrot-pki = { path = "../bakashrot-pki" } +bakashrot-proto = { path = "../bakashrot-proto" } +clap = { version = "4", features = ["derive"] } +serde = { version = "1.0.229", features = ["derive"] } +serde_json = "1.0.154" +time = "0.3.55" +toml = { version = "1.2.1", default-features = false, features = ["std", "parse", "serde"] } + +[dev-dependencies] +bakashrot-config = { path = "../bakashrot-config" } +bakashrot-server = { path = "../bakashrot-server" } +tokio = { version = "1.54.1", features = ["rt-multi-thread", "net"] } + +[lints] +workspace = true diff --git a/crates/bakashrot-tools/src/bin/bakashrot-cert.rs b/crates/bakashrot-tools/src/bin/bakashrot-cert.rs new file mode 100644 index 0000000..054169b --- /dev/null +++ b/crates/bakashrot-tools/src/bin/bakashrot-cert.rs @@ -0,0 +1,241 @@ +//! `bakashrot-cert`: makes a CA, issues certificates, revokes them, shows +//! them. Every file is PEM; keys are written once, never over an existing +//! file. See `docs/certificates.md`. + +use bakashrot_pki::{ + CA_DAYS, CERTIFICATE_DAYS, Ca, IDENTITY_OID_IS_PLACEHOLDER, Identity, Revocations, Usage, + summarize, +}; +use clap::{Parser, Subcommand}; +use std::fs; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::process::ExitCode; + +#[derive(Parser)] +#[command( + name = "bakashrot-cert", + version, + about = "Issues and revokes BakaShrot's certificates" +)] +struct Cli { + #[command(subcommand)] + command: Command, +} + +#[derive(Subcommand)] +enum Command { + /// Makes a new CA: ca.crt and ca.key in --out. Keep ca.key off the + /// servers: whoever has it can make any identity. + Ca { + /// The CA's name (its certificate's CN). + #[arg(long)] + name: String, + /// How long it's valid, in days. + #[arg(long, default_value_t = CA_DAYS)] + days: u32, + /// Where to write ca.crt and ca.key. + #[arg(long, default_value = ".")] + out: PathBuf, + }, + /// Issues a certificate for a node: NAME.crt and NAME.key in --out + /// (or --file's). + Issue { + /// The node's name. + #[arg(long)] + name: String, + /// A role, any number of times (the server's config says what each + /// may do). + #[arg(long = "role")] + roles: Vec, + /// A server's certificate (clients and peers connect to it), not a + /// client's. + #[arg(long)] + server: bool, + /// How long it's valid, in days. + #[arg(long, default_value_t = CERTIFICATE_DAYS)] + days: u32, + /// The folder of ca.crt and ca.key. + #[arg(long, default_value = ".")] + ca: PathBuf, + /// Where to write the certificate and its key. + #[arg(long, default_value = ".")] + out: PathBuf, + /// The files' name, without .crt and .key (the node's name by + /// default): another certificate for the same name, beside the + /// first one (two servers of the same name, a new one before the + /// old one is revoked). + #[arg(long)] + file: Option, + }, + /// Revokes certificates: (re)writes ca.crl in --ca, with every one + /// revoked before. Push it to the servers' folders. + Revoke { + /// The certificates to revoke. + #[arg(required = true)] + certificates: Vec, + /// The folder of ca.crt, ca.key and ca.crl. + #[arg(long, default_value = ".")] + ca: PathBuf, + /// When to expect the next CRL, in days. + #[arg(long, default_value_t = CERTIFICATE_DAYS)] + days: u32, + }, + /// Shows what a certificate says. + Show { + /// The certificate. + certificate: PathBuf, + }, +} + +fn main() -> ExitCode { + match run(Cli::parse().command) { + Ok(()) => ExitCode::SUCCESS, + Err(error) => { + eprintln!("bakashrot-cert: {error}"); + ExitCode::FAILURE + } + } +} + +/// Said whenever a certificate is made while the OID is the placeholder. +const PLACEHOLDER_WARNING: &str = "warning: the identity extension's OID is still a placeholder \ +(docs/oid.md): fine for tests, not for certificates in use"; + +fn run(command: Command) -> Result<(), String> { + if IDENTITY_OID_IS_PLACEHOLDER && matches!(command, Command::Ca { .. } | Command::Issue { .. }) + { + eprintln!("{PLACEHOLDER_WARNING}"); + } + match command { + Command::Ca { name, days, out } => { + let ca = Ca::create(&name, days).map_err(|e| e.to_string())?; + write_new(&out.join("ca.crt"), &ca.certificate, false)?; + write_new(&out.join("ca.key"), &ca.key, true)?; + } + Command::Issue { + name, + roles, + server, + days, + ca, + out, + file, + } => { + let roles: Vec<&str> = roles.iter().map(String::as_str).collect(); + let identity = Identity::new(&name, &roles).map_err(|e| e.to_string())?; + let usage = if server { Usage::Server } else { Usage::Client }; + let issued = load_ca(&ca)? + .issue(&identity, usage, days) + .map_err(|e| e.to_string())?; + let file = file.unwrap_or(name); + write_new(&out.join(format!("{file}.crt")), &issued.certificate, false)?; + write_new(&out.join(format!("{file}.key")), &issued.key, true)?; + } + Command::Revoke { + certificates, + ca: folder, + days, + } => revoke(&folder, &certificates, days)?, + Command::Show { certificate } => show(&certificate)?, + } + Ok(()) +} + +fn read(path: &Path) -> Result { + fs::read_to_string(path).map_err(|error| format!("{}: {error}", path.display())) +} + +fn load_ca(folder: &Path) -> Result { + Ca::load( + &read(&folder.join("ca.crt"))?, + &read(&folder.join("ca.key"))?, + ) + .map_err(|error| format!("the CA in {}: {error}", folder.display())) +} + +/// Writes a new file, never over an existing one; a key readable by its +/// owner only (on Unix). +fn write_new(path: &Path, text: &str, private: bool) -> Result<(), String> { + let mut options = fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + if private { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + #[cfg(not(unix))] + let _ = private; + let mut file = options + .open(path) + .map_err(|error| format!("{}: {error}", path.display()))?; + file.write_all(text.as_bytes()) + .map_err(|error| format!("{}: {error}", path.display()))?; + println!("Wrote {}", path.display()); + Ok(()) +} + +fn revoke(folder: &Path, certificates: &[PathBuf], days: u32) -> Result<(), String> { + let ca = load_ca(folder)?; + let ca_certificate = read(&folder.join("ca.crt"))?; + let crl_path = folder.join("ca.crl"); + + // Those revoked before stay revoked. + let mut serials: Vec> = if crl_path.exists() { + Revocations::load(&read(&crl_path)?, &ca_certificate) + .map_err(|error| format!("{}: {error}", crl_path.display()))? + .serials() + .map(<[u8]>::to_vec) + .collect() + } else { + Vec::new() + }; + for path in certificates { + let certificate = read(path)?; + if !ca + .issued(&certificate) + .map_err(|e| format!("{}: {e}", path.display()))? + { + return Err(format!("{}: not issued by this CA", path.display())); + } + let summary = summarize(&certificate).map_err(|e| format!("{}: {e}", path.display()))?; + if !serials.contains(&summary.serial) { + serials.push(summary.serial); + } + println!("Revoked {} ({})", path.display(), summary.subject); + } + + // Written aside then moved: a server reading it never sees half of it. + let crl = ca + .revocation_list(&serials, days) + .map_err(|e| e.to_string())?; + let temporary = folder.join("ca.crl.new"); + fs::write(&temporary, crl).map_err(|error| format!("{}: {error}", temporary.display()))?; + fs::rename(&temporary, &crl_path) + .map_err(|error| format!("{}: {error}", crl_path.display()))?; + println!("Wrote {} ({} revoked)", crl_path.display(), serials.len()); + Ok(()) +} + +fn show(path: &Path) -> Result<(), String> { + let summary = summarize(&read(path)?).map_err(|e| format!("{}: {e}", path.display()))?; + println!("{}", path.display()); + match &summary.identity { + Some(identity) => { + println!(" name: {}", identity.name); + println!(" roles: {}", identity.roles.join(", ")); + } + None => println!(" subject: {}", summary.subject), + } + let usage = match (summary.is_ca, summary.usage) { + (true, _) => "CA", + (false, Some(Usage::Server)) => "server", + (false, Some(Usage::Client)) => "client", + (false, None) => "other", + }; + println!(" usage: {usage}"); + println!(" issuer: {}", summary.issuer); + println!(" valid: {} to {}", summary.not_before, summary.not_after); + println!(" serial: {}", summary.serial_hex()); + Ok(()) +} diff --git a/crates/bakashrot-tools/src/bin/bakashrot.rs b/crates/bakashrot-tools/src/bin/bakashrot.rs new file mode 100644 index 0000000..5f533b8 --- /dev/null +++ b/crates/bakashrot-tools/src/bin/bakashrot.rs @@ -0,0 +1,388 @@ +//! `bakashrot`: pushes messages, reads them and their attachments, runs +//! queries and lists names from the command line, connecting with a +//! `client.toml`. The old `BakaShrot*` tools in one program; see +//! `docs/client.md`, "The tools". + +use bakashrot_client::{Client, Error, Settings}; +use bakashrot_proto::error::{code_name, is_refusal_code}; +use bakashrot_proto::limits::MAX_MESSAGES_PER_PACKET; +use bakashrot_proto::packets::{MessageEntry, NameKind}; +use clap::{Parser, Subcommand, ValueEnum}; +use serde::Deserialize; +use std::fs; +use std::io::{self, Read, Write}; +use std::path::{Path, PathBuf}; +use std::process::ExitCode; +use std::time::Duration; + +#[derive(Parser)] +#[command( + name = "bakashrot", + version, + about = "Pushes and reads BakaShrot's messages", + after_help = "Exits with 0 on success, 1 on a failure, 2 on bad arguments." +)] +struct Cli { + /// The client's settings: the server, the CA's certificate, this + /// client's certificate and key, the CRL. + #[arg(short, long, global = true, default_value = "client.toml")] + config: PathBuf, + #[command(subcommand)] + command: Command, +} + +#[derive(Subcommand)] +enum Command { + /// Pushes a message as this client's node, prints its id. + Push { + /// The topic to push to. + topic: String, + /// The message (JSON or any text), @FILE for a file's, - for the + /// standard input's (PowerShell before 7.3 drops the double quotes + /// inside arguments: use @FILE or - there). + message: String, + /// A file to attach (1 byte and up, as much as the server takes): + /// the message is stored once all of it came. + #[arg(short, long)] + attachment: Option, + }, + /// Prints a topic and node's latest message: its id, when it was pushed + /// (UTC), its attachment if it has one, then its data. + Latest { + /// The topic. + topic: String, + /// The node that pushed it. + node: String, + }, + /// Saves a message's attachment as FILE (replaced), checked with its + /// SHA-256, and prints its size. A failed one leaves no file. + Attachment { + /// The topic. + topic: String, + /// The node that pushed it. + node: String, + /// The message's id. + id: u64, + /// Where to save it. + file: PathBuf, + }, + /// Prints a topic and node's messages in order, a line each: its id, a + /// tab, its data as stored (a line break in it spans lines). + Messages { + /// The topic. + topic: String, + /// The node that pushed them. + node: String, + /// Starts after this message id: 0 from the first one, "latest" + /// after the latest one (only new ones, with --follow). + #[arg(long, default_value = "0", value_parser = after)] + after: After, + /// Stops after this many, 0 for no limit [default: 100, none with + /// --follow]. + #[arg(long)] + limit: Option, + /// Keeps going once caught up, checking every --interval, until + /// stopped (Ctrl+C) or the connection fails. + #[arg(short, long)] + follow: bool, + /// How often --follow checks, in milliseconds. + #[arg(long, default_value_t = 500, value_parser = clap::value_parser!(u64).range(10..=3_600_000))] + interval: u64, + /// Also prints when each was pushed (UTC), between its id and its + /// data. + #[arg(short, long)] + time: bool, + }, + /// Runs read-only SQL on the server, prints its result as JSON: + /// {"columns":[...],"rows":[[...],...]}. The client's roles must allow + /// queries. + Query { + /// One SELECT (or WITH ... SELECT), @FILE for a file's, - for the + /// standard input's. + sql: String, + }, + /// Lists the topics this client may use (every one if it may query) and + /// the nodes with messages. + List { + /// What to list. + #[arg(value_enum, default_value_t = What::All)] + what: What, + /// Prints JSON, a line per list: {"kind":...,"names":[...],"truncated":...}. + #[arg(long)] + json: bool, + }, +} + +/// Where `messages` starts. +#[derive(Clone, Copy)] +enum After { + Id(u64), + Latest, +} + +fn after(text: &str) -> Result { + if text.eq_ignore_ascii_case("latest") { + return Ok(After::Latest); + } + text.parse() + .map(After::Id) + .map_err(|_| "a message id or \"latest\"".to_owned()) +} + +#[derive(Clone, Copy, ValueEnum)] +enum What { + Topics, + Nodes, + All, +} + +/// `client.toml`: paths are relative to its folder. +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct ClientToml { + server: String, + ca: PathBuf, + certificate: PathBuf, + key: PathBuf, + crl: Option, +} + +fn main() -> ExitCode { + let cli = Cli::parse(); + match run(&cli.config, cli.command) { + Ok(()) => ExitCode::SUCCESS, + Err(message) => { + eprintln!("{message}"); + ExitCode::FAILURE + } + } +} + +fn run(config: &Path, command: Command) -> Result<(), String> { + match command { + Command::Push { + topic, + message, + attachment, + } => { + let message = input(&message)?; + let Some(path) = attachment else { + let id = connect(config)?.push(&topic, &message).map_err(failed)?; + println!("Pushed as message #{id}"); + return Ok(()); + }; + let mut file = fs::File::open(&path) + .map_err(|error| format!("Can't read {}: {error}", path.display()))?; + let id = connect(config)? + .push_with_attachment(&topic, &message, &mut file) + .map_err(failed)?; + let size = file.metadata().map_or(0, |metadata| metadata.len()); + println!("Pushed as message #{id}, with an attachment of {size} bytes"); + } + Command::Attachment { + topic, + node, + id, + file, + } => { + let size = connect(config)? + .save_attachment(&topic, &node, id, &file) + .map_err(failed)?; + println!("Saved {size} bytes as {}", file.display()); + } + Command::Latest { topic, node } => { + let message = latest(&mut connect(config)?, &topic, &node)? + .ok_or_else(|| format!("No message yet in {topic}:{node}"))?; + println!( + "Message {topic}:{node}#{}, pushed {}", + message.id, + utc(message.pushed_at) + ); + if let Some(attachment) = &message.attachment { + let here = if attachment.ready { + "" + } else { + ", not on this server yet" + }; + println!("Attachment: {} bytes{here}", attachment.size); + } + println!("{}", message.data); + } + Command::Messages { + topic, + node, + after, + limit, + follow, + interval, + time, + } => { + let mut client = connect(config)?; + let mut after = match after { + After::Id(id) => id, + After::Latest => latest(&mut client, &topic, &node)?.map_or(0, |m| m.id), + }; + let limit = limit.unwrap_or(if follow { 0 } else { 100 }); + let mut printed = 0; + let mut out = io::BufWriter::new(io::stdout().lock()); + loop { + let left = if limit > 0 { limit - printed } else { u64::MAX }; + let asked = left.min(u64::from(MAX_MESSAGES_PER_PACKET)) as u32; + let batch = client + .get_messages(&topic, &node, Some(after), asked) + .map_err(failed)?; + for message in &batch.messages { + after = message.id; + let written = if time { + let at = utc(message.pushed_at); + writeln!(out, "{after}\t{at}\t{}", message.data) + } else { + writeln!(out, "{after}\t{}", message.data) + }; + written.map_err(cant_write)?; + } + out.flush().map_err(cant_write)?; + printed += batch.messages.len() as u64; + if (limit > 0 && printed >= limit) || (!batch.more && !follow) { + break; + } + if !batch.more { + std::thread::sleep(Duration::from_millis(interval)); + } + } + } + Command::Query { sql } => { + let sql = input(&sql)?; + println!("{}", connect(config)?.query(&sql).map_err(failed)?); + } + Command::List { what, json } => { + let mut client = connect(config)?; + let kinds = [ + (NameKind::Topic, "topic", "Topics"), + (NameKind::Node, "node", "Nodes"), + ]; + for (kind, name, label) in kinds { + if matches!( + (what, kind), + (What::Topics, NameKind::Node) | (What::Nodes, NameKind::Topic) + ) { + continue; + } + let list = client.list_names(kind).map_err(failed)?; + if json { + let json = serde_json::json!({ + "kind": name, + "names": list.names, + "truncated": list.truncated, + }); + println!("{json}"); + continue; + } + println!("{label} ({}):", list.names.len()); + for name in &list.names { + println!(" {name}"); + } + if list.truncated { + println!(" ... more than fit in one answer"); + } + } + } + } + Ok(()) +} + +/// A topic and node's latest message, if any. +fn latest(client: &mut Client, topic: &str, node: &str) -> Result, String> { + let latest = client.get_messages(topic, node, None, 1).map_err(failed)?; + Ok(latest.messages.into_iter().next_back()) +} + +/// Connects with the settings in `config`. +fn connect(config: &Path) -> Result { + let text = fs::read_to_string(config).map_err(|error| { + format!( + "Can't read {}: {error} (the client's settings, see --help)", + config.display() + ) + })?; + let settings: ClientToml = + toml::from_str(&text).map_err(|error| format!("{}: {error}", config.display()))?; + let folder = config.parent().unwrap_or(Path::new("")); + let pem = |what: &str, path: &Path| { + let path = folder.join(path); + fs::read_to_string(&path) + .map_err(|error| format!("Can't read the {what} {}: {error}", path.display())) + }; + let ca = pem("CA's certificate", &settings.ca)?; + let certificate = pem("certificate", &settings.certificate)?; + let key = pem("key", &settings.key)?; + let crl = settings + .crl + .as_deref() + .map(|path| pem("CRL", path)) + .transpose()?; + let pems = Settings { + ca: &ca, + certificate: &certificate, + key: &key, + crl: crl.as_deref(), + }; + Client::connect(&settings.server, &pems).map_err(|error| { + format!( + "Failed to connect to {} ({}): {}", + settings.server, + code_name(error.code()), + error.message() + ) + }) +} + +/// A message or SQL from the command line: as is, `@FILE` for a file's, +/// `-` for the standard input's (a UTF-8 BOM dropped). +fn input(text: &str) -> Result { + let read = if text == "-" { + let mut read = String::new(); + io::stdin() + .read_to_string(&mut read) + .map_err(|error| format!("Can't read the standard input: {error}"))?; + read + } else if let Some(path) = text.strip_prefix('@') { + fs::read_to_string(path).map_err(|error| format!("Can't read {path}: {error}"))? + } else { + return Ok(text.to_owned()); + }; + Ok(match read.strip_prefix('\u{feff}') { + Some(rest) => rest.to_owned(), + None => read, + }) +} + +fn failed(error: Error) -> String { + let what = if is_refusal_code(error.code()) { + "Refused by the server" + } else { + "Failed" + }; + format!("{what} ({}): {}", code_name(error.code()), error.message()) +} + +fn cant_write(error: io::Error) -> String { + format!("Can't write the output: {error}") +} + +/// Milliseconds since 1970 as "2026-11-08T14:03:59.123Z". +fn utc(ms: u64) -> String { + match time::OffsetDateTime::from_unix_timestamp_nanos(i128::from(ms) * 1_000_000) { + Ok(t) => format!( + "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}.{:03}Z", + t.year(), + u8::from(t.month()), + t.day(), + t.hour(), + t.minute(), + t.second(), + t.millisecond() + ), + Err(_) => format!("{ms} ms"), + } +} diff --git a/crates/bakashrot-tools/tests/bakashrot.rs b/crates/bakashrot-tools/tests/bakashrot.rs new file mode 100644 index 0000000..988e633 --- /dev/null +++ b/crates/bakashrot-tools/tests/bakashrot.rs @@ -0,0 +1,556 @@ +//! `bakashrot` end to end against a server on a free port: the old suites' +//! tool checks (GetMessages, Names, BigMessages). + +use bakashrot_client::{Client, Settings}; +use bakashrot_config::Config; +use bakashrot_pki::{Ca, Identity, Usage}; +use bakashrot_server::Server; +use std::fs; +use std::io::{BufRead, BufReader, Write}; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::sync::mpsc; +use std::time::{Duration, Instant}; + +const CONFIG: &str = r#" +[server] +listen = "127.0.0.1:0" +ca = "ca.crt" +certificate = "server.crt" +key = "server.key" +topics = ["logs", "secret"] +synchronous = "normal" + +[roles.home] +push_topics = ["logs", "secret"] +read_topics = ["*"] +query = true + +[roles.lounge] +read_topics = ["logs"] +"#; + +/// A server in a folder of its own, with `kitchen` (home) and `lounge` +/// (lounge) issued: `.crt`, `.key` and `.toml`. +struct Running { + folder: PathBuf, + port: u16, + runtime: Option, +} + +impl Running { + fn start(name: &str) -> Running { + let folder = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(format!("tool-{name}")); + let _ = fs::remove_dir_all(&folder); + fs::create_dir_all(&folder).unwrap(); + let issued = Ca::create("Test CA", 10).unwrap(); + let ca = Ca::load(&issued.certificate, &issued.key).unwrap(); + let server = ca + .issue( + &Identity::new("server-1", &["peer"]).unwrap(), + Usage::Server, + 10, + ) + .unwrap(); + fs::write(folder.join("ca.crt"), &issued.certificate).unwrap(); + fs::write(folder.join("server.crt"), &server.certificate).unwrap(); + fs::write(folder.join("server.key"), &server.key).unwrap(); + fs::write(folder.join("server.toml"), CONFIG).unwrap(); + let server = Server::start(Config::load(&folder.join("server.toml")).unwrap()).unwrap(); + + let runtime = tokio::runtime::Runtime::new().unwrap(); + let listener = runtime + .block_on(tokio::net::TcpListener::bind("127.0.0.1:0")) + .unwrap(); + let port = listener.local_addr().unwrap().port(); + runtime.spawn(async move { server.serve(listener).await }); + + for (name, role) in [("kitchen", "home"), ("lounge", "lounge")] { + let issued = ca + .issue(&Identity::new(name, &[role]).unwrap(), Usage::Client, 10) + .unwrap(); + fs::write(folder.join(format!("{name}.crt")), &issued.certificate).unwrap(); + fs::write(folder.join(format!("{name}.key")), &issued.key).unwrap(); + let toml = format!( + "server = \"127.0.0.1:{port}\"\nca = \"ca.crt\"\ncertificate = \"{name}.crt\"\nkey = \"{name}.key\"\n" + ); + fs::write(folder.join(format!("{name}.toml")), toml).unwrap(); + } + Running { + folder, + port, + runtime: Some(runtime), + } + } + + /// Runs the tool as `who` (`kitchen`, `lounge`). + fn tool(&self, who: &str, args: &[&str]) -> Run { + run(&self.folder, who, args, None) + } + + /// A client of the library's, as kitchen: pushing many is quicker. + fn client(&self) -> Client { + let read = |name: &str| fs::read_to_string(self.folder.join(name)).unwrap(); + let (ca, certificate, key) = (read("ca.crt"), read("kitchen.crt"), read("kitchen.key")); + let settings = Settings { + ca: &ca, + certificate: &certificate, + key: &key, + crl: None, + }; + Client::connect(&format!("127.0.0.1:{}", self.port), &settings).unwrap() + } + + /// Stops the server: its connections close. + fn stop(&mut self) { + if let Some(runtime) = self.runtime.take() { + runtime.shutdown_background(); + } + } +} + +/// What a run printed, and its exit code. +#[derive(Debug)] +struct Run { + code: i32, + out: String, + err: String, +} + +impl Run { + fn lines(&self) -> Vec<&str> { + self.out.lines().collect() + } + + /// The ids `messages` printed. + fn ids(&self) -> Vec { + self.lines() + .iter() + .filter_map(|line| line.split('\t').next()?.parse().ok()) + .collect() + } + + #[track_caller] + fn ok(&self) -> &Run { + assert_eq!(self.code, 0, "{self:?}"); + self + } + + #[track_caller] + fn fails(&self, code: i32, text: &str) { + assert_eq!(self.code, code, "{self:?}"); + assert!(self.err.contains(text), "expected '{text}': {self:?}"); + } +} + +fn run(folder: &Path, who: &str, args: &[&str], stdin: Option<&str>) -> Run { + let mut child = Command::new(env!("CARGO_BIN_EXE_bakashrot")) + .args(["-c", &format!("{who}.toml")]) + .args(args) + .current_dir(folder) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let mut input = child.stdin.take().unwrap(); + if let Some(text) = stdin { + input.write_all(text.as_bytes()).unwrap(); + } + drop(input); + let output = child.wait_with_output().unwrap(); + Run { + code: output.status.code().unwrap_or(-1), + out: String::from_utf8(output.stdout).unwrap(), + err: String::from_utf8(output.stderr).unwrap(), + } +} + +fn range(from: u64, to: u64) -> Vec { + (from..=to).collect() +} + +#[test] +fn pushes_and_latest() { + let server = Running::start("push"); + let push = |args: &[&str]| server.tool("kitchen", &[&["push"], args].concat()); + + assert_eq!( + push(&["logs", r#"{"t":21,"room":"kitchen"}"#]).ok().out, + "Pushed as message #1\n" + ); + fs::write(server.folder.join("m.json"), "\u{feff}{\"from\":\"file\"}").unwrap(); + assert_eq!( + push(&["logs", "@m.json"]).ok().out, + "Pushed as message #2\n" + ); + let piped = run( + &server.folder, + "kitchen", + &["push", "logs", "-"], + Some("piped\ntext"), + ); + assert_eq!(piped.ok().out, "Pushed as message #3\n"); + assert_eq!(push(&["secret", "{}"]).ok().out, "Pushed as message #1\n"); + + let latest = server.tool("kitchen", &["latest", "logs", "kitchen"]); + let lines = latest.ok().lines(); + assert!( + lines[0].starts_with("Message logs:kitchen#3, pushed 20"), + "{lines:?}" + ); + assert!( + lines[0].ends_with('Z') + && lines[0].len() == "Message logs:kitchen#3, pushed 2026-11-08T14:03:59.123Z".len() + ); + assert_eq!(lines[1..], ["piped", "text"]); + let messages = server.tool("kitchen", &["messages", "logs", "kitchen"]); + assert_eq!( + messages.ok().lines()[..2], + [r#"1 {"t":21,"room":"kitchen"}"#, r#"2 {"from":"file"}"#] + ); + + // Refusals, the client's own failures. + server + .tool("lounge", &["push", "logs", "{}"]) + .fails(1, "Refused by the server (NotAllowed)"); + push(&["nope", "{}"]).fails(1, "Refused by the server (UnknownName): "); + push(&["bad name!", "{}"]).fails(1, "Failed (InvalidArgument)"); + push(&["logs", "@missing.json"]).fails(1, "Can't read missing.json"); + let big = "x".repeat(bakashrot_proto::limits::MAX_MESSAGE_SIZE + 1); + fs::write(server.folder.join("big.txt"), big).unwrap(); + push(&["logs", "@big.txt"]).fails(1, "Failed ("); + server + .tool("lounge", &["latest", "logs", "lounge"]) + .fails(1, "No message yet in logs:lounge"); + server + .tool("lounge", &["latest", "secret", "kitchen"]) + .fails(1, "(NotAllowed)"); + server + .tool("kitchen", &["push", "logs"]) + .fails(2, "MESSAGE"); +} + +#[test] +fn messages() { + let server = Running::start("messages"); + assert!( + server + .tool("kitchen", &["messages", "logs", "kitchen"]) + .ok() + .out + .is_empty() + ); + assert!( + server + .tool( + "kitchen", + &["messages", "logs", "kitchen", "--after", "latest"] + ) + .ok() + .out + .is_empty() + ); + + let mut client = server.client(); + for i in 1..=120 { + client.push("logs", &format!(r#"{{"i":{i}}}"#)).unwrap(); + } + let messages = |who: &str, args: &[&str]| server.tool(who, &[&["messages"], args].concat()); + + let first = messages("kitchen", &["logs", "kitchen"]); + assert_eq!(first.ok().ids(), range(1, 100), "the first 100 by default"); + assert_eq!(first.lines()[0], r#"1 {"i":1}"#); + assert_eq!(first.lines()[99], r#"100 {"i":100}"#); + assert_eq!( + messages("kitchen", &["logs", "kitchen", "--limit", "0"]) + .ok() + .ids(), + range(1, 120) + ); + assert_eq!( + messages("kitchen", &["logs", "kitchen", "--after", "115"]) + .ok() + .ids(), + range(116, 120) + ); + assert_eq!( + messages( + "kitchen", + &["logs", "kitchen", "--after", "10", "--limit", "7"] + ) + .ok() + .ids(), + range(11, 17) + ); + assert!( + messages("kitchen", &["logs", "kitchen", "--after", "120"]) + .ok() + .out + .is_empty() + ); + assert!( + messages("kitchen", &["logs", "kitchen", "--after", "LATEST"]) + .ok() + .out + .is_empty() + ); + assert_eq!( + messages("kitchen", &["LOGS", "Kitchen", "--after", "118"]) + .ok() + .ids(), + range(119, 120) + ); + assert_eq!( + messages("lounge", &["logs", "kitchen", "--after", "100"]) + .ok() + .ids(), + range(101, 120) + ); + let timed = messages("kitchen", &["logs", "kitchen", "--after", "119", "--time"]); + let fields: Vec<&str> = timed.ok().out.trim_end().split('\t').collect(); + assert_eq!( + (fields[0], fields[2], fields[1].len()), + ("120", r#"{"i":120}"#, 24), + "{fields:?}" + ); + + client.push("secret", "{}").unwrap(); + assert_eq!(messages("kitchen", &["secret", "kitchen"]).ok().ids(), [1]); + messages("lounge", &["secret", "kitchen"]).fails(1, "(NotAllowed)"); + messages("kitchen", &["logs", "nobody"]).fails(1, "(UnknownName)"); + messages("kitchen", &["nothing", "kitchen"]).fails(1, "(UnknownName)"); + assert!( + messages("lounge", &["logs", "lounge"]).ok().out.is_empty(), + "its own node, none yet" + ); + messages("kitchen", &["logs", "kitchen", "--after", "soon"]) + .fails(2, "a message id or \"latest\""); + messages("kitchen", &["logs", "kitchen", "--nope"]).fails(2, "--nope"); + messages("kitchen", &["logs", "kitchen", "--interval", "5"]).fails(2, "--interval"); + + // As stored: not JSON, a line break spanning lines; big ones over + // several answers. + client.push("logs", "plain\ntext").unwrap(); + let big: Vec = (0..5) + .map(|i| format!("{i}{}", "y".repeat(600_000))) + .collect(); + for data in &big { + client.push("logs", data).unwrap(); + } + let read = messages("kitchen", &["logs", "kitchen", "--after", "120"]); + let lines = read.ok().lines(); + assert_eq!(lines[..2], ["121\tplain", "text"]); + for (i, data) in big.iter().enumerate() { + assert_eq!(lines[2 + i], format!("{}\t{data}", 122 + i)); + } + assert_eq!( + messages( + "kitchen", + &["logs", "kitchen", "--after", "121", "--limit", "2"] + ) + .ok() + .ids(), + [122, 123] + ); +} + +#[test] +fn follows() { + let mut server = Running::start("follow"); + let mut client = server.client(); + client.push("logs", "old").unwrap(); + + let mut follower = Command::new(env!("CARGO_BIN_EXE_bakashrot")) + .args([ + "-c", + "lounge.toml", + "messages", + "logs", + "kitchen", + "-f", + "--after", + "latest", + "--interval", + "20", + ]) + .current_dir(&server.folder) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let (lines, read) = mpsc::channel(); + let stdout = follower.stdout.take().unwrap(); + std::thread::spawn(move || { + for line in BufReader::new(stdout).lines() { + let _ = lines.send(line.unwrap()); + } + }); + + std::thread::sleep(Duration::from_millis(300)); + assert!( + follower.try_wait().unwrap().is_none(), + "keeps running once caught up" + ); + for i in 1..=3 { + client.push("logs", &format!("new {i}")).unwrap(); + } + let got: Vec = (0..3) + .map(|_| read.recv_timeout(Duration::from_secs(10)).unwrap()) + .collect(); + assert_eq!( + got, + ["2\tnew 1", "3\tnew 2", "4\tnew 3"], + "only the new ones" + ); + + drop(client); + server.stop(); + let started = Instant::now(); + let status = loop { + if let Some(status) = follower.try_wait().unwrap() { + break status; + } + assert!( + started.elapsed() < Duration::from_secs(20), + "still following" + ); + std::thread::sleep(Duration::from_millis(50)); + }; + assert_eq!(status.code(), Some(1), "fails once the server is gone"); +} + +#[test] +fn queries_and_lists() { + let server = Running::start("query"); + server.client().push("logs", r#"{"t":1}"#).unwrap(); + + let query = server.tool("kitchen", &["query", "SELECT 1 AS one"]); + assert_eq!( + query.ok().out, + "{\"columns\":[\"one\"],\"rows\":[[\"1\"]]}\n" + ); + fs::write(server.folder.join("q.sql"), r#"SELECT "two" AS "a b""#).unwrap(); + assert!( + server + .tool("kitchen", &["query", "@q.sql"]) + .ok() + .out + .contains(r#""a b""#) + ); + let piped = run(&server.folder, "kitchen", &["query", "-"], Some("SELECT 3")); + assert!(piped.ok().out.contains(r#"[["3"]]"#), "{piped:?}"); + server + .tool("lounge", &["query", "SELECT 1"]) + .fails(1, "(NotAllowed)"); + server + .tool("kitchen", &["query", "DELETE FROM messages"]) + .fails(1, "(QueryFailed)"); + + let all = server.tool("kitchen", &["list"]); + assert_eq!( + all.ok().out, + "Topics (2):\n logs\n secret\nNodes (1):\n kitchen\n" + ); + assert_eq!( + server.tool("lounge", &["list", "topics"]).ok().out, + "Topics (1):\n logs\n" + ); + let json = server.tool("kitchen", &["list", "nodes", "--json"]); + assert_eq!( + json.ok().out, + "{\"kind\":\"node\",\"names\":[\"kitchen\"],\"truncated\":false}\n" + ); + server + .tool("kitchen", &["list", "everything"]) + .fails(2, "everything"); +} + +#[test] +fn attachments() { + let server = Running::start("attachments"); + let photo: Vec = (0..2_500_000u32).map(|i| (i % 253) as u8).collect(); + fs::write(server.folder.join("photo.jpg"), &photo).unwrap(); + + let pushed = server.tool( + "kitchen", + &["push", "logs", r#"{"photo":1}"#, "-a", "photo.jpg"], + ); + assert_eq!( + pushed.ok().out, + "Pushed as message #1, with an attachment of 2500000 bytes\n" + ); + server.tool("kitchen", &["push", "logs", "{}"]).ok(); + server + .tool( + "kitchen", + &["push", "logs", "{}", "--attachment", "missing.jpg"], + ) + .fails(1, "Can't read missing.jpg"); + + let saved = server.tool( + "lounge", + &["attachment", "logs", "kitchen", "1", "copy.jpg"], + ); + assert_eq!(saved.ok().out, "Saved 2500000 bytes as copy.jpg\n"); + assert_eq!(fs::read(server.folder.join("copy.jpg")).unwrap(), photo); + server + .tool( + "lounge", + &["attachment", "logs", "kitchen", "2", "none.jpg"], + ) + .fails( + 1, + "Refused by the server (NotFound): no attachment for logs:kitchen#2", + ); + assert!( + !server.folder.join("none.jpg").exists(), + "a refused one leaves no file" + ); + + let mut client = server.client(); + client.push("logs", "{}").unwrap(); + let mut tiny = std::io::Cursor::new(b"tiny".to_vec()); + client + .push_with_attachment("logs", "last", &mut tiny) + .unwrap(); + let latest = server.tool("kitchen", &["latest", "logs", "kitchen"]); + let lines = latest.ok().lines(); + assert!(lines[0].starts_with("Message logs:kitchen#4,"), "{lines:?}"); + assert_eq!(lines[1..], ["Attachment: 4 bytes", "last"]); +} + +#[test] +fn settings() { + let server = Running::start("settings"); + let folder = &server.folder; + run(folder, "nobody", &["list"], None).fails(1, "Can't read nobody.toml"); + + // Paths are relative to the file's folder, wherever it runs from. + fs::create_dir_all(folder.join("elsewhere")).unwrap(); + let up = run( + &folder.join("elsewhere"), + "../kitchen", + &["list", "topics"], + None, + ); + assert_eq!(up.ok().out, "Topics (2):\n logs\n secret\n"); + + let kitchen = fs::read_to_string(folder.join("kitchen.toml")).unwrap(); + fs::write( + folder.join("typo.toml"), + kitchen.replace("certificate =", "certficate ="), + ) + .unwrap(); + run(folder, "typo", &["list"], None).fails(1, "certficate"); + fs::write( + folder.join("crl.toml"), + format!("{kitchen}crl = \"none.crl\"\n"), + ) + .unwrap(); + run(folder, "crl", &["list"], None).fails(1, "Can't read the CRL"); + let closed = kitchen.replace(&server.port.to_string(), "1"); + fs::write(folder.join("closed.toml"), closed).unwrap(); + run(folder, "closed", &["list"], None) + .fails(1, "Failed to connect to 127.0.0.1:1 (ConnectFailed)"); +} diff --git a/crates/bakashrot-tools/tests/cert.rs b/crates/bakashrot-tools/tests/cert.rs new file mode 100644 index 0000000..6d030dc --- /dev/null +++ b/crates/bakashrot-tools/tests/cert.rs @@ -0,0 +1,149 @@ +//! `bakashrot-cert` end to end, in a folder of the build's. + +use bakashrot_pki::{Revocations, summarize}; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::Command; + +fn folder(name: &str) -> PathBuf { + let folder = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(name); + let _ = fs::remove_dir_all(&folder); + fs::create_dir_all(&folder).unwrap(); + folder +} + +/// Runs the tool in `folder`: whether it succeeded, and what it printed. +fn cert(folder: &Path, args: &[&str]) -> (bool, String) { + let output = Command::new(env!("CARGO_BIN_EXE_bakashrot-cert")) + .args(args) + .current_dir(folder) + .output() + .unwrap(); + let text = format!( + "{}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + (output.status.success(), text) +} + +fn read(folder: &Path, name: &str) -> String { + fs::read_to_string(folder.join(name)).unwrap() +} + +#[test] +fn a_ca_issues_and_revokes() { + let folder = folder("cert-tool"); + let (ok, text) = cert(&folder, &["ca", "--name", "Test CA"]); + assert!(ok, "{text}"); + if bakashrot_pki::IDENTITY_OID_IS_PLACEHOLDER { + assert!(text.contains("OID is still a placeholder"), "{text}"); + } + assert!( + cert( + &folder, + &[ + "issue", "--name", "kitchen", "--role", "sensor", "--role", "reader" + ] + ) + .0 + ); + assert!(cert(&folder, &["issue", "--name", "garage"]).0); + assert!( + cert( + &folder, + &["issue", "--name", "server-1", "--role", "peer", "--server"] + ) + .0 + ); + + let (ok, text) = cert(&folder, &["show", "kitchen.crt"]); + assert!(ok, "{text}"); + assert!( + text.contains("name: kitchen") && text.contains("roles: sensor, reader"), + "{text}" + ); + assert!( + text.contains("usage: client") && text.contains("issuer: Test CA"), + "{text}" + ); + let (_, text) = cert(&folder, &["show", "server-1.crt"]); + assert!(text.contains("usage: server"), "{text}"); + let (_, text) = cert(&folder, &["show", "ca.crt"]); + assert!(text.contains("usage: CA"), "{text}"); + + // Revoking twice keeps the first. + assert!(cert(&folder, &["revoke", "kitchen.crt"]).0); + let (ok, text) = cert(&folder, &["revoke", "garage.crt", "kitchen.crt"]); + assert!(ok && text.contains("(2 revoked)"), "{text}"); + let revocations = + Revocations::load(&read(&folder, "ca.crl"), &read(&folder, "ca.crt")).unwrap(); + assert_eq!(revocations.len(), 2); + for (name, revoked) in [("kitchen", true), ("garage", true), ("server-1", false)] { + let serial = summarize(&read(&folder, &format!("{name}.crt"))) + .unwrap() + .serial; + assert_eq!( + revocations.serials().any(|s| s == serial), + revoked, + "{name}" + ); + } + assert!(!folder.join("ca.crl.new").exists()); +} + +#[test] +fn a_name_can_have_several_certificates() { + let folder = folder("cert-tool-same-name"); + assert!(cert(&folder, &["ca", "--name", "Test CA"]).0); + let server = ["issue", "--name", "server-1", "--role", "peer", "--server"]; + assert!(cert(&folder, &server).0); + assert!(!cert(&folder, &server).0, "server-1.crt is there already"); + let (ok, text) = cert(&folder, &[&server[..], &["--file", "server-1b"]].concat()); + assert!(ok, "{text}"); + + let first = summarize(&read(&folder, "server-1.crt")).unwrap(); + let second = summarize(&read(&folder, "server-1b.crt")).unwrap(); + assert_eq!(first.identity, second.identity); + assert_ne!(first.serial, second.serial); + + // Revoking one leaves the other. + assert!(cert(&folder, &["revoke", "server-1b.crt"]).0); + let revocations = + Revocations::load(&read(&folder, "ca.crl"), &read(&folder, "ca.crt")).unwrap(); + assert!(revocations.serials().any(|s| s == second.serial)); + assert!(!revocations.serials().any(|s| s == first.serial)); +} + +#[test] +fn nothing_is_overwritten_or_mixed_up() { + let folder = folder("cert-tool-refusals"); + assert!(cert(&folder, &["ca", "--name", "Test CA"]).0); + let key = read(&folder, "ca.key"); + let (ok, text) = cert(&folder, &["ca", "--name", "Another"]); + assert!(!ok, "{text}"); + assert_eq!(read(&folder, "ca.key"), key, "the CA's key is still there"); + + assert!(cert(&folder, &["issue", "--name", "kitchen"]).0); + assert!( + !cert(&folder, &["issue", "--name", "kitchen"]).0, + "already there" + ); + assert!(!cert(&folder, &["issue", "--name", "12"]).0, "not a name"); + assert!( + !cert(&folder, &["issue", "--name", "garage", "--role", "a b"]).0, + "not a role" + ); + + // A certificate of another CA isn't revoked by this one. + let other = folder.join("other"); + fs::create_dir_all(&other).unwrap(); + assert!(cert(&other, &["ca", "--name", "Other CA"]).0); + assert!(cert(&other, &["issue", "--name", "stranger"]).0); + let (ok, text) = cert(&folder, &["revoke", "other/stranger.crt"]); + assert!(!ok && text.contains("not issued by this CA"), "{text}"); + assert!(!folder.join("ca.crl").exists()); + + let (ok, text) = cert(&folder, &["show", "missing.crt"]); + assert!(!ok && text.contains("missing.crt"), "{text}"); +} diff --git a/docker/Dockerfile b/docker/Dockerfile new file mode 100644 index 0000000..e888ee0 --- /dev/null +++ b/docker/Dockerfile @@ -0,0 +1,64 @@ +# The BakaShrot server's image: bakashrot-server, with the bakashrot and +# bakashrot-cert tools beside it. Built from the repository's root: +# docker build -f docker/Dockerfile -t bakashrot-server . +# CI builds it for amd64 and arm64 on a version tag, checks it +# (docker/test.sh) and pushes it to ghcr.io/aziascreations/bakashrot-server +# (.github/workflows/ci.yml). +# +# The config goes in /etc/bakashrot (read-only: server.toml, the CA's +# certificate, the server's certificate and key, the CRL if any), the +# database in /var/lib/bakashrot (a volume). In server.toml: +# listen = "0.0.0.0:7000" every interface: 127.0.0.1 isn't reachable +# from outside the container +# database = "/var/lib/bakashrot/bakashrot.sqlite" +# and the certificates relative to it (ca = "ca.crt", ...). The server runs +# as uid 10001, which must be able to read its key (bakashrot-cert writes +# keys readable by their owner only): chown 10001:10001 config/server-1.key +# +# docker run -d --name bakashrot -p 7000:7000 \ +# -v ./config:/etc/bakashrot:ro -v bakashrot-data:/var/lib/bakashrot \ +# ghcr.io/aziascreations/bakashrot-server +# +# Or docker/compose.yml. `docker stop` stops it cleanly (SIGTERM). +# The tools: docker run --rm bakashrot-cert ... (or bakashrot ...). + + +# --- Build --------------------------------------------------------------------- + +FROM rust:1-slim-trixie AS build + +WORKDIR /src +# Only what the programs are built from (Dockerfile.dockerignore). +COPY . . +# The toolchain rust-toolchain.toml pins, then the release build. +RUN rustup toolchain install \ + && cargo build --release --locked -p bakashrot-server -p bakashrot-tools \ + && mkdir /out \ + && cp target/release/bakashrot-server target/release/bakashrot target/release/bakashrot-cert /out/ + + +# --- Runtime ------------------------------------------------------------------- + +# The same Debian as the build: the programs only need its glibc. +FROM debian:trixie-slim + +# The source label links the package to the repository on ghcr.io. CI +# pushes each architecture's image as is, then an index of both with the +# same as annotations: GitHub reads those on an index. +LABEL org.opencontainers.image.source="https://github.com/aziascreations/BakaShrot" \ + org.opencontainers.image.description="BakaShrot server" \ + org.opencontainers.image.licenses="CC0-1.0" + +RUN groupadd --system --gid 10001 bakashrot \ + && useradd --system --uid 10001 --gid 10001 --home-dir /var/lib/bakashrot --shell /usr/sbin/nologin bakashrot \ + && mkdir -p /etc/bakashrot /var/lib/bakashrot \ + && chown bakashrot:bakashrot /var/lib/bakashrot + +COPY --from=build /out/ /usr/local/bin/ + +USER bakashrot +WORKDIR /var/lib/bakashrot +VOLUME /var/lib/bakashrot +EXPOSE 7000 + +CMD ["bakashrot-server", "/etc/bakashrot/server.toml"] diff --git a/docker/Dockerfile.dockerignore b/docker/Dockerfile.dockerignore new file mode 100644 index 0000000..2ffdca4 --- /dev/null +++ b/docker/Dockerfile.dockerignore @@ -0,0 +1,8 @@ +# Only what the programs are built from: target/ alone can hold gigabytes +# of builds and test databases, and keys. +* +!Cargo.toml +!Cargo.lock +!rust-toolchain.toml +!.cargo +!crates diff --git a/docker/compose.yml b/docker/compose.yml new file mode 100644 index 0000000..d6adf72 --- /dev/null +++ b/docker/compose.yml @@ -0,0 +1,27 @@ +# BakaShrot's server with docker compose, from this folder: +# docker compose up -d pulls the image (--build: builds it here) +# docker compose logs -f +# docker compose down stops it cleanly (SIGTERM) +# +# config/, next to this file: server.toml, ca.crt, the server's certificate +# and key, the CRL if any (the Dockerfile says what server.toml needs; its +# key readable by uid 10001). The database lives in the bakashrot-data +# volume, kept by `down` (`down -v` deletes it). + +services: + bakashrot: + image: ghcr.io/aziascreations/bakashrot-server:latest + build: + context: .. + dockerfile: docker/Dockerfile + container_name: bakashrot + restart: unless-stopped + ports: + # server.toml's listen port. + - "7000:7000" + volumes: + - ./config:/etc/bakashrot:ro + - bakashrot-data:/var/lib/bakashrot + +volumes: + bakashrot-data: diff --git a/docker/test.sh b/docker/test.sh new file mode 100755 index 0000000..7fec479 --- /dev/null +++ b/docker/test.sh @@ -0,0 +1,68 @@ +#!/bin/sh +# Smoke-tests a server image, as CI does before pushing it: certificates by +# its bakashrot-cert, its server started with them, its bakashrot pushing +# and reading back over a Docker network, then `docker stop`, which must +# end it cleanly (exit code 0, "stopped"). +# Usage: docker/test.sh +set -eu +image=$1 +name=bakashrot-test-$$ +work=$(mktemp -d) +# The image's user (10001) writes the certificates there. +chmod 777 "$work" + +cleanup() { + docker rm -f -v "$name" >/dev/null 2>&1 || true + docker network rm "$name" >/dev/null 2>&1 || true + rm -rf "$work" +} +trap cleanup EXIT +fail() { + echo "FAILED: $1" + docker logs "$name" 2>&1 || true + exit 1 +} +tool() { + docker run --rm -v "$work:/w" -w /w --network "$name" "$image" "$@" +} + +docker network create "$name" >/dev/null +tool bakashrot-cert ca --name "Image test CA" +tool bakashrot-cert issue --name server-1 --server +tool bakashrot-cert issue --name tester --role tester +cat >"$work/server.toml" <"$work/client.toml" </dev/null +tries=0 +until docker logs "$name" 2>&1 | grep -q "listening on"; do + tries=$((tries + 1)) + [ "$tries" -lt 100 ] || fail "the server isn't listening" + [ "$(docker inspect -f '{{.State.Running}}' "$name")" = true ] || fail "the server exited" + sleep 0.2 +done + +tool bakashrot push imagetest '{"image":"test"}' | grep -q "message #1" || fail "push" +tool bakashrot messages imagetest tester | grep -q '"image":"test"' || fail "messages" + +docker stop "$name" >/dev/null +[ "$(docker inspect -f '{{.State.ExitCode}}' "$name")" = 0 ] || fail "the server's exit code" +docker logs "$name" 2>&1 | grep -q "stopped" || fail "no clean stop" +echo "The image: certificates, the server, a push read back, a clean stop: OK" diff --git a/docs/certificates.md b/docs/certificates.md new file mode 100644 index 0000000..91fff22 --- /dev/null +++ b/docs/certificates.md @@ -0,0 +1,135 @@ +# Certificates + +Who connects to whom, and how it's checked. The code is +`crates/bakashrot-pki` (the library) and `crates/bakashrot-tools` +(`bakashrot-cert`, the tool). Decided in `../revamp.md`, "Decided". + +## The idea + +One CA per deployment. Every client and every server has a certificate +from it, saying who it is: a node's name and its roles. Servers trust the +CA, not lists of keys; clients trust the CA, not a server's key. Revoking +is a CRL file from the CA, pushed to the servers. + +## Certificates + +- **Keys:** ECDSA P-384, signatures SHA-384 (the strongest rustls checks). +- **The identity**, an extension of BakaShrot's own, non-critical (rustls + refuses critical extensions it doesn't know): + + ``` + BakaShrotIdentity ::= SEQUENCE { + version INTEGER, -- 1 + name UTF8String, -- the node: "kitchen" + roles SEQUENCE OF UTF8String -- free: "sensor", "peer"... + } + ``` + + Names and roles follow the name rules (1-64 of `A-Z a-z 0-9 _ . -`, not + only digits), 64 roles at most. Roles mean nothing to the certificates: + the server's config says what each may do. +- **Its OID is a placeholder** (`IDENTITY_OID`, `1.3.6.1.4.1.32473.1.1`, + under the PEN RFC 5612 reserves for documentation; `bakashrot-cert` + warns while it is): it goes under NibblePoker's own PEN before + certificates are issued for real. Why, how to request it, what to change: + `oid.md`. +- **The CN is the name too**, for people (`openssl x509 -text`, logs). Only + the extension is trusted. +- **Clients' certificates** are for `clientAuth`. **Servers'** are for + `serverAuth` and `clientAuth` (a server is its peers' client), and have + one DNS name, `bakashrot-server` (`SERVER_NAME`): a label, not a host. +- **No host names or IPs:** a client connects to any address and asks for + `bakashrot-server`; rustls' own verifier then checks the server's + certificate is the CA's, valid, not revoked... and for servers. A + client's certificate can't pose as a server's: it isn't for `serverAuth` + and doesn't have the name. +- **Lifetimes:** the CA 10 years, the others 1 year, by default. +- **The CA's key stays off the servers:** whoever has it can make any + identity, peers included. + +## TLS + +`bakashrot_pki::tls`: TLS 1.3 only, through aws-lc, offering only the +strongest of everything (both ends are ours, nothing to negotiate down to): + +- cipher suite `TLS13_AES_256_GCM_SHA384`; +- key exchange `X25519MLKEM768`, the X25519 + ML-KEM hybrid (holds against + quantum computers too); +- ALPN `bakashrot`: what isn't BakaShrot is refused in the handshake (the + protocol's version is checked right after, `protocol.md`); +- a certificate from the CA on both ends; +- randomness (keys, nonces) from the OS: aws-lc's generator seeded from + Windows' `ProcessPrng` or Linux's `getrandom`, plus RDRAND, as BoringSSL + and `ring` do. Built without its CPU Jitter Entropy + (`AWS_LC_SYS_NO_JITTER_ENTROPY`, `../.cargo/config.toml`), which only adds + a source and cost 25 ms in every process, at its first connection. + +`server_config()` checks clients with rustls' verifier, `client_config()` +checks the server with rustls' verifier too (for `bakashrot-server`). Then +both check the certificate isn't revoked and has an identity. Once +connected, `peer_identity()` gives the other end's `Identity`. + +## Revocation + +- `bakashrot-cert revoke` writes `ca.crl`, signed by the CA, with every + certificate revoked before (written aside, then moved in place). +- A server reads it into `Revocations`, which its TLS setup shares + (`SharedRevocations`): replacing what's inside takes effect for the next + handshake, no new configuration needed. `Revocations::revokes()` tells + the server which open connections to drop. +- **Both ends check it:** `server_config()` and `client_config()` both take + the revocations (`Revocations::none()` without a CRL). A server dialing + its peer is the peer's client, with the same CRL: servers block each + other, whichever end dials. +- **Revoking is by certificate, not by name:** each certificate has its own + key and its own serial number (made from that key), so two of the same + name (two servers named alike, a new one before the old one goes) are + revoked one at a time. +- A CRL is only taken if it's the CA's: issued by it, its signature + checked. One that isn't is refused, the server keeps the previous one. + Its "next update" isn't held against it: CRLs are pushed by hand. +- The server watches the file (its time and size, every 5 s), reloads + it, and drops a revoked certificate's connection at its next request + (`server.md`). + +## The tool + +``` +bakashrot-cert ca --name "Home CA" ca.crt, ca.key +bakashrot-cert issue --name kitchen --role sensor kitchen.crt, kitchen.key +bakashrot-cert issue --name server-1 --role peer --server +bakashrot-cert revoke kitchen.crt ca.crl +bakashrot-cert show kitchen.crt +``` + +`--ca` (the folder of `ca.crt` / `ca.key`, `.` by default), `--out` (where +to write), `--days`, `--file` (the files' name when it isn't the node's: +another certificate of the same name, `--file server-1b`). Files are PEM. Nothing is ever written over an +existing certificate or key; keys are readable by their owner only on +Unix. `revoke` only takes certificates the CA issued. + +## Tests + +- `bakashrot-pki/tests/tls.rs`: handshakes in memory. The strongest + settings negotiated, identities both ways, a server as its peer's + client; refused: a client or a server of another CA, a client's + certificate posing as a server's, a revoked client (and taken again once + the CRL changes, on the same configuration), a certificate without an + identity, another protocol; clients given the CRL refusing a revoked + server, servers blocking each other both ways, two servers of the same + name each with its own certificate, revoked one at a time. +- `bakashrot-pki/tests/ca.rs`: what certificates say, a CA's key that isn't + its own, CRLs revoking exactly what they list, another CA's or a + tampered CRL refused, and OpenSSL agreeing (`openssl verify` for clients + and servers, the CRL's signature, a revoked certificate; skipped without + OpenSSL, Git's is found). +- `bakashrot-tools/tests/cert.rs`: the tool end to end, two certificates + of the same name, and what it refuses (overwriting, bad names and roles, + another CA's certificate). + +## For later + +- **`AllowedServerNames`** in a client's config and for the peers a + server dials: the server names it accepts (any of the CA's servers + without it). +- NibblePoker's PEN, replacing the placeholder OID (`oid.md`). diff --git a/docs/client.md b/docs/client.md new file mode 100644 index 0000000..9d9b760 --- /dev/null +++ b/docs/client.md @@ -0,0 +1,187 @@ +# The clients + +What apps connect with, in layers: + +| Layer | Where | For | +|---|---|---| +| `bakashrot-client` | `crates/bakashrot-client` | Rust: blocking, one connection per `Client` | +| The DLL | `crates/bakashrot-capi`: `bakashrot.dll`, `libbakashrot.so` | C and anything that loads a DLL: the old `BakaShrot_*` exports, one connection per process | +| C header | `bindings/c/bakashrot.h` | generated from the DLL (cbindgen) | +| PureBasic | `bindings/purebasic/` | the prototypes and the error codes, as the old DLL's | +| Python | `bindings/python/bakashrot.py` | `Client` over the DLL (ctypes), standard library only | +| The tools | `crates/bakashrot-tools`: `bakashrot` | the command line, over `bakashrot-client` | + +Decided in `../revamp.md`, "Decided" (2026-11-13). What goes over the +wire: `protocol.md`; the server's side: `server.md`. + +**Status:** steps 7 to 9: connecting, pushes, messages, attachments, +names, queries. + +## Who connects: certificates + +A client is its certificate, issued by the CA the servers trust +(`certificates.md`, `bakashrot-cert issue`): its name is its node, its +roles say what it may do on each server (`config.md`). It needs the CA's +certificate (to check the server's), its own certificate and key, and the +CA's CRL if there is one (servers it revokes are refused). + +### `client.toml` + +What Python's `Client.from_file()` and the tools read. Paths are relative +to the file's folder. + +```toml +server = "10.0.0.2:7000" # host:port, [an IPv6 address]:port +ca = "ca.crt" +certificate = "kitchen.crt" +key = "kitchen.key" +crl = "ca.crl" # optional +``` + +## The DLL + +The old DLL's conventions, kept: + +- **One connection per process.** Calls from several threads wait for each + other. +- **`A` and `W` exports:** strings in and out as UTF-8 (`char*`) or UTF-16 + (`uint16_t*`, `wchar_t*` on Windows; PureBasic uses these), + null-terminated. A null string is an empty one where that means + something (a message), refused otherwise (`InvalidArgument`). +- **Strings out** are copied into the caller's buffer of `BufferSize` + bytes: the getter returns the bytes needed, terminator included, and + copies nothing if they don't fit; a null buffer asks for the size. +- **Failures:** 0, or -1 where a count or an id is returned. Then + `BakaShrot_GetLastError()` gives the code (`../crates/bakashrot-proto/src/error.rs`: + 1-99 a server's refusal, the connection still open; 100 and up the + client's own) and `BakaShrot_GetRefusalReason()` why, in words (now for + every failure, not only refusals). After `ConnectionLost` or + `ProtocolError` the connection is closed: connect again. Nothing + reconnects by itself; a push whose answer was lost may have been stored. +- **Inside:** every export catches panics (`Internal`); no threads, no + runtime, so it unloads cleanly; nothing allocated on one side is freed + on the other; the C runtime linked statically on Windows (the release + DLL imports system DLLs only). + +| Exports | What | +|---|---| +| `SetCaCertificate`, `SetCertificate`, `SetPrivateKey`, `SetCrl` (`A`/`W`) | PEM text (starting with `-----BEGIN`), or the path of a file holding it; `SetCrl` null or empty for none. Before connecting (`AlreadyConnected`); a file that can't be read is `FileError` | +| `Connect(Host, Port)` (`A`/`W`) | TLS with those; refused: `AuthRejected` (the server refused the certificate), `ServerNotVerified` (this client refused the server's), `NotAllowed` (none of its roles is the server's), `VersionMismatch` | +| `IsConnected`, `Disconnect` | `IsConnected` notices a connection the server closed | +| `GetNode` (`A`/`W`) | the node the server says this client is | +| `PushMessageTo(Topic, Data)` (`A`/`W`) | the id, -1 on failure | +| `GetLatestMessageOf(Topic, Node)` (`A`/`W`) | 1, or 0 with `NotFound` when there's none yet | +| `GetMessages(Topic, Node, After, Limit)` (`A`/`W`) | how many (0 isn't a failure), -1 on failure; then `GetMessageCount`, `SelectMessage(Index)`, `HasMoreMessages` | +| `GetMessageId`, `GetMessagePushedAt`, `GetMessageAttachmentSize`, `IsMessageAttachmentReady`, `GetMessageData`/`Topic`/`Node` (`A`/`W`) | the selected message; topic and node as asked | +| `ListTopics`, `ListNodes`, then `GetNamesList` (`A`/`W`) | how many; `{"kind":"topic","names":[...],"truncated":false}` | +| `Query(Sql)`, then `GetQueryResult` (`A`/`W`) | `{"columns":[...],"rows":[[...],...]}` | +| `PushMessageWithFile(Topic, Data, FilePath)`, `PushMessageWithData(Topic, Data, *Data, Size)` (`A`/`W`) | the id, -1 on failure; the attachment 1 byte and up, as much as the server takes (`TooBig`); a file read twice (its SHA-256 first), one changed in between refused (`DataMismatch`) | +| `SaveAttachment(Topic, Node, MessageId, FilePath)` (`A`/`W`) | its size, -1 on failure (`NotFound`, `NotReady`, `AttachmentMismatch`); a failed one leaves no file | +| `LoadAttachment(Topic, Node, MessageId)` (`A`/`W`), then `GetAttachmentData(*Buffer, Size)`, `FreeAttachmentData()` | into memory, for small ones; the getter returns the size, copies nothing if it doesn't fit | +| `GetLastError`, `GetRefusalReason` (`A`/`W`) | why the last call failed | + +The header has each one's comment. Every name starts with `BakaShrot_`. + +### Changed from the PureBasic DLL + +- **Connecting:** certificates instead of keys and a node: + `SetCaCertificate`, `SetCertificate`, `SetCrl` are new, `SetPrivateKey` + takes a PEM key; `SetPublicKey`, `SetServerPublicKey`, `SetNode`, + `SetNodeId` are gone. `GetNode` is new (the node comes from the + certificate). +- **No default topic:** `PushMessage(Data)` is gone, `PushMessageTo` names + its topic. +- **Attachments:** the same six, by names. +- **No ids:** `GetLatestMessage(TopicId, NodeId)`, `GetMessageTopicId`, + `GetMessageNodeId`, `ResolveTopic`, `ResolveNode`, `GetResolvedName` are + gone; `GetNamesList` lists names. +- **The file:** `bakashrot.dll` (`libbakashrot.so`), no libsodium next to + it. + +## Python + +`bindings/python/bakashrot.py`, the old module adapted: `Client(server, ca, +certificate, key, crl=None)` (PEM text or paths) or +`Client.from_file("client.toml")` (Python 3.11+, `tomllib`; the rest runs +on 3.8), `client.node` once connected, `push(data, topic, +attachment=None)` (the topic required; the attachment bytes or a path), +`latest()`, `get_messages()`, `iter_messages()`, `follow()`, +`get_attachment()` (bytes), `save_attachment()` (a file), +`list_topics()` / `list_nodes()` (names), `query()` / `query_raw()`. +Errors: `RefusedError`, `ConnectionLostError`, `AuthError` (a certificate +refused, either way, or no role allowed), `BakaShrotError`. The DLL is +looked for next to the module, or `BAKASHROT_DLL`. The release has a +wheel with the library in it (`pip install bakashrot-*.whl`, nothing else: +`bindings/python/make_wheel.py`, `../README.md`, "Releases"). + +## PureBasic + +`bindings/purebasic/BakaShrot_Client_Prototypes.pbi` (with +`BakaShrot_ErrorCodes.pbi`): `BakaShrot_LoadClient("bakashrot.dll")`, then +the `W` exports under the old names, `BakaShrot_*String()` helpers for the +getters. Run directly, it's an example: `ClientExample + `, pushing a message and one +with an attachment, reading both back (checked by hand with 5.73 against +a server; not in CI, which has no PureBasic). + +## The tools + +`bakashrot`, the old `BakaShrot*` tools in one program (`bakashrot-cert`, +for the CA, is apart: `certificates.md`). Each command connects with +`-c ` (`client.toml` by default), does one thing and exits: 0, 1 on a +failure (why on stderr: `Refused by the server (NotAllowed): ...`, +`Failed to connect to ...`), 2 on bad arguments. `--help` on each. + +```text +bakashrot push logs '{"t":21}' Pushed as message #42 +bakashrot push logs @reading.json (- for the standard input) +bakashrot push logs '{"cam":1}' -a photo.jpg Pushed as message #43, with an attachment of 81234 bytes +bakashrot latest logs kitchen Message logs:kitchen#43, pushed 2026-11-14T09:12:03.120Z + Attachment: 81234 bytes + {"cam":1} +bakashrot attachment logs kitchen 43 copy.jpg Saved 81234 bytes as copy.jpg +bakashrot messages logs kitchen 1{"t":20}, a line each +bakashrot messages logs kitchen -f --after latest --time +bakashrot query "SELECT topic, count(*) FROM messages GROUP BY topic" +bakashrot list Topics (2): ... Nodes (1): ... +bakashrot list nodes --json {"kind":"node","names":["kitchen"],"truncated":false} +``` + +- **`messages`:** the first 100 by default (`--limit 0` for all), `--after + ` or `latest`; data as stored, a line break in it spanning lines; + `--follow` checks every `--interval` ms (500) until stopped or the + connection fails (exit 1); `--time` adds the push time between the id and + the data. +- **Attachments:** `push -a `; `attachment` replaces the file, + leaves none if it fails; `latest` says a message's (", not on this + server yet" for one on its way from a peer). +- **Messages and SQL:** inline, `@file` or `-` (a UTF-8 BOM dropped). + PowerShell before 7.3 drops the double quotes inside arguments: use a + file there. +- **Changed from the old tools:** one program; `-c` instead of the last + argument, `client.toml` instead of `client.ini`; `push` names its topic; + names only (no ids in the output, `ResolveIds` gone); errors on stderr; + `GetAttachment` is the `attachment` command. +- **Speed** (release, a local server, 2026-11-14): a command takes about + 11 ms, connecting included (the old tools 8 ms); `messages --limit 0` + writes 200,000 messages to a file in 0.26 s (Python's `iter_messages()`: + 1.5 s). Against the old ones: `server.md`, "Measured". + +## Tests + +`crates/bakashrot-capi/tests/`, each against a server on a free port: + +- `exports.rs`: the exports as C calls them: certificates from files and + PEM, the `W` strings (and some `A`), the buffers (the size, too small, + unaligned), selecting messages, attachments (from a file and memory, + saved and loaded, the buffer, refused ones), every refusal and the + client's own errors, closing, another identity. +- `python.rs`: runs `bindings/python/check_bakashrot.py` (the old one, + ported: 52 checks) on the DLL; skipped, saying so, without Python 3.11+. +- `header.rs`: `bindings/c/bakashrot.h` matches the exports (rewritten + when it doesn't: check it in). + +`crates/bakashrot-tools/tests/bakashrot.rs` runs the tool against a server: +the old GetMessages suite's checks (`--follow` too), the Names, +BigMessages and Attachments suites' tool checks, queries, lists, +`client.toml`. diff --git a/docs/config.md b/docs/config.md new file mode 100644 index 0000000..a33bfea --- /dev/null +++ b/docs/config.md @@ -0,0 +1,114 @@ +# The server's config + +One TOML file, read and checked at once by `crates/bakashrot-config`: a +config that's wrong is refused whole, saying where (the line, shown) and +why. Every value is checked as it's read (serde), so every refusal has its +line. Every key, with its default: `crates/bakashrot-config/example.toml`. +Decided in `../revamp.md`, "Decided". + +## What's in it + +| Section | What | +|---|---| +| `[server]` | where it listens, the certificate files, the database, its topics, how pushes are flushed, attachments, retention's pace | +| `[retention]` | how long each topic's messages are kept | +| `[replication]` | the servers it sends to and takes from, the topics replicated at all, retry and sync pace, batch size | +| `[roles.]` | what certificates with that role may do | + +Unknown keys are refused, so a typo or a key of the old ini is caught. + +## Who's who: certificates, then roles + +A connection's certificate (`certificates.md`) says its node (its name) +and its roles. The server looks its roles up in `[roles.*]`: + +- **Everything its roles allow, each role on its own**: `sensor` and + `reader` push what `sensor` may push, read what `reader` may read. For + replication, a role's topics go with that role's nodes, they're not + mixed with another role's. +- **None of its roles has a section: refused.** Roles the server doesn't + know are ignored (a certificate may have roles for other servers). +- Roles compare without case, like names. + +What a role gives: + +| Key | Default | Allows | +|---|---|---| +| `push_topics` | none | pushing to these topics, always as its own node | +| `read_topics` | none | reading these topics' messages | +| `query` | `false` | read-only SQL, which reads every topic | +| `send_topics` | none | replication: these topics sent to it | +| `accept_topics` | none | replication: these topics taken from it | +| `send_nodes` | `["*"]` | replication: only these nodes' messages sent | +| `accept_nodes` | `["*"]` | replication: only these nodes' messages taken | + +No `AllowRead` / `AllowWrite`: a list that's empty allows nothing. No +default topic: a push always names its topic (protocol 7 has none). + +## Peers + +Who replicates with whom is each server's config, by address (not the +certificates: that would mean reissuing them): + +- **`[replication] push_to`:** the servers it dials and sends to, + `host:port`. +- **`[replication] accept_from`:** the servers it takes replicated + messages from, IP addresses or hostnames without a port, `"*"` for + all; none by default. Clients aren't concerned: they push wherever + their roles allow. + +A link carries messages one way: the server that dials sends, the one +dialed takes them. What's sent and taken is still the roles': the other +server's certificate's roles here, their `send_*` for what's sent to it, +their `accept_*` for what's taken from it. + +`[replication] replicated_topics`, optional, filters every peer's +replication whatever its roles say: an edge node that keeps some topics to +itself. Without it, no filter; `[]` replicates nothing. Pushing and reading +aren't filtered. + +## Names and values + +- **Names** (topics, nodes, roles): 1-64 of `A-Z a-z 0-9 _ . -`, not only + digits, compared without case. Lists of topics or nodes also take + patterns: `*` any characters, `?` one, `"*"` for all. `[server] topics` + takes names only. +- **Names with dots are quoted as keys:** `"sensors.kitchen" = "12h"`, + `[roles."site.reader"]`. Unquoted, TOML reads dots as tables: refused, + `[retention]` says to quote. +- **Durations:** numbers with a unit (`s m h d w`), added up: `"30s"`, + `"1d12h"`. Ages in `[retention]` can also be `"forever"`. +- **Sizes:** bytes, or `"500M"` with `K M G T` (1024-based), up to 1T. +- **Paths:** relative ones are from the config file's folder. + +## Retention + +A topic takes its name's line, else the first pattern matching it in the +file's order, else `"*"`'s line wherever it is; without any, it's kept +forever. Ages count from when a message was first pushed, on whichever +server; each server has its own. + +## What changed from the old ini + +| Old (`OldSource/Server/Config/schema.ini`) | Now | +|---|---| +| `PrivateKey`, `[BakaShrot] Node` | `ca`, `certificate`, `key`: the node is the certificate's name | +| `[BakaShrot.Client.*]`: keys, `Node`, `Allow*` | `[roles.*]`, the node and roles from the certificate | +| `[BakaShrot.Peer.*]`: `Host`, `Port`, `Node`, `PublicKey`, topic and node lists | `[replication] push_to` and `accept_from` (addresses), the lists in the peer's roles | +| `ReplicatingTopics` | each peer role's `send_topics` / `accept_topics`; `replicated_topics` filters them all | +| topic and node ids, pins, ranges, `[BakaShrot.Nodes]` | names only: ids are the database's | +| `DefaultTopic` | dropped: a push always names its topic | +| `Host` + `Port` | `listen` | +| seconds | durations (`"10s"`) | +| `NetThreadPoolSize` | gone (tokio) | +| `UploadTimeout` | gone: attachments are streamed in their push (protocol 7), nothing waits | +| `FULL` / `NORMAL` | `"full"` / `"normal"`; `off` still refused | + +## Tests + +`crates/bakashrot-config/tests/config.rs`: the example, the defaults, +every setting, retention's order, permissions (several roles, none known, +replication per role), `replicated_topics`, paths from the config's +folder, and the refusals, each with its line: TOML errors, unknown keys +(the old ini's too), every value that's wrong, names twice (without case), +unquoted dotted names. diff --git a/docs/known-issues.md b/docs/known-issues.md new file mode 100644 index 0000000..937662a --- /dev/null +++ b/docs/known-issues.md @@ -0,0 +1,75 @@ +# Known issues and ideas + +What's still true of the PureBasic version's notes, for this one. That +version was removed on 2026-11-15; it's in git history up to commit +`68966a8` (`OldSource/Notes.md`, "Open items"; `OldSource/Design/`). + +## Threat model + +BakaShrot is an **internal tool, on trusted machines and a trusted +network**, not exposed to the internet. So: + +- TLS and the certificates are defence in depth: they stop a misconfigured + client or server from talking to the wrong one and keep data off the + wire in clear, they aren't holding off attackers. +- The security issues below are low priority unless the deployment + changes. If it ever faces an untrusted network, start with messages + signed by their origin and rate limiting connections. +- Correctness, durability and operations matter more: losing or mixing up + data, or a server that can't run unattended, hurts on day one. + +## Known issues + +- **One server per node, not checked.** A node's messages are pushed to + one server; the others get them by replication. A node pushing to two + servers that replicate makes the same ids with different messages on + each: only the last id per topic and node is compared, so it's never + noticed, and a replicated id already stored keeps the local message. + Fix if that rule ever has to go: one server owns each topic and node's + ids (the others refuse or forward pushes), or at least compare a hash of + the messages to log the drift. +- **Gaps in a topic and node's ids aren't detected** on replication (old + item 6). A server with `1, 2, 5` says 5 and never gets 3 and 4. Batches + are sent in order and a refusal stops them, so it needs something + unusual, but nothing repairs it. Fix: send the count with the last id + (count = last id: no gaps), compare ranges when they differ. +- **The attachments a server lacks:** it reports the 256 oldest at a + time (`SyncState`). With several peers, ones none of them has can hold + back newer ones. +- **Peers are trusted with what they replicate** (old item 12): a server + in `accept_from` can send any message its roles accept, for any node. + Messages carry no proof of who first wrote them. Fix: sign each message + with its node's key when first stored, check it on replication (every + server then needs every node's public key). +- **Private keys sit in PEM files**, readable by whoever can read them: on + trusted machines, file permissions are enough. +- **One connection per process in the DLL** (old item 10, `revamp.md`, + "Open questions"): a handle-based API for several. Polling rather than + pushed subscriptions; nothing reconnects by itself, on purpose. +- **At least once:** a push whose answer was lost (the server stopped + between committing and answering) is stored twice if retried. A client + that minds reads the latest message before retrying. + +## Ideas for later + +From the old benchmarks and suggestions (`OldSource/Design/Suggestions.md`), +worth it only when a use calls for them: + +- **Several pushes in flight per connection.** One request at a time + (`protocol.md`, "Rules") caps a node at one push per round trip: + thousands a second on a LAN, about 20 over 50 ms. A client could send + several before the first answer (answers come back in order; a request + id to match them), with an asynchronous push in the DLL beside the + blocking one. The server already groups pushes from every connection. +- **Replication, lower lag:** a link checks in again at once after + sending, otherwise every `sync_interval`. Next, cheapest first: check + in as soon as the writer commits something (at most every 100 ms or so); + send several batches before the first answer (the receiver must then + refuse a batch that doesn't follow its last id, which also closes the + gaps above); several connections per link, each topic and node always + on the same one. +- **Benchmark on two machines:** on one, the load generator and the + servers compete for the CPU and the disk. +- **A JSON field queried often:** a generated column with an index on it + turns a full scan into a lookup (`storage.md`, "For later", has the + other storage ideas). diff --git a/docs/lab.md b/docs/lab.md new file mode 100644 index 0000000..3056294 --- /dev/null +++ b/docs/lab.md @@ -0,0 +1,207 @@ +# A test lab, step by step + +Two servers replicating each other, a client pushing to one, another +reading from the other. Every command here was run as written (on one +machine, 2026-11-15, Windows): the outputs shown are what came back. + +Get a release (CI's artifacts, or `release.ps1` / `python release.py`): +the programs, `bakashrot.dll` / `libbakashrot.so`, the wheel, the +example configs. The certificates are throwaway for now: the identity +OID is a placeholder until NibblePoker's PEN (`oid.md`), every tool run +says so. Reissue them all once it changes. + +| Machine | What runs there | Files it gets | +|---|---|---| +| admin (any) | `bakashrot-cert` | `ca.key` stays here, never copied | +| server-1 | `bakashrot-server` | `ca.crt`, `server-1.crt`, `server-1.key`, `server.toml` | +| server-2 | `bakashrot-server` | `ca.crt`, `server-2.crt`, `server-2.key`, `server.toml` | +| kitchen | `bakashrot` (pushes to server-1) | `ca.crt`, `kitchen.crt`, `kitchen.key`, `client.toml` | +| dashboard | `bakashrot` (reads from server-2) | `ca.crt`, `dashboard.crt`, `dashboard.key`, `client.toml` | +| any | Python, pushes and reads | `ca.crt`, `lab-py.crt`, `lab-py.key`, `client.toml` | + +Below, `server-1.lab` and `server-2.lab` are the servers' addresses: put +their hostnames or IPs. The clients can be on the servers' machines. + +## 1. The certificates (admin) + +``` +bakashrot-cert ca --name "Lab CA" +bakashrot-cert issue --name server-1 --role peer --server +bakashrot-cert issue --name server-2 --role peer --server +bakashrot-cert issue --name kitchen --role sensor +bakashrot-cert issue --name dashboard --role dashboard +bakashrot-cert issue --name lab-py --role sensor --role dashboard +``` + +A certificate is its name (the node) and its roles; the servers' configs +say what each role may do. `--server` makes a server's certificate; with +the `peer` role, the other server's config lets it replicate. More +clients: one `issue` each, any name and roles (`--role a --role b`). + +## 2. The servers + +`server.toml` on server-1 (server-2's: swap `1` and `2`): + +```toml +[server] +listen = "0.0.0.0:7000" +ca = "ca.crt" +certificate = "server-1.crt" +key = "server-1.key" +crl = "ca.crl" # optional; a missing file is fine, it's watched +database = "bakashrot.sqlite" +topics = ["lab.temps", "lab.events"] + +[retention] +"*" = "7d" + +[replication] +push_to = ["server-2.lab:7000"] # dialed, sent to +accept_from = ["server-2.lab"] # taken from (its address as seen from here) + +[roles.sensor] +push_topics = ["lab.*"] + +[roles.dashboard] +read_topics = ["*"] +query = true + +[roles.peer] +send_topics = ["lab.*"] +accept_topics = ["lab.*"] +``` + +- `topics` are names, not patterns (`"lab.*"` there is refused, with its + line); the roles take patterns. +- Every setting, with its default: `server.example.toml` (`config.md`). +- Open the port: `New-NetFirewallRule -DisplayName BakaShrot -Direction + Inbound -Protocol TCP -LocalPort 7000 -Action Allow` on Windows, the + distribution's firewall on Linux. + +Start each one from its folder: `bakashrot-server server.toml`. Their logs: + +``` +INFO server-1 listening on 0.0.0.0:7000 +INFO server-2.lab:7000: linked to server-2 +``` + +The first to start says once that the other refused (`WARN ... +actively refused it`) and dials again every 10 s. Stop with Ctrl+C +(SIGTERM on Linux): what was answered is stored. Unattended: a systemd +unit (`server.md`, "Running"), NSSM on Windows, or Docker (below). + +## 3. The clients + +`client.toml` for kitchen (dashboard's: its own name, `server-2.lab`): + +```toml +server = "server-1.lab:7000" +ca = "ca.crt" +certificate = "kitchen.crt" +key = "kitchen.key" +``` + +`bakashrot` reads `client.toml` from the current folder (`-c` for +another). + +## 4. Things to try + +**Push on one server, read on the other.** On kitchen: + +``` +> bakashrot push lab.temps '{"celsius":21.5}' +Pushed as message #1 +> bakashrot push lab.events '{"with":"file"}' -a note.txt +Pushed as message #1, with an attachment of 6 bytes +``` + +(Quoted for bash and PowerShell 7.3+; cmd wants `"{\"celsius\":21.5}"`, +and Windows PowerShell 5.1 drops the inner quotes: there, `@file` reads +the message from a file, `-` from stdin.) A few seconds later (a check-in every 5 s), +on dashboard: + +``` +> bakashrot list +Topics (2): + lab.temps + lab.events +Nodes (1): + kitchen +> bakashrot messages lab.temps kitchen +1 {"celsius":21.5} +> bakashrot latest lab.events kitchen +Message lab.events:kitchen#1, pushed 2026-11-15T00:15:09.401Z +Attachment: 6 bytes +{"with":"file"} +> bakashrot attachment lab.events kitchen 1 got.txt +Saved 6 bytes as got.txt +> bakashrot query "SELECT topic, node, message_id, message_data ->> '$.celsius' AS c FROM messages" +{"columns":["topic","node","message_id","c"],"rows":[["lab.events","kitchen","1",null],["lab.temps","kitchen","1","21.5"]]} +``` + +**Refusals.** A topic not in the config: + +``` +> bakashrot push other "{}" +Refused by the server (UnknownName): unknown topic 'other' +``` + +A certificate whose roles aren't in the config +(`issue --name visitor --role guest`): + +``` +Failed to connect to server-1.lab:7000 (NotAllowed): none of visitor's roles (guest) is allowed on this server +``` + +**Catching up.** Stop server-2, push a few messages on kitchen (server-1 +takes them; it logs once that server-2 refused), start server-2: within +about 10 s every one is on dashboard, in order. + +**Revoking.** On admin, `bakashrot-cert revoke dashboard.crt` writes +`ca.crl`; copy it next to each server's `server.toml` (the `crl` above). +Within 5 s they reload it (`INFO ca.crl: reloaded, 1 revoked`), and the +certificate is refused, at its next connection or request: + +``` +Failed to connect to server-2.lab:7000 (AuthRejected): the server refused this client's certificate (CertificateRevoked) +``` + +**Python.** `pip install bakashrot-0.2.0-py3-none-.whl` (from the +release's `python/`), then, next to lab-py's `client.toml` (it may push and +read: `sensor` and `dashboard`): + +```python +import bakashrot + +with bakashrot.Client.from_file("client.toml") as client: + client.connect() + print(client.push({"celsius": 20.5}, "lab.temps")) # its id: 1 + print(client.latest("lab.temps", client.node)) # Message(id=1, topic='lab.temps', node='lab-py', ...) + print(client.query("SELECT COUNT(*) AS n FROM messages")) # [{'n': '...'}]: query results are strings +``` + +The whole API: +`client.md`, "Python". + +**Also worth a look:** a node pushes to one server only (its messages +reach the others by replication: pushing the same node to both makes +diverging ids, `known-issues.md`); `BAKASHROT_LOG=debug` for more logs; +the database is a plain SQLite file, the `messages` and `browse` views +are for looking into it (`storage.md`, "The query surface"). + +## Docker instead (Linux) + +The image `ghcr.io/aziascreations/bakashrot-server` (`server.md`, "In +Docker"; not run by hand yet, only CI's check). On a server's machine, +`docker/compose.yml` from the repository, and next to it `config/` with +`ca.crt`, the server's certificate and key and `server.toml` as above, +except: + +```toml +database = "/var/lib/bakashrot/bakashrot.sqlite" +``` + +The server runs as uid 10001, which must read its key: +`sudo chown 10001:10001 config/server-1.key`. Then `docker compose up -d`, +`docker compose logs -f`, `docker compose down` (a clean stop; the +database stays in its volume). diff --git a/docs/oid.md b/docs/oid.md new file mode 100644 index 0000000..d1989dc --- /dev/null +++ b/docs/oid.md @@ -0,0 +1,77 @@ +# The identity extension's OID + +**Open point:** the OID is a placeholder until NibblePoker has its own +Private Enterprise Number (PEN) from IANA. The owner's to request +(below), then a few lines to change here. + +## Why it matters + +Servers find a certificate's name and roles by its identity extension's +OID (`bakashrot_pki::IDENTITY_OID`). Changing the OID makes every +certificate issued before unreadable as a BakaShrot identity: all of them +would have to be issued again. So it's settled before certificates are in +use; what's inside the extension can still change (its `version` field) +without touching the OID. + +Within a deployment, only the CA's certificates are read, so another +extension using the same OID somewhere else can't confuse a server. The OID +mostly needs to be stable, and properly ours. + +## Now: a placeholder + +- `IDENTITY_OID = 1.3.6.1.4.1.32473.1.1`: under PEN 32473, "Example + Enterprise Number for Documentation Use" (RFC 5612). It works, but isn't + meant for real use, and examples elsewhere use it too. +- `IDENTITY_OID_IS_PLACEHOLDER = true`: `bakashrot-cert` warns whenever it + makes a CA or issues a certificate. +- Fine for development and tests; not for certificates in use. +- `OldSource/`'s UUID arc (`2.25.2320...0981`) can't be used: `rcgen` + writes OID parts of 64 bits at most, a UUID is 128. + +## Requesting a PEN + +From IANA's application page (checked 2026-11-13): + +1. **Check first** that NibblePoker doesn't have one: search the registry, + (it had none on + 2026-11-13). An organization that has one hands out sub-numbers under + it instead of asking for another. +2. **Apply** at . It's free. + It asks for: + - the **assignee**, the organization (or person) the number is for: + name ("NibblePoker"), address, country, phone (optional); + - a **contact**, the person IANA and others write to with questions, + who may also request changes later: name, address, country, phone and + fax (optional), **email** (required). +3. **Confirm** the request from the email IANA sends to that address. +4. **Wait:** if nothing else is needed, the number comes within seven days + of that confirmation. Questions: iana-pen@iana.org. + +**What's public:** the registry lists, for every number, the organization, +the contact's name and the contact's email address (written with `&` for +`@`). Use an address meant to be published (a role address, not a +personal one). + +Ask for one number for NibblePoker as a whole, not one per project: every +project gets its own branch under it. + +## Once the number is there + +With `` the number IANA gave: + +1. **Plan the branches**, and record them in the table below; a number + once given is never reused: + + | OID | What | + |---|---| + | `1.3.6.1.4.1.` | NibblePoker | + | `1.3.6.1.4.1..1` | BakaShrot | + | `1.3.6.1.4.1..1.1` | BakaShrot's identity extension | + +2. **In `crates/bakashrot-pki/src/lib.rs`:** `IDENTITY_OID` to + `[1, 3, 6, 1, 4, 1, , 1, 1]`, `IDENTITY_OID_IS_PLACEHOLDER` to + `false`. +3. **Update** this file (the table, "Now"), `certificates.md` and the open + point in `../revamp.md`. +4. **Issue again** any certificate made with the placeholder, and run + `test.ps1` (the tests issue their own, nothing to change there). diff --git a/docs/protocol.md b/docs/protocol.md new file mode 100644 index 0000000..f5f7f48 --- /dev/null +++ b/docs/protocol.md @@ -0,0 +1,183 @@ +# Protocol 7 + +What goes over a connection between a client and a server, or two servers. +The code is `crates/bakashrot-proto`; this describes it. Protocol 6, the +PureBasic one, is `OldSource/Design/Packets.md`: what the requests do is +mostly the same, the transport, the encoding and the packets themselves +were simplified (see the end). + +**Status (2026-11-13):** packets, frames, names and error codes are written +and tested (`bakashrot-proto`), so is the TLS setup (`bakashrot-pki`, +`certificates.md`). The server and the client speak it so far for +connecting, pushes and messages (`server.md`). + +## Transport + +- **TCP, then TLS 1.3**, both ends with a certificate from the deployment's + CA (mutual TLS, `revamp.md`, "Decided"), at the strongest settings + rustls has: ECDSA P-384 certificates, AES-256-GCM-SHA384, the X25519MLKEM768 + key exchange, nothing else offered. +- **Identities:** a certificate's identity extension gives its node's name + and roles. The client's is who it is; the server's is checked by the + certificate alone (the CA's, valid, not revoked, for servers, the name + expected), no host names or IPs. Revoked certificates are in the CA's + CRL: servers check it, and so do clients given it (servers dialing their + peers too). +- **ALPN `bakashrot`** (`limits::ALPN`): both ends offer it, what isn't + BakaShrot doesn't get past the TLS handshake. It isn't versioned. +- **The versions, first:** right after TLS, each end sends its protocol + version, 4 bytes little-endian (`frame::write_version()`), and reads the + other's (`frame::check_version()`). Different versions: both ends + abandon the connection (the client's error is `VersionMismatch`). This + comes before any frame, so it holds whatever later versions change. +- **The server speaks next:** a `Welcome`, saying who the connection is. + Then the client sends requests. A certificate none of whose roles the + server has gets a `RequestRefused` (`NotAllowed`) instead, then the + connection closes. +- **Frames:** every packet is one frame, its size as a 4-byte + little-endian unsigned integer, then the packet (`frame`). A size of 0, + or over `MAX_PACKET_SIZE` (16 MiB), aborts the connection as soon as it + arrived. The blocking client reads and writes them with `frame::read()` + / `write()`, the async server with `frame::codec()` (`tokio-util`). + +## Packets + +A packet is **a MessagePack array of two: its type, then its fields as an +array**, `[type, [field, ...]]`. A struct inside is an array of its fields, +an optional value nil or itself, bytes a binary. The structs in +`crates/bakashrot-proto/src/packets/` are the format: `serde` derives it +(`rmp-serde`'s compact form). Any MessagePack library reads it. For +example `PushMessage { topic: "logs", data: "{}", attachment: None }`: + +``` +92 array of 2 +04 type 4, PushMessage +93 its 3 fields +a4 6c 6f 67 73 "logs" +a2 7b 7d "{}" +c0 nil: no attachment +``` + +**Decoding checks everything** (`Packet::decode`): the types and number +of fields, each packet's rules (ranges, names, ids in order), and that +nothing follows. Anything wrong is a `DecodeError`: the connection is +aborted. (A struct given as a map of its field names is taken too, a +leniency of `serde`'s derive: nothing writes it, it isn't part of the +format, its values are checked all the same.) + +### Values + +- **Topics and nodes are names**, everywhere: 1-64 of `A-Z a-z 0-9 _ . -`, + not only digits, compared without case (`names`). A name that isn't one + is malformed (the client libraries check before sending); one the server + doesn't have is refused (`UnknownName`). Ids are each server's own, in + its database, never on the wire. +- **Patterns** (in a `SyncState`): names with `*` (any characters, none + included) and `?` (one). +- **Message ids:** 1 to 2^43 - 1 (`MAX_MESSAGE_ID`), in their topic/node + pair: what a server stores (`storage.md`, "Keys"). +- **Times:** milliseconds since 1970-01-01 00:00:00 UTC, 1 to + 9999-12-31 23:59:59.999 (`MAX_TIMESTAMP`). Stamped by the server a + message is pushed to, kept by replication. +- **Attachments:** `[size, sha256]`, 1 B to 1 TiB, sent in parts of + 1 MiB (`ATTACHMENT_PART_SIZE`), the last one what's left. + +### Types + +Direction: **C** client, **S** server, **P** peer (a server linked to +another, as its client). Ids are protocol 7's own (6 can't connect); a new +packet takes the next one, none is ever reused. + +| Id | Packet | Dir | Fields | Answered by | +|---|---|---|---|---| +| 1 | Welcome | S→C, S→P | `server` name, `node` name (the connection's, from its certificate) | | +| 2 | RequestRefused | S→C, S→P | `code` 1-99 (`error`), `reason` str | | +| 3 | Continue | S→C, S→P | none: send the attachment's parts | | +| 4 | PushMessage | C→S | `topic` name, `data` str (up to `MAX_MESSAGE_SIZE` bytes), `attachment` or nil | MessagePushed / RequestRefused; with an attachment, Continue first | +| 5 | MessagePushed | S→C, S→P | `message_id` | | +| 6 | GetMessages | C→S | `topic`, `node`, `after` (an id, 0 for all) or nil (the last ones), `limit` 1-10000 | Messages / RequestRefused | +| 7 | Messages | S→C | `more` bool, `[[id, pushed_at, data, [size, ready] or nil]...]` (ids strictly increasing, 10000 at most) | | +| 8 | GetAttachment | C→S | `topic`, `node`, `message_id`, `from_part` | Attachment then its parts / RequestRefused | +| 9 | Attachment | S→C | `size`, `sha256` | | +| 10 | AttachmentPart | C→S, S→C, P→S | `data` bin, 1 B to 1 MiB | | +| 11 | ListNames | C→S | `kind` (1 topics, 2 nodes) | NamesList | +| 12 | NamesList | S→C | `kind`, `truncated` bool, `[name...]` (65536 at most) | | +| 13 | Query | C→S | `sql` str | QueryResult / RequestRefused | +| 14 | QueryResult | S→C | `json` str: `{"columns":[...],"rows":[[...],...]}` | | +| 15 | SyncStateRequest | P→S | none | SyncState / RequestRefused | +| 16 | SyncState | S→P | `[topic...]`, `[node...]` (names and patterns it takes from P), `[[topic, node, last_id]...]`, `[[topic, node, message_id, next_part]...]` (attachments it lacks, 256 at most) | | +| 17 | ReplicateMessages | P→S | `topic`, `node`, `[[id, pushed_at, data, [size, sha256] or nil]...]` (1-10000, ids strictly increasing) | MessagePushed (the last id) / RequestRefused | +| 18 | ReplicateAttachment | P→S | `topic`, `node`, `message_id`, `from_part` | Continue, then its parts, then MessagePushed / RequestRefused | + +## Flows + +``` +Pushing C: PushMessage S: MessagePushed / RequestRefused + with an C: PushMessage(attachment) S: Continue / RequestRefused + attachment C: AttachmentPart x every part S: MessagePushed / RequestRefused (DataMismatch) +Reading C: GetMessages(after: id) S: Messages, `more` if others follow + the latest C: GetMessages(after: nil, 1) S: Messages (empty if none) +An attachment C: GetAttachment(from_part) S: Attachment, then AttachmentPart x the rest + / RequestRefused (NotFound, NotReady) +Replicating P: SyncStateRequest S: SyncState + P: ReplicateMessages x the batches S: MessagePushed each / RequestRefused + P: ReplicateAttachment x missing S: Continue / RequestRefused + P: AttachmentPart x from next_part S: MessagePushed / RequestRefused +``` + +- **Parts are streamed:** no request or answer per part, TCP paces them. + A part's index follows from the order, its exact size from the + attachment's size (`Attachment::part_len()`); the receiver checks both, + and the SHA-256 once all came. +- **Once the server said `Continue`**, it reads every part even if storing + them failed, then refuses: the client never has to read while sending. +- **A server failing while it sends parts** closes the connection; the + client asks again `from_part` the next one it needs. +- **Replication:** `SyncState` is all a check-in needs. The peer compares + it with what it has, by name, sends the messages the server lacks in + batches of up to `batch_size` messages and about 1 MiB (a bigger + message alone), then the attachments it listed. + +## Rules + +The same as protocol 6: + +- **One request at a time:** a client sends one, waits for its answer (the + parts of an attachment being part of its request or answer). +- **Refuse or abort:** valid but not allowed or not found (permissions, + unknown names, over a limit, a failed query) is a `RequestRefused` with a + code, the connection stays. Malformed or out of order (a bad frame, a + `DecodeError`, an unexpected packet) aborts it. Clients apply the same + to answers. +- **The identity is the connection's:** requests never say who sends them. + A push picks its topic, never its node. +- **Error codes** (`error`): 1-99 refusals, 100+ the client's own; the + numbers of protocol 6, never renumbered. + +## What changed from protocol 6 + +- **TLS** instead of the sealed Hello, the signed key exchange and the own + cipher: the handshake packets are gone, `Welcome` is new, the identity + comes from the certificate. +- **The version is checked once**, sent by both ends before anything else: + packets lost their magic and version. +- **Names only:** no ids on the wire, no refs. `ResolveName` / + `NameResolved` are gone, answers don't echo ids, `NamesList` is names, + `SyncState` gives its heads by name. +- **No default topic:** a push always names its topic, `Welcome` doesn't + give one (`NoDefaultTopic`, 6, is never sent). +- **Fewer packets, 26 → 18:** `GetMessages` with `after: nil` replaces + `GetLatestMessage`, `Messages` replaces `LatestMessage`; `SyncState` + lists the missing attachments (no `MissingAttachmentsRequest` / + `MissingAttachments`); answers don't echo what was asked. +- **Attachments are streamed in their request:** no upload ids, no uploads + waiting for their push (and no `UploadTimeout`), no request or answer per + part (`UploadStart`, `UploadStarted`, `UploadChunk`, `ChunkStored`, + `AttachmentChunk`, `ReplicateAttachmentChunk` are gone). An upload cut + short starts over (none resumed in protocol 6 either); reads and + replication go on `from_part`. +- **Encoding:** derived with `serde`, `[type, [fields...]]`, booleans and + nil where they belong (were 0/1 and empty values). Nothing may follow a + packet (was ignored). +- **No 4 KB limit before authentication:** TLS has authenticated both ends + before any frame. diff --git a/docs/server.md b/docs/server.md new file mode 100644 index 0000000..73a932e --- /dev/null +++ b/docs/server.md @@ -0,0 +1,371 @@ +# The server and the client + +`crates/bakashrot-server` (a library and the `bakashrot-server` program) +and `crates/bakashrot-client` (the blocking client library the C DLL will +wrap). Decided in `../revamp.md`, "Decided" (2026-11-13). What goes over +the wire: `protocol.md`. + +**Status:** steps 5, 6, 9, 10, 11 and 12: connecting, pushes and their +attachments, messages, attachments, names, queries, retention, +replication, stopping cleanly. Every request of protocol 7 is answered. + +## Running + +``` +bakashrot-server server.toml +``` + +The config (`config.md`) gives where to listen, the certificates, the CRL, +the database, the topics and the roles. Decided 2026-11-14 +(`../revamp.md`, "Operations"): + +- **Stopping:** SIGTERM or SIGINT on Linux; Ctrl+C, Ctrl+Break or its + console closed on Windows. It stops taking connections and writes + what was queued for the database (`Server::stop`): every push + answered is stored, the ones after are refused (`ServerError`, "the + server is stopping"), then it exits with 0. Nothing else to wait for: + a client whose push wasn't answered pushes it again (at least once). +- **No console commands** (the old `quit`, `restart`, `vacuum`, `names`, + `help`): it needs no console, a service manager runs it as is. `names` + is `bakashrot list`, `restart` a stop and a start. Maybe an admin + channel later. +- **Logs go to the console** (stdout, `tracing`), without colours when + it isn't a terminal: redirect them, or let systemd or Docker keep + them. `BAKASHROT_LOG` sets the level: `error`, `warn`, `info` (the + default), `debug`, `trace`. +- **No Windows service mode:** a tool like NSSM runs it as one, stopping + it with Ctrl+C. + +A systemd unit, for example: + +```ini +[Service] +ExecStart=/opt/bakashrot/bakashrot-server /etc/bakashrot/server.toml +User=bakashrot +Restart=on-failure +# SIGTERM, then 90 s at most: far more than a stop takes. +``` + +### In Docker + +`docker/Dockerfile` (its comments have the details), the image +`ghcr.io/aziascreations/bakashrot-server` (amd64 and arm64, pushed by CI +on a version tag): the server, with `bakashrot` and `bakashrot-cert` +beside it, on `debian:trixie-slim`, as uid 10001. + +- **The config** in `/etc/bakashrot`, read-only: `server.toml`, the + certificates, the server's key (readable by uid 10001: `chown 10001` + it, `bakashrot-cert` writes keys for their owner only). `listen = + "0.0.0.0:7000"`: 127.0.0.1 isn't reachable from outside. +- **The database** in `/var/lib/bakashrot`, a volume: `database = + "/var/lib/bakashrot/bakashrot.sqlite"`. +- **Running it:** `docker/compose.yml` (`docker compose up -d` from + `docker/`, the config in `docker/config/`), or `docker run -d -p + 7000:7000 -v ./config:/etc/bakashrot:ro -v + bakashrot-data:/var/lib/bakashrot `. `docker stop` is SIGTERM: + a clean stop. The logs: `docker logs`. +- **The tools:** `docker run --rm bakashrot-cert ...`. +- **Checked** by `docker/test.sh ` (CI runs it on both before + pushing): certificates by the image's tool, its server, a push read + back over a Docker network, `docker stop` ending it cleanly. + +## Inside the server + +| What | Where | How | +|---|---|---| +| Connections | tokio, a task each | TLS (`tokio-rustls`, `bakashrot-pki`'s settings), the versions, the identity, then requests one at a time | +| Writes | one writer thread | a queue of every write (pushes, uploads and their parts, replicated messages and parts, retention's deletes); the thread writes whatever is queued in one transaction (group commit, 1000 at most): the busier, the bigger the groups | +| Reads, queries | tokio's blocking threads | a pool of read connections and one of query connections (`query_only`), reused | +| WAL checkpoints | one thread, every second | its own connection, off the writer's way (`storage.md`) | +| The CRL file | a task, every 5 s | reloaded when its time or size changes; one that isn't the CA's is refused, the previous one stays | +| Retention | a task, at start then every `retention_interval` (1 min) | below | +| Replication | a task per server of `push_to` | below: links kept up, a check-in every `sync_interval` (5 s) | + +## Retention + +`[retention]` (`config.md`) says how long each topic's messages are kept. +At start, then every `retention_interval`, the server goes through every +topic in its database (one no longer in `topics` too) and deletes the +messages pushed before now minus its age, 10,000 per write, so pushes go +on between them. Then the parts of their attachments, 64 MB per write. +Each topic's count is logged ("deleted 3 messages of topic 'logs'"). + +- **In id order** (`storage.md`, "Retention"): a message stamped earlier + than the one before it (a clock set back) waits for that one. +- **Ids go on:** a stream's last id stays, the next push takes the next. +- **"May be" deleted past its age:** up to `retention_interval` later. +- **Each server its own:** a peer's ages are its own. What a peer sends + already past this server's age isn't stored, but counts as received: + it isn't sent again. + +## Replication + +Decided in `../revamp.md` ("Replication by address", 2026-11-14). +Each server's config says who it replicates with, by address +(`config.md`, "Peers"): `push_to`, the servers it dials and sends to; +`accept_from`, the servers whose messages it takes (`"*"` for all). A link +carries messages one way, from the server that dials to the one dialed; +the other way is the other server's own `push_to`. + +**Sending** (`push_to.rs`): a link to each server of `push_to`, as a +client with this server's certificate; a failed or dropped one is dialed +again after `retry_delay` (10 s), its failure logged once until it +changes. It checks in from the start, then again at once if it sent +something (so it keeps up under load), after `sync_interval` (5 s) +otherwise: + +1. `SyncStateRequest`: the other server answers what it takes from this + one (topics and nodes, patterns included), its last id in each topic + and node, and the attachments it lacks (256 at most). +2. **The messages:** for each topic and node here that it takes and that + its roles here may be sent (`send_topics`, `send_nodes`, + `replicated_topics`), and where it's behind, the messages after its + last id, `batch_size` (1000) at a time and about 1 MiB at most (a + bigger one alone), each batch answered before the next. A refusal + leaves that topic and node for the next check-in. +3. **The attachments it lacks:** those this server has ready, from the + part it needs. One it says doesn't match its SHA-256 is read back + here: damaged (a disk, a bug), this server's copy is dropped and asked + for again from its own peers (`replicating`, not served meanwhile), + instead of sent again at every check-in (the old open item 3). + +**Receiving** (`accept_from.rs`): replication requests are answered only +if the connection comes from `accept_from` (a hostname looked up at its +first request, `NotAllowed` otherwise), and only for what its roles' +`accept_topics` / `accept_nodes` allow (`NotAllowed`). Messages keep +their ids and `pushed_at`; ones already here are kept as they are; one +past this server's age is only counted. An attachment comes after its +message (`replicating`, `NotReady` to readers), from the part this server +needs, the parts it had read back for the SHA-256; matching, it's ready, +otherwise started over (`DataMismatch`). A stop between its last part +and the check: started over at the next start. + +**One server per node** stays the config's rule, as in the old version +(`known-issues.md`): a node pushing to two servers that replicate makes +the same ids with different messages, undetected. + +## A connection + +1. **TLS:** the client's certificate must be the CA's, valid, not revoked, + with an identity (`certificates.md`). A refused one gets TLS's alert, + then a gentle close: the server shuts down and reads until the client + closes (1 s at most). Closing at once reset the connection (the + client's version bytes unread), which could beat the alert to the + client: `ConnectionLost` instead of `AuthRejected`, about 1 in 10 under + load on Windows. +2. **The versions:** each end sends its own; different ones, the + connection is dropped (the client says `VersionMismatch`). +3. **The roles:** none of the certificate's roles in the config, the + server answers `RequestRefused` (`NotAllowed`, saying which roles) and + closes; otherwise `Welcome` (the server's name, the client's node). +4. **Requests**, one at a time. Before each, the certificate is checked + against the current CRL: revoked since, the connection is dropped. + A client closing without TLS's close_notify (the tools, the DLL, a + killed process) is a normal close, not logged. + +| Timeout | | +|---|---| +| TLS, versions, welcome | 10 s (the server); the client's connect too | +| Silence between requests | 5 min, then the server closes | +| An answer | 30 s (the client) | +| An attachment's next part | 30 s (the server), then it closes | + +## Requests so far + +- **`PushMessage`:** the topic must be one of the config's (`UnknownName`), + the roles must allow pushing to it (`NotAllowed`), the message at most + `MAX_MESSAGE_SIZE` (`TooBig`); stored under the client's node, stamped + with the server's time; answered `MessagePushed` once committed. +- **With an attachment:** also at most the config's `max_attachment_size` + (`TooBig`; 0 takes none). The server answers `Continue`, then reads + every part: each written while the next come (4 at most waiting for the + writer, so the client waits through TCP rather than the server holding + them), the SHA-256 computed as they come. All there and matching, the + message is stored with it, ready, in one transaction. A part of the + wrong size (`InvalidRequest`), a wrong SHA-256 (`DataMismatch`), a + failed write: refused once every part came, the connection kept. A + connection that closes, or sends anything else than the next part, is + dropped. Not pushed, the upload goes (`storage.md`, "Attachments"). +- **`GetAttachment`:** the roles must allow reading the topic + (`NotAllowed`), the topic must be one of the config's (`UnknownName`). + A message without one, or none of that id: `NotFound`; one still on its + way from a peer: `NotReady`; one this server doesn't keep: `TooBig`. + Then `Attachment` (its size, its SHA-256) and the parts from + `from_part`. A part that can't be read closes the connection. +- **`GetMessages`:** the roles must allow reading the topic + (`NotAllowed`), the topic must be one of the config's and the node one + with messages in any topic, or the client's own (`UnknownName`); a known + topic and node without messages answer none. At most `limit` messages and about 1 MB + (`MESSAGES_BYTES`, a bigger message alone), `more` if others follow. +- **`ListNames`:** topics are the config's, those the roles may push to or + read (every one with `query`, which reads them all anyway); nodes are + every one with messages. `truncated` past 65,536. +- **`Query`:** the roles must allow it (`NotAllowed`); read-only SQL, + refused with SQLite's message (`QueryFailed`, with a hint to add + `is_json = 1` on "malformed JSON"), over 10,000 rows or 16 MB + (`TooBig`), never a partial result (`storage.md`, "The query surface"). +- **Sizes:** frames up to 16 MB (`MAX_PACKET_SIZE`), a bigger one drops the + connection; messages up to `MAX_MESSAGE_SIZE` (16 MB less 4 KB), the + server refusing bigger ones (`TooBig`); the client refuses messages and + queries over it before sending (`InvalidArgument`). + +## The client + +`Client::connect(address, settings)` (`host:port`, the CA's certificate, +the client's certificate and key, the CRL if any), then `push(topic, +data)`, `get_messages(topic, node, after, limit)`, `list_names(kind)`, +`query(sql)`. Blocking, no runtime. The DLL and the bindings over it: +`client.md`. + +Attachments: `push_with_attachment(topic, data, source)`, the source any +`Read + Seek` (a `File`, a `Cursor`), read twice: its SHA-256, then its +parts; `get_attachment(topic, node, id, out)` into any `Write`, checked +with its SHA-256 once all came; `save_attachment(topic, node, id, path)`, +written to `path` and `.download` then moved over `path`, so a failed one +leaves no file. A source or a part that fails half-way closes the +connection (the server can't be told to stop); a failing `out` doesn't +(the rest is read, then `FileError`). + +Its errors are the protocol's codes: a server's refusal keeps its own +(1-99), the client's are 100 and up (`ConnectFailed`, `AuthRejected` when +the server refused its certificate, `ServerNotVerified` when it refused the +server's, `ConnectionLost`, `ProtocolError`, `InvalidArgument`, +`FileError`, `AttachmentMismatch`, `VersionMismatch`). + +## Measured + +`push_rate` (`tests/end_to_end.rs`, ignored by default): a whole server on +localhost, 10 clients each its own node (`CLIENTS`), one push at a time +each, 200-byte JSON, 20,000 pushes per client. + +| `synchronous` | 10 clients | Slowest push | 1 client | +|---|---|---|---| +| `normal` | 40,400/s | 37 ms | 14,200/s | +| `full` | 9,229/s | 9 ms | 1,920/s | + +- With `normal`, the server reaches the storage's own ceiling (about 37k/s + alone, `storage.md`, a slightly different load). Up from 36,000/s once + a connection's revocation check stopped reading its certificate at + every request (its serial is read once, at connect). +- One client waits for each answer: a round trip and a commit per push. + Through Python and the DLL, about 10,700 pushes/s (the old module did + about 9,000), and 140,000 messages/s read. +- With `full`, every group commit waits for the disk's flush (about 1 ms + here): 10 clients make groups of about 10. More clients, bigger groups. +- **Attachments** (release, the tool, `normal`): 200 MB up in 1.3 s and + down in 0.5 s, the tool's start and the client's hashing included. +- **Built for size** (`opt-level = "s"`, 2026-11-14; the numbers here + were measured before, at 3): `normal` about 5% lower (36,900-38,100/s + against 39,800-40,400), `full` the same (the disk's), attachments and + tool commands the same. The programs and the DLL 25-31% smaller. + +### Against the old server (2026-11-14) + +The same work on the same machine, release builds, one server on +localhost: the old one (`OldSource/Build/Bench/BenchServer.exe`, its DLL, +`bakashrot.py` and tools) and this one. Pushes and reads through each one's +Python module and DLL (10 clients: 10 processes, the same node), 200-byte +JSON; the rest through the tools. + +| | Old, `full` | New, `full` | Old, `normal` | New, `normal` | +|---|---|---|---|---| +| One tool command, connecting included | 8 ms | 12 ms | 8 ms | 11 ms | +| Pushes, 1 client | 1,945/s | 1,954/s | 9,386/s | 11,600-13,100/s | +| Pushes, 10 clients | 9,006/s | 10,072/s | 25,419/s | 56,200-64,300/s | +| Reads, Python | 76,466/s | 130,861/s | 77,526/s | 146,368/s | +| The tool writing 120,000 messages to a file | | | 45.5 s | 0.14 s | +| A 200 MB attachment up, the tool | 3.49 s | 1.15 s | 2.84 s | 1.15 s | +| The same down | 1.57 s | 0.59 s | 1.62 s | 0.67 s | + +- **`full`, one client:** both wait for the disk's flush at every push. +- **A command:** the TLS handshake's P-384 signatures and checks, both + ends, cost about 7 ms against the old handshake's X25519; aws-lc's CPU + Jitter Entropy seeding cost 25 ms more per process before it was turned + off (`certificates.md`, "TLS"). +- **The old tool's read** printed a line at a time to the console API. + +### Replication, against the old server (2026-11-14) + +`replication_rate` (`tests/end_to_end.rs`, ignored by default) against +the old `Tests/Bench/Bench-Replication.ps1 -Parts Ramp -Ramp 10x0`: 4 +servers in a Y (a hub sending to 3 leaves, each sending to the hub), 10 +nodes pushing to each as fast as they're answered for 30 s, 200-byte +JSON, the same machine. The old one's pushers are its PureBasic bench +client, the new one's `bakashrot-client` threads in the test's process. + +| | Old, `full` | New, `full` | Old, `normal` | New, `normal` | +|---|---|---|---|---| +| Pushes, all 4 servers | 16,638/s | 16,000-16,300/s | 33,895/s | 35,300-37,500/s | +| Slowest push | 134 ms | 50-57 ms | 854 ms | 420-510 ms | +| Behind when the pushes stop (most of a server) | 9.0 s of pushes | 0 | 11.4 s | 0.3-0.9 s | +| Until every server has everything | 8.8 s | 0.3 s | 14.8 s | 5.3-5.6 s | + +- **Keeping up:** a link checks in again at once after sending; before + it waited `sync_interval` after every check-in, as the old one did, and + pushes went faster (19,300/s `full`, 40,200/s `normal`) while the + leaves fell 7-9 s behind and took 10-20 s to catch up. +- **`batch_size` 1000** (was 100, the old `PeerBatchSize`): `normal` went + from 27,500-31,500/s to 35,300-37,500/s, and from 2-2.5 s to under 1 s + behind. Batches stay about 1 MiB at most. +- **The last few seconds** with `normal` are a link's `sync_interval`: + idle once caught up, it looks again 5 s later. + +## Tests + +`crates/bakashrot-server/tests/end_to_end.rs`, a server on a free port +each: + +- pushes and reads back (ids, data, times, another connection); +- runs of messages (`OldSource/Tests/GetMessages-Test.ps1`, the server's + part): from the start, after an id, with a limit, `more`, the last ones, + nothing yet, unknown topics and nodes, names without case, data that + isn't one line of JSON; +- big messages (`BigMessages-Test.ps1`, one server's part): five of 600 KB + and one of the largest size, one per answer, read back whole; one byte + over refused; a query result over 16 MB refused; +- names: topics by role, nodes; +- attachments (`Attachments-Test.ps1`, one server's part): 100 KB, 5 MB + + 123 bytes, exactly 2 MB, 1 byte, 1 MB, read back and saved; the + messages saying theirs; none, or no such message, refused leaving no + file; another reader, one not allowed; over the server's limit, 0 for + none, empty; the parts stored; +- attachment edges (`AttachmentEdges-Test.ps1`'s, through the client and + a raw connection): a source changed between its SHA-256 and its + sending, one failing half-way (the connection closed, the upload + dropped), a part of the wrong size, a wrong SHA-256, reading from a + part on, something else than a part (closed, dropped); +- queries (`BigMessages-Test.ps1`'s): not allowed, results, a non-JSON row + refused with the hint, errors, writes and two statements refused; +- refusals keeping the connection (not allowed, unknown topic, a bad name + the client catches); +- certificates refused (no known role, with why; another CA's client; a + client trusting another CA; nothing listening); +- revoked certificates (an open connection dropped at its next request, a + new one refused, others going on, a bad CRL refused); +- six connections pushing at once (one id stream per node, none lost or + doubled); +- stopping cleanly: eight nodes pushing flat out, the server stopped + under them: every push answered is there after a restart, the ones + after refused as `ServerError`; +- retention (`Retention-Test.ps1`'s local part): a topic's messages and + their attachment deleted past its age, another topic kept forever, ids + going on, a younger message kept through a pass; +- replication (`Names-Test.ps1`'s replication, `Restart-Test.ps1`, + `AttachmentEdges-Test.ps1`'s corruption): three servers of one CA, a + pushing to b and c. b gets every message by name with its id, time + and data, and the attachment; c, whose `accept_from` hasn't a, gets + nothing; b's own pushes don't go to a. b stopped, a pushes meanwhile + and its copy of an attachment gets damaged; b started again on its + database and address: a links again, sends what b lacks, ids go on; + b refuses the damaged copy, a finds it damaged and asks for it again; +- replication edges (the test as the peer, a raw connection): what + `SyncState` says, ids and last ids kept, a message past its age only + counted, an attachment from the wrong part refused, one cut after its + first part going on from the second (the first read back for the + SHA-256), one not matching refused and asked for from the start, a + certificate whose roles take nothing refused; +- `replication_rate`, ignored by default: the benchmark above (`SYNC`, + `NODES`, `SECONDS`, `BATCH`). + +The old tests' tool parts (`--follow`, the output) are the tools' tests +(`client.md`). diff --git a/docs/storage.md b/docs/storage.md new file mode 100644 index 0000000..d473386 --- /dev/null +++ b/docs/storage.md @@ -0,0 +1,287 @@ +# Storage: schema v9 + +The server's database: one SQLite file. The code is +`crates/bakashrot-storage`; the schema is +`crates/bakashrot-storage/src/schema_v9.sql`, made in one go. Decided in +`../revamp.md`, "Decided" (2026-11-13). + +**Not compatible with v8:** a database of the old server isn't opened +(refused at start, saying so); its data isn't carried over. + +## In short + +- **By name outside, packed integers inside.** The rest of the code (the + server, the tools) only sees topics, nodes, message ids and times, as on + the wire. Inside, a topic and node pair is a *stream*, and a message's + key packs its stream and its id into one integer. Only this crate packs + and unpacks keys; the `messages` view shows plain columns. +- **One B-tree per kind of data:** messages, attachment parts. A push + writes its message's row and nothing else (no index): about 2.3 times + the pushes of v8's layout, 30% less disk (see "Measured"). +- **One writer, many readers** (WAL). Writes go in batches, one + transaction each: a group commit. + +## Streams + +A **stream** is one node's messages in one topic: `logs` written by +`kitchen` is one, `logs` written by `garage` another. Everything works on +them: + +- message ids count per stream, from 1; +- replication compares each stream's `last_id` (`SyncState`'s heads); +- `GetMessages` reads a range of one stream. + +`streams` holds each one's id (1 to 2^20 - 1), its topic and node names +(compared without case), and `last_id`: the highest id it ever had. +Deleting messages leaves `last_id`, so ids never go back. A trigger keeps +it, for pushes and replication alike. + +There are no `topics` or `nodes` tables: a topic's streams are its rows in +`streams`, the names are listed from there (`Reader::topics()`, +`nodes()`), and the config adds the topics it names. + +## Keys + +``` +data.key = stream_id << 43 | message_id + [0][ stream: 20 bits ][ message id: 43 bits ] + +attachment_parts.key = attachment_id << 20 | part + [0][ attachment: 43 bits ][ part: 20 bits ] +``` + +- `data.key` is the table's own key (`INTEGER PRIMARY KEY`): the messages + are stored ordered by stream, then id. A stream's messages sit together; + "after id 100", "the last 10" are ranges of keys, read in order. No + other index is written when a message is stored. +- **Limits:** 1,048,575 streams per database, message ids up to + 2^43 - 1 (8,796,093,022,207) per stream: 278 years at 1,000 messages a + second. `MAX_MESSAGE_ID` (`bakashrot-proto`) is that, so the protocol + can't carry an id a server can't store. Past either, a push is refused + (`TooBig`). +- **Attachment parts** the same way: 2^20 parts of 1 MiB is exactly the + 1 TiB limit, an attachment's parts are a range of keys. +- `data` also has `stream_id`, `message_id` and `is_json` as **virtual + columns**: computed when read, never stored (a test checks the schema + unpacks keys as the code does). + +Why not v8's three columns with an index? A second B-tree to write at every +push, and reads going through the index then to the row. Measured below. + +## Writing + +`Database::writer()` gives the one connection that writes; +`Writer::batch(|batch| ...)` runs a closure in one transaction. Every +operation of a `Batch` is all or nothing on its own (a savepoint), so a +batch goes on after one fails: the server queues pushes and stores them +together, one disk flush for all. + +| Operation | What | +|---|---| +| `push(topic, node, pushed_at, data)` | the next id of its stream, which it returns; the stream is made if new | +| `start_upload(size, sha256)`, `write_part(id, part, data)`, `push_with_attachment(id, ...)`, `cancel_upload(id)` | a push with an attachment: its parts first, then the message with it | +| `replicate(topic, node, messages, max_attachment_size, skip_before)` | a peer's messages, with their ids; ones already here are kept; ones pushed before `skip_before` (past their age here) only counted in `last_id` | +| `write_part`, `finish_replicated(id, matches)` | a replicated attachment's parts, then ready (or started over) | +| `damaged(id)` | a ready attachment found not matching its SHA-256: its parts dropped, asked for again (`replicating`) | +| `delete_before(topic, cutoff, limit)` | retention | +| `purge_attachments(max_parts)` | deleted messages' attachments | +| `Writer::vacuum()` (outside a batch) | the file shrunk to what it holds: the old server's `vacuum` command | +| `Checkpointer::checkpoint()` (its own connection) | the WAL copied into the database, every second, off the writer's way | + +**SHA-256s are the caller's to check:** the server hashes the parts as they +stream by, nothing is read back from the disk. A resumed replicated +attachment's first parts are read back (`Reader::read_part`) to finish its +hash. + +## Reading + +`Database::reader()` gives a connection that reads, as many as needed; they +read while the writer writes. Answers are the protocol's own types: + +| Reader | Gives | How | +|---|---|---| +| `messages(topic, node, after, limit)` | `Messages`: after an id in order, or the last ones; about 1 MiB at most (a bigger message alone), `more` if others follow | a range of keys | +| `topics()`, `nodes()` | the names with messages | `streams` | +| `heads()`, `last_id(topic, node)` | each stream's last id: `SyncState` | `streams` | +| `to_replicate(topic, node, after, limit)` | messages after an id as replication sends them (attachments' SHA-256s), about 1 MiB at most | a range of keys | +| `missing_attachments(limit)` | replicated attachments not all here, from which part | `attachments` (index on states) | +| `attachment(topic, node, id)`, `read_part(id, part)` | an attachment, its parts | the message's key; a part's key | + +A topic and node with no messages read as none, unless the node has none +in any topic: `Error::UnknownName`, as the old server refused unknown +nodes. Whether a topic is known is the server's (the config's topics). + +## Attachments + +One table, a state each: + +| State | Meaning | Next | +|---|---|---| +| `uploading` | a push's attachment, parts coming, no message yet (`message_key` NULL) | all parts and the SHA-256 match: the message is stored and the attachment `ready`, one transaction. Cut short: deleted with its parts (and every one left at start) | +| `replicating` | its message came from a peer with its size and SHA-256; parts come after | asked from part `received / 1 MiB` on; all came and match: `ready`, else started over (also at start, all came but not checked) | +| `ready` | all here, checked | readable | +| `too_big` | bigger than this server's `max_attachment_size` | never asked for; its message is kept | +| `deleting` | its message was deleted (a trigger) | parts deleted in batches, then the row | + +Readers never see a message whose pushed attachment is missing: the +message is only stored with its complete attachment. A replicated message +can be here before its attachment: `Messages` says `ready: false`. + +## Retention + +`delete_before(topic, cutoff, limit)` reads each of the topic's streams from +its oldest message and stops at the first it keeps: only what it deletes is +read, nothing indexes `pushed_at`. So messages go **in id order**: one +stamped earlier than the one before it (a server's clock set back) waits for +that one. `last_id` stays. The parts of deleted messages' attachments go +afterwards, `purge_attachments(max_parts)` a batch at a time. + +## The query surface + +Clients' `Query` runs on `Database::query_runner()`, read-only three ways: +the connection is `query_only`, the statement must be one SQLite says only +reads, and one statement only (more is refused, not ignored). The result is +`{"columns":[...],"rows":[[...]]}`, every value a string or null (blobs in +hex), 10,000 rows and 16 MB at most (`TooBig`). A failing row fails it all, +with SQLite's message: never a partial result. "malformed JSON" (a JSON +function on a row that isn't) gets the old server's hint: add +`is_json = 1` to the WHERE. + +The `messages` view, by name: + +| Column | | +|---|---| +| `topic`, `node` | names | +| `message_id`, `message_data`, `is_json`, `pushed_at`, `pushed_utc` | as in v8 | +| `attachment_size`, `attachment_state` | NULL without one | + +```sql +SELECT * FROM messages WHERE topic = 'logs' AND node = 'kitchen' +SELECT message_data ->> '$.temp' FROM messages WHERE topic = 'sensors' AND is_json = 1 +``` + +- **By topic, or topic and node:** ranges of the table, read in order (a + test checks the plans). +- **Filters on `pushed_at` or `message_id`** read the streams they're in, + whole: a millisecond or two for 10,000 messages per stream, growing with + them (see "Measured"). If that gets slow, a time index is one migration + away ("For later"). +- `browse` / `browse_messages`: v8's, for database tools (set `browse`'s + one row, open the view); no dropdowns any more. + +## The file + +- `PRAGMA application_id` = "BSHT": a BakaShrot database. +- `metadata`: `schema_version` (9), `created_at`, `created_by` (this crate + and its version). +- **Opening** (`Database::open`): an empty file is made a v9 database; a + v9 one is opened; an older one is migrated, a version at a time, each + step one transaction that also sets `schema_version` (none yet); a newer + one, the old server's, or another program's is refused, saying which. +- Every connection: WAL, `synchronous` from the config (`full`: every + commit flushed; `normal`: about once a second), a 5 s busy timeout. No + foreign keys: one writer keeps the tables consistent, `CHECK`s keep the + values valid. +- SQLite is compiled in (`rusqlite`'s `bundled`): the same version + everywhere, no system library. + +## Measured + +Python's `sqlite3` (SQLite 3.50), 5,000,000 small JSON messages pushed to +500 streams (100 topics x 5 nodes) at random, 100 per transaction, WAL, +`synchronous = NORMAL`, 16 MB page cache: + +| | v9 (this) | v9 + a time index | the first draft (v8's layout) | +|---|---|---|---| +| Pushes/s | **23k** | 9-10k | 9k | +| File | **330 MB** | 457 MB | 484 MB | +| Latest 100 of a stream | 0.05 ms | 0.05 ms | 0.19 ms | +| 1000 after an id | 0.53 ms | 0.53 ms | 3.04 ms | +| Retention, 10% of a topic | 5.5 ms | 6.4 ms | 241 ms | +| Query: a node's last hour | 1.65 ms | 0.90 ms | 3.29 ms | +| Query: a topic's last hour | 8.4 ms | 4.7 ms | 16.0 ms | + +- A push dirties its stream's page: with pushes spread over many streams, + each costs about a page written to the WAL. Any index per stream (v8's, + a time index) doubles that, and a bigger cache doesn't help (it's writes, + not reads). +- Bigger batches over fewer streams share pages: the server's group commit + helps most when many pushes come at once. + +### Against the old storage (2026-11-13) + +The same workload on both, each storage layer alone (no network): pushes +over 500 streams picked at random, 100 per transaction, 200-byte JSON; +2000 latest-message reads; 500 reads of 1000 messages after a stream's +middle id; retention of 10% of one topic. The new side is +`compare_with_old` (`tests/storage.rs`, ignored by default: +`PUSHES=1000000 SYNC=normal cargo test --release -p bakashrot-storage -- +--ignored --nocapture`). The old side calls `OldSource`'s writer +(`BakaShrot_Writer_WriteJobs()`, its group commit, PureBasic 5.73, SQLite +3.54.1 from `sqlite3.dll`), from a program built outside `OldSource`. +Same machine, NVMe, one run each. + +| | Old, 1M | New, 1M | Old, 1M `full` | New, 1M `full` | Old, 5M | New, 5M | +|---|---|---|---|---|---|---| +| Pushes/s, first | **25,874** | 13,803 | **19,976** | 13,205 | **19,558** | 12,184 | +| Pushes/s, step 5's writer | 25,874 | **37,332** | 19,976 | **29,952** | 19,558 | **29,363** | +| File | 276 MB | 249 MB | 276 MB | 249 MB | 1,380 MB | 1,239 MB | +| Latest message | 0.013 ms | 0.017 ms | 0.013 ms | 0.017 ms | 0.014 ms | 0.017 ms | +| 1000 after an id | 4.26 ms | **0.43 ms** | 4.28 ms | **0.43 ms** | 4.32 ms | **0.45 ms** | +| Retention, 10% of a topic | 20 ms | **7 ms** | 23 ms | **9 ms** | 98 ms | **8 ms** | + +`normal` unless said. At first, the old writer pushed faster, from code the +new one didn't have, not from the schema; step 5 brought two of them over +(the second row, about 1.5 times the old): + +- **checkpoints off the push path:** `Database::checkpointer()`, every + second on its own connection (the server's thread), the writer only + checkpointing itself past 10,000 pages (`WRITER_CHECKPOINT_PAGES`, + SQLite's default is 1,000): 13.8k to 34.7k pushes/s; +- **no savepoint around a push** (a failed one leaves at most its empty + stream): 37.3k; +- **next ids in memory**, left out: an indexed read of the stream's row per + push, not where the time goes. + +The new layout reads ranges 10 times faster, deletes faster (and keeps +doing so as the database grows), loses less push speed from 1M to 5M (-12% +against -24%), and makes a file 10% smaller with 200-byte messages (30% +with 45-byte ones: its saving is the indexes, a fixed cost per message). + +## Tests + +`crates/bakashrot-storage/tests/storage.rs`, on database files in +`target/`: opening (made, reopened, an empty file), refused databases +(another program's, v8, a newer version, no version), pushes and reads +(ids per stream, names without case, after/latest/limit/more, the 1 MiB +cut), uploads (parts in order and of their size, incomplete refused, a +failed operation not spoiling its batch, cancelled and left-over ones +deleted), replication (own ids, kept ones, attachments to ask for, too big, +started over, resumed), retention (limits, id order, heads kept, ids going +on, attachments purged in batches), vacuum (the file shrinks, ids go on), +the limits (no stream, no id left, the highest key), queries (results, every write refused, failing rows, too +big), the view's plans, and readers with two writers at once. In +`src/lib.rs`: the keys, the schema unpacking them the same, the states. + +## For later + +- **A time index**, if time queries over big streams get slow: a v10 + migration adding an index on `(stream_id, pushed_at)` and joining the + view on it too (measured above: twice the write cost). +- **Interrupting long queries** (a time limit): the server's, with + SQLite's interrupt. +- **Attachments as files** next to the database instead of in it, if their + size calls for it. + +## What changed from v8 + +| v8 | v9 | +|---|---| +| `data(topic_id, node_id, message_id, ...)` + 3 indexes | `data(key, pushed_at, message_data)`, no index | +| `topics`, `nodes` with ids and origins | names in `streams` | +| `node_heads` | `streams.last_id` | +| `attachments` + `blobs` (two sets of states), `blob_chunks` | `attachments` (five states), `attachment_parts` | +| uploads waiting for their message, `UploadTimeout` | uploads inside their push | +| `is_json` stored | computed when read | +| no version in the file | `metadata` with `schema_version`; `application_id` | +| foreign keys declared, not checked | none, `CHECK`s | diff --git a/readme.md b/readme.md index f45a3f7..9da289b 100644 --- a/readme.md +++ b/readme.md @@ -1,48 +1,125 @@ # BakaShrot -A message store with replication, written in PureBasic. +A message store with replication. Servers take messages (usually JSON) per topic and node from authenticated clients, -store them in SQLite, and replicate them to their peers by name. +store them in SQLite, and replicate them to other servers by topic and node name. > [!NOTE] > Meant as an internal tool on trusted machines and networks. ## Features -* Encrypted connections, both ends prove who they are (Ed25519, libsodium) -* Replication between peers, by topic and node names -* Attachments of any size, one per message +* TLS 1.3 connections, both ends proving who they are with certificates from your own CA (`bakashrot-cert`) +* Replication between servers, by topic and node names +* Attachments, one per message, 1 GB by default * Per-topic retention * Read-only SQL queries on the stored messages * Clients: - * A DLL, with PureBasic prototypes - * CLI tools to push, read, query and list - * A Python module over the DLL, without dependencies, as a wheel with the DLLs in it + * A C library (`bakashrot.dll`, `libbakashrot.so`), with a C header and PureBasic prototypes + * A CLI tool to push, read, query and list + * A Python module over the library, without dependencies, as a wheel with the library in it + +See [revamp.md](revamp.md) for why it was rewritten in Rust, what was decided, and the plan. +The PureBasic version it replaced (protocol 6) is in the git history: `OldSource/`, up to commit `68966a8`. ## Building -Requires PureBasic 5.73 or 6.40+ and the submodules. +Requires [rustup](https://rustup.rs) (it installs the pinned toolchain, [rust-toolchain.toml](rust-toolchain.toml), +by itself; on Windows, Visual Studio's C++ tools for the linker) and Python 3.11+ for releases. -* **Development:** `powershell -ExecutionPolicy Bypass -File Build.ps1` (into `Build\`) -* **Release:** `powershell -ExecutionPolicy Bypass -File Release.ps1` (into `Release\`) -* **Docker:** See [Docker/README.md](Docker/README.md) -* **Python:** See [Interactors/Python/README.md](Interactors/Python/README.md) +From the repository's root, on Windows (`powershell -ExecutionPolicy Bypass -File