diff --git a/.gitignore b/.gitignore index 6ab3666..3d5678a 100644 --- a/.gitignore +++ b/.gitignore @@ -5,27 +5,14 @@ # Build Artifacts *.exe *.dll -# ... except the runtime redistributables the old release packages, see OldSource/Libs/redist/README.md -!OldSource/Libs/redist/**/*.dll *.so *.a *.pdb *.lib *.exp -# Build output, holds generated private keys -Build/ - -# Release builds, see Release.ps1 -Release/ - # Python __pycache__/ # Rust (Source/) target/ - -# The examples run their server in their own folder: its database, and -# what their client scripts write -OldSource/Examples/**/*.sqlite* -OldSource/Examples/**/out/ diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index 2ad491a..0000000 --- a/.gitmodules +++ /dev/null @@ -1,3 +0,0 @@ -[submodule "Includes/PB-MessagePack"] - path = OldSource/Includes/PB-MessagePack - url = https://github.com/aziascreations/PB-MessagePack.git diff --git a/CLAUDE.md b/CLAUDE.md index 73793c4..e2ed56f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -5,15 +5,16 @@ 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**. -**Being rewritten in Rust** (since 2026-11-13): +**Rewritten in Rust** (since 2026-11-13): - `revamp.md`: why, what's decided, what's proposed and open, the plan and its status. Read it first. -- `Source/`: the new implementation (`Source/README.md`: layout, commands, - conventions; `Source/docs/`: designs, `protocol.md` first). -- `OldSource/`: the old PureBasic implementation, the reference for the - behaviour to carry over. It has its own `CLAUDE.md` (build, test, traps), - `Notes.md` and `Design/`; its paths are relative to `OldSource/`. +- `Source/`: the implementation (`Source/README.md`: layout, commands, + conventions; `Source/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. ## Toolchain @@ -23,24 +24,19 @@ between peers by name. Clients: a C DLL, CLI tools, a Python module. An (`Source/rust-toolchain.toml`, 1.100.0, MSVC; Visual Studio 18 has the linker). - `Source\check.ps1` runs what CI runs; it must pass before a step is done. -- PureBasic 5.73 and 6.40 for `OldSource/`, see `OldSource/CLAUDE.md`. ## Working rules - **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. -- **`OldSource/` is the reference:** don't change it beyond keeping it - building and passing, unless asked. - **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`). - **Files mix CRLF and LF:** edits must keep each file's line endings - (`Source/` is LF, the docs at the root and in `OldSource/` mostly CRLF). + (`Source/` is LF, the docs at the root mostly CRLF). - **Bash tool heredocs collapse `\\`:** write edit scripts to files, or use the Edit tool. -- **Run exes from a build folder** (`OldSource\Build\`, `Source\target\`): +- **Run exes from a build folder** (`Source\target\`): the antivirus blocks them in temp folders. -- **Generated keys and certificates never go in git** (`Build/`, - `target/`). The one exception: `OldSource/Examples/*/` commit theirs on - purpose (public, example-only, marked so). +- **Generated keys and certificates never go in git** (`target/`). diff --git a/OldSource/Build.ps1 b/OldSource/Build.ps1 deleted file mode 100644 index 557b9fc..0000000 --- a/OldSource/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/OldSource/CLAUDE.md b/OldSource/CLAUDE.md deleted file mode 100644 index 5b460ef..0000000 --- a/OldSource/CLAUDE.md +++ /dev/null @@ -1,121 +0,0 @@ -# BakaShrot, the old PureBasic implementation - start here - -**Frozen since 2026-11-13** as the reference for the Rust rewrite -(`../revamp.md`, `../CLAUDE.md`). Every path below is relative to this -folder, `OldSource/`: run the scripts and compilers from here. - -A message store with replication, in PureBasic: servers take JSON (or any) -messages per topic/node from authenticated clients, store them in SQLite, -and replicate them between peers by name. Clients: a DLL, CLI tools, a -Python module. An **internal tool on trusted machines**: correctness and -operations come before security hardening (`Notes.md`, "Threat model"). - -## Read first - -1. `Notes.md`: "Right now" (what's committed, what's next), where things - stand, "Open items, by importance" (the to-do list), "Testing tips". -2. `Design/`, by topic: `Packets.md` (the protocol, where every file lives, - code conventions), `Attachments.md`, `Cryptography.md`, - `Certificates.md`, `StorageConcurrency.md`, `ReplicationIssues.md`, - `Release.md`, `Suggestions.md`. -3. `git log --oneline` and `git status`: what's committed. Work happens on - branches off `master` (`timestamps-retention` at this writing). - -## Build - -- Dev compiler, PureBasic 5.73: `C:\Program Files\PureBasic_573\Compilers\pbcompiler.exe /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`, `Tests\X509Test.pb` | `Build\` | `/CONSOLE` | -| `Tests\AttachmentEdgeClient.pb` | `Build\AttachmentEdgeClient.exe` | `/CONSOLE /THREAD` | - -- `Release.ps1 [-Force]` builds the release with 6.40 into `Release\` and - smoke-tests it (`-Force` replaces an existing folder of the same name). -- Linux: same sources and flags (`-t`, `-e`, `-so` for the DLL), with - `libsodium-dev`. `Docker/Server/` builds the server image, on the - PureBasic image `git.nibblepoker.lu/packages/purebasic` (6.41, linux3; - needs a `docker login`), see its Dockerfile. - -## Test - -Each suite starts its own servers (`BenchServer.exe`) on fixed ports, in a -fresh folder under `Build\`, and prints PASS/FAIL lines; exit code 0 means -all passed. `powershell -ExecutionPolicy Bypass -File Tests\.ps1`: - -| Suite | Ports | Covers | -|---|---|---| -| `Names-Test.ps1` | 12401-12402 | names/ids, filters, wildcards, replication by name | -| `BigMessages-Test.ps1` | 12403-12404 | 16 MB messages, handshake frame limit, `is_json`, query errors | -| `GetMessages-Test.ps1` | 12405 | runs of messages, `--follow` | -| `Python-Test.ps1` | 12406-12407 | `bakashrot.py` (`check_bakashrot.py`), the wire is encrypted (`wire_check.py`) | -| `Retention-Test.ps1` | 12408-12409 | `pushed_at`, retention, schema upgrade (Python) | -| `Attachments-Test.ps1` | 12410-12411 | attachments through the tools, replication, limits | -| `AttachmentEdges-Test.ps1` | 12413-12414 | raw-protocol edge cases, expiry, resuming, corruption (Python) | -| `Restart-Test.ps1` | 12415-12416 | servers killed mid-traffic and mid-catch-up: nothing acknowledged lost, ids carry on, both catch up (Python pushers) | -| `X509-Test.ps1` | none | X.509 certificates (`X509Test.exe`), both ways with OpenSSL when it's there (Git's) | - -Plus `Build\HandshakeTest.exe` and `Build\CipherTest.exe` (no server), and -the release's smoke test. Speed: `Tests\Bench\Bench-Replication.ps1 -Ramp 10x0 -Parts Ramp` -(push ceiling for 4 servers: ~17,000 msg/s with the default `Synchronous = -FULL`, ~34,000-40,000 with `-Synchronous NORMAL`). After a change, run every -suite: they take a few minutes in all. - -## Traps - -- **Run exes from `Build\`**: the antivirus blocks them in temp folders. -- **`Build\` holds private keys**: git-ignored, never publish it. The one - exception: `Examples/*/` commit their configs, keys included, on purpose - (public, example-only, marked so); don't copy those keys anywhere else. -- **PureBasic is single pass**: constants, structures and procedures must - be declared before use, so include order matters (e.g. `Config.pbi` - includes `Packets.pbi` for its constants). -- **`SetDatabase*()` binds the next statement run on that connection**, not - a specific one: set them right before their `DatabaseUpdate/Query`. -- **Never `Goto` out of a `Select`**: 5.73's ASM backend keeps the value on - the stack, the jump corrupts it (a config error crashed the server with - 0xC0000005). Set the error, leave the `Select`, then jump. Out of - `For`/`ForEach`/`While` loops is fine (checked on both compilers). -- **PureBasic lists aren't safe to walk from several threads** (`ForEach` - moves the shared current element): give each thread its own copy. -- **Files mix CRLF and LF**: edits must keep each file's line endings. -- **PowerShell 5**: JSON passed as an argument loses its double quotes - (tests write it to a file, `@file`), and `@()` can't be passed through - `-File`. -- **Bash tool heredocs collapse `\\`**, and PureBasic uses `\` for fields: - write edit scripts to files, or use the Edit tool. -- **The real server needs a console on Windows** (it stops at once without - input): tests use `BenchServer.exe` and its stop file instead. On Linux - it runs on without one, SIGTERM/SIGINT stop it. - -## Working rules - -- **Commit only when the owner asks**, on a branch, not `master`. -- **Wire changes bump `#BakaShrot_ProtocolVersion`** (`Packets.pbi`, 6 at - this writing); any difference refuses the connection. -- **Schema changes** add a `Server/Storage/db_schema_vN.dbml` (v8 at this - writing) and a migration in `SetupStorageDatabase()` (`Storage.pbi`), - existing databases must keep working. -- **Packets** follow `Design/Packets.md` "Code conventions": one file per - packet in `Commons/Networking/Packets/`, `_Encode` / `_Decode` (and - `_Free` when it holds data), every field validated on decode. -- **Every write goes through the writer** (`Server/Storage/Writer.pbi`, - under its mutex); reads use the thread's own connection. -- **Every `.pb`/`.pbi` starts with a code header** (`;{- Code Header`, - like PB-MessagePack's): name, version (0.0.1 at this writing), tested - compilers. A release bumps the version in all of them; only list a - compiler/platform once every suite passed with it. -- **Docs follow the code**: a finished piece gets a "Done: ... (date)" - section in `Notes.md`, what's left goes to its open items, and the - `Design/` doc of that area is updated with it. diff --git a/OldSource/Client/BakaShrot_Client.pbi b/OldSource/Client/BakaShrot_Client.pbi deleted file mode 100644 index d666be4..0000000 --- a/OldSource/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/OldSource/Client/BakaShrot_Client.pbi.cfg b/OldSource/Client/BakaShrot_Client.pbi.cfg deleted file mode 100644 index e0cc554..0000000 --- a/OldSource/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/OldSource/Client/BakaShrot_Client_Prototypes.pbi b/OldSource/Client/BakaShrot_Client_Prototypes.pbi deleted file mode 100644 index 35b4710..0000000 --- a/OldSource/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/OldSource/Client/BakaShrot_ErrorCodes.pbi b/OldSource/Client/BakaShrot_ErrorCodes.pbi deleted file mode 100644 index 0ec758e..0000000 --- a/OldSource/Client/BakaShrot_ErrorCodes.pbi +++ /dev/null @@ -1,145 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: BakaShrot_ErrorCodes.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64, Linux x64) -; * PureBasic 6.40 C Backend (Windows x64) -; * PureBasic 6.41 (Linux x64) -; * PureBasic 6.41 C Backend (Linux x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; BakaShrot error codes -; -; What BakaShrot_GetLastError() returns after a failed call of the client DLL -; (BakaShrot_Client.pbi), and the code a server sends with each refusal -; (RequestRefused, protocol 6). The Python client has the same numbers in -; bakashrot.ErrorCode. Shipped next to BakaShrot_Client_Prototypes.pbi, -; which includes it. -; -; 0 no error (the last call succeeded) -; 1-99 refused by the server: the connection is still open, see -; BakaShrot_GetRefusalReason() for the details -; 100+ the client's own: the connection, the arguments, the files -; -; What to do about each: -; reconnect, then retry: NotConnected, ConnectFailed, ConnectionLost, -; ProtocolError (the connection is closed) -; retry later: NotReady (an attachment still on its way), -; ServerError (the server's storage failed) -; fix the config: AuthRejected, ServerNotVerified, NotAllowed, -; UnknownName, NoDefaultTopic -; fix the call: InvalidArgument, InvalidRequest, TooBig, -; QueryFailed, FileError -; gone, or not yet there: NotFound -; sent again by itself: DataMismatch (an upload that doesn't match its -; SHA-256: upload it again), AttachmentMismatch (a -; downloaded one that doesn't: read it again) -; -; A push whose answer was lost (ConnectionLost) may still have been stored: -; pushing it again can store it twice, under the next id. Delivery is at -; least once; check the latest message first if a duplicate matters. -; ============================================================================ - -; --- Refused by the server (RequestRefused's Code) ---------------------------- - -; Not allowed to this client: AllowRead / AllowWrite / AllowQuery, its -; PushTopics / ReadTopics, or a request only peers may make. -#BakaShrot_Refused_NotAllowed = 1 -; A topic or node name (or id) this server doesn't know. -#BakaShrot_Refused_UnknownName = 2 -; No such message, attachment or upload. -#BakaShrot_Refused_NotFound = 3 -; The attachment isn't on this server yet (still being replicated). -#BakaShrot_Refused_NotReady = 4 -; A message, attachment or query result over a limit, or an attachment -; bigger than this server keeps. -#BakaShrot_Refused_TooBig = 5 -; A push without a topic, and no DefaultTopic for this client. -#BakaShrot_Refused_NoDefaultTopic = 6 -; A request that doesn't fit: parts out of order, an upload for another -; topic or already attached, a part that doesn't exist... -#BakaShrot_Refused_InvalidRequest = 7 -; An uploaded attachment that doesn't match its SHA-256: dropped. -#BakaShrot_Refused_DataMismatch = 8 -; The SQL of a query failed (its error in the reason). -#BakaShrot_Refused_QueryFailed = 9 -; The server couldn't store or read something: its database failed. -#BakaShrot_Refused_ServerError = 10 - -; The highest a refusal can have, anything above is the client's own. -#BakaShrot_Refused_Max = 99 - -; --- The client's own (BakaShrot_GetLastError()) -------------------------------- - -#BakaShrot_Error_None = 0 -; Not connected: never, or the connection was closed or lost before. -#BakaShrot_Error_NotConnected = 100 -; The server couldn't be reached at that host and port. -#BakaShrot_Error_ConnectFailed = 101 -; The server closed the connection during the handshake: wrong -; ServerPublicKey, a key or node it doesn't allow, or another protocol -; version (its log says which). -#BakaShrot_Error_AuthRejected = 102 -; The server couldn't prove it holds ServerPublicKey's private key. -#BakaShrot_Error_ServerNotVerified = 103 -; The connection broke during a request (it's closed now). A push may -; still have been stored. -#BakaShrot_Error_ConnectionLost = 104 -; The server answered something unexpected or malformed: the connection is -; closed. -#BakaShrot_Error_ProtocolError = 105 -; A bad argument: a ref that's neither a name nor an id, a null pointer, a -; message or attachment over the limits, a setting missing before connecting. -#BakaShrot_Error_InvalidArgument = 106 -; A file couldn't be opened, read or written. -#BakaShrot_Error_FileError = 107 -; A downloaded attachment doesn't match its SHA-256. -#BakaShrot_Error_AttachmentMismatch = 108 -; Already connected: disconnect first. -#BakaShrot_Error_AlreadyConnected = 109 -; Out of memory, or another failure inside the client. -#BakaShrot_Error_Internal = 110 - - -; The name of an error code, as the constants have it ("NotFound"), or -; "Error " for an unknown one. -Procedure.s BakaShrot_ErrorName(Code.l) - Select Code - Case #BakaShrot_Error_None : ProcedureReturn "None" - Case #BakaShrot_Refused_NotAllowed : ProcedureReturn "NotAllowed" - Case #BakaShrot_Refused_UnknownName : ProcedureReturn "UnknownName" - Case #BakaShrot_Refused_NotFound : ProcedureReturn "NotFound" - Case #BakaShrot_Refused_NotReady : ProcedureReturn "NotReady" - Case #BakaShrot_Refused_TooBig : ProcedureReturn "TooBig" - Case #BakaShrot_Refused_NoDefaultTopic : ProcedureReturn "NoDefaultTopic" - Case #BakaShrot_Refused_InvalidRequest : ProcedureReturn "InvalidRequest" - Case #BakaShrot_Refused_DataMismatch : ProcedureReturn "DataMismatch" - Case #BakaShrot_Refused_QueryFailed : ProcedureReturn "QueryFailed" - Case #BakaShrot_Refused_ServerError : ProcedureReturn "ServerError" - Case #BakaShrot_Error_NotConnected : ProcedureReturn "NotConnected" - Case #BakaShrot_Error_ConnectFailed : ProcedureReturn "ConnectFailed" - Case #BakaShrot_Error_AuthRejected : ProcedureReturn "AuthRejected" - Case #BakaShrot_Error_ServerNotVerified : ProcedureReturn "ServerNotVerified" - Case #BakaShrot_Error_ConnectionLost : ProcedureReturn "ConnectionLost" - Case #BakaShrot_Error_ProtocolError : ProcedureReturn "ProtocolError" - Case #BakaShrot_Error_InvalidArgument : ProcedureReturn "InvalidArgument" - Case #BakaShrot_Error_FileError : ProcedureReturn "FileError" - Case #BakaShrot_Error_AttachmentMismatch : ProcedureReturn "AttachmentMismatch" - Case #BakaShrot_Error_AlreadyConnected : ProcedureReturn "AlreadyConnected" - Case #BakaShrot_Error_Internal : ProcedureReturn "Internal" - EndSelect - ProcedureReturn "Error " + Str(Code) -EndProcedure - -; #True for a code a server sends with a refusal (1-99). -Procedure.i BakaShrot_IsRefusalCode(Code.l) - ProcedureReturn Bool(Code >= 1 And Code <= #BakaShrot_Refused_Max) -EndProcedure diff --git a/OldSource/Client/notes.txt b/OldSource/Client/notes.txt deleted file mode 100644 index 8808b4b..0000000 --- a/OldSource/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/OldSource/Commons/Console.pbi b/OldSource/Commons/Console.pbi deleted file mode 100644 index e69de29..0000000 diff --git a/OldSource/Commons/Cryptography/Cipher.pbi b/OldSource/Commons/Cryptography/Cipher.pbi deleted file mode 100644 index 31aeb01..0000000 --- a/OldSource/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/OldSource/Commons/Cryptography/Der.pbi b/OldSource/Commons/Cryptography/Der.pbi deleted file mode 100644 index a92f4a2..0000000 --- a/OldSource/Commons/Cryptography/Der.pbi +++ /dev/null @@ -1,1084 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: Der.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64) -; * PureBasic 6.40 C Backend (Windows x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; BakaShrot DER -; -; Reading and writing ASN.1 DER, the encoding of X.509 certificates, for -; Commons/Cryptography/X509.pbi. Only what certificates use: universal -; tags, context tags [0]-[30], lengths up to #BakaShrot_Der_MaxSize. -; -; Reading is strict, anything that isn't DER is refused: -; - definite lengths only, in their shortest form, -; - tag numbers under 31 (one identifier byte), -; - integers in their shortest form, booleans $00 or $FF, -; - OIDs without padded arcs, times as UTCTime "YYMMDDHHMMSSZ" or -; GeneralizedTime "YYYYMMDDHHMMSSZ" (UTC, whole seconds, real dates), -; - strings without a NUL, PrintableString and IA5String in ASCII. -; A reader never reads past its end: element and contents sizes are checked -; before anything is read. -; -; Reading: a BakaShrot_DerReader walks the elements of a buffer, or of a -; constructed element's contents (BakaShrot_Der_ReaderOf()). Once a read -; fails, the reader stays failed. The elements point into the buffer read, -; which must outlive them. -; -; Writing: a BakaShrot_DerWriter appends elements to a buffer it grows; -; BakaShrot_Der_Begin()/_End() wrap what's written between them in a -; constructed element (SEQUENCE, SET, [n], or an OCTET STRING holding DER). -; Once a write fails the writer stays failed, BakaShrot_Der_Finish() gives -; the result or 0. -; -; Times are seconds since 1970-01-01 00:00:00 UTC, years 0000 to 9999. -; OIDs are dotted text ("1.3.101.112"), arcs of any size up to 140 bits -; (2.25. OIDs have 128-bit arcs). -; -; No globals: any number of threads, each with its own readers and writers. -; ============================================================================ - - -; Universal tags, as their whole identifier byte. -#BakaShrot_Der_Boolean = $01 -#BakaShrot_Der_Integer = $02 -#BakaShrot_Der_BitString = $03 -#BakaShrot_Der_OctetString = $04 -#BakaShrot_Der_Null = $05 -#BakaShrot_Der_Oid = $06 -#BakaShrot_Der_Utf8String = $0C -#BakaShrot_Der_PrintableString = $13 -#BakaShrot_Der_T61String = $14 -#BakaShrot_Der_Ia5String = $16 -#BakaShrot_Der_UtcTime = $17 -#BakaShrot_Der_GeneralizedTime = $18 -#BakaShrot_Der_BmpString = $1E -#BakaShrot_Der_Sequence = $30 -#BakaShrot_Der_Set = $31 - -; Context-specific tags: #BakaShrot_Der_Context | n for a primitive [n] -; (IMPLICIT of a primitive type), #BakaShrot_Der_ContextConstructed | n for -; a constructed one (EXPLICIT, or IMPLICIT of a constructed type). -#BakaShrot_Der_Context = $80 -#BakaShrot_Der_ContextConstructed = $A0 - -; Biggest element read or written, far more than any certificate. -#BakaShrot_Der_MaxSize = $1000000 - -; Most constructed elements a writer keeps open at once. -#BakaShrot_Der_MaxDepth = 16 - -; Longest OID arc, encoded: 20 bytes of 7 bits, 140 bits. -#BakaShrot_Der_MaxArcBytes = 20 - -; Longest OID arc in decimal digits (2^140 has 43; DecimalToArc() refuses -; what still takes more than 20 bytes). -#BakaShrot_Der_MaxArcDigits = 43 - - -; An element read: its whole identifier byte, where it starts, its size -; with its header, and its contents. -Structure BakaShrot_DerElement - Tag.i - *Start - Size.i - *Content - ContentSize.i -EndStructure - - -Structure BakaShrot_DerReader - *Position - *End - Failed.i -EndStructure - - -Structure BakaShrot_DerWriter - *Buffer - Capacity.i - Size.i - ; The constructed elements begun and not ended yet: where their contents - ; start in Buffer, and their tags. - Depth.i - Starts.i[#BakaShrot_Der_MaxDepth] - Tags.i[#BakaShrot_Der_MaxDepth] - Failed.i -EndStructure - - -;- Reading - -; Reads Size bytes at *Data. -Procedure BakaShrot_Der_InitReader(*Reader.BakaShrot_DerReader, *Data, Size.i) - *Reader\Position = *Data - *Reader\End = *Data - *Reader\Failed = #True - If *Data And Size >= 0 - *Reader\End = *Data + Size - *Reader\Failed = #False - EndIf -EndProcedure - - -; Reads the contents of *Element (a SEQUENCE, a SET, an EXPLICIT [n]...). -Procedure BakaShrot_Der_ReaderOf(*Reader.BakaShrot_DerReader, *Element.BakaShrot_DerElement) - BakaShrot_Der_InitReader(*Reader, *Element\Content, *Element\ContentSize) -EndProcedure - - -; #True once everything was read, and nothing failed. -Procedure.i BakaShrot_Der_AtEnd(*Reader.BakaShrot_DerReader) - ProcedureReturn Bool(Not *Reader\Failed And *Reader\Position = *Reader\End) -EndProcedure - - -; The identifier byte of the next element, -1 at the end or once failed. -; Doesn't move: for OPTIONAL and DEFAULT elements. -Procedure.i BakaShrot_Der_PeekTag(*Reader.BakaShrot_DerReader) - If *Reader\Failed Or *Reader\Position >= *Reader\End - ProcedureReturn -1 - EndIf - ProcedureReturn PeekA(*Reader\Position) -EndProcedure - - -; Reads the next element, whatever its tag, into *Element. -; Returns #False, and the reader fails, at the end or if it isn't DER. -Procedure.i BakaShrot_Der_Read(*Reader.BakaShrot_DerReader, *Element.BakaShrot_DerElement) - Protected *P, Left.i, Tag.i, First.i, Count.i, Length.q, i.i - - If *Reader\Failed - ProcedureReturn #False - EndIf - *P = *Reader\Position - Left = *Reader\End - *P - If Left < 2 - Goto ReadFailed - EndIf - - ; High tag numbers (31 and up) take more bytes, certificates never use them. - Tag = PeekA(*P) - If (Tag & $1F) = $1F - Goto ReadFailed - EndIf - - First = PeekA(*P + 1) - If First < $80 - Length = First - Count = 0 - ElseIf First = $80 Or First > $84 - ; Indefinite (BER only), or over 4 bytes of length. - Goto ReadFailed - Else - Count = First & $7F - If Left < 2 + Count - Goto ReadFailed - EndIf - ; The shortest form only: no leading zero, the long form from 128 on. - If PeekA(*P + 2) = 0 - Goto ReadFailed - EndIf - Length = 0 - For i = 0 To Count - 1 - Length = (Length << 8) | PeekA(*P + 2 + i) - Next - If Length < $80 - Goto ReadFailed - EndIf - EndIf - - If Length > #BakaShrot_Der_MaxSize Or Length > Left - 2 - Count - Goto ReadFailed - EndIf - - *Element\Tag = Tag - *Element\Start = *P - *Element\Content = *P + 2 + Count - *Element\ContentSize = Length - *Element\Size = 2 + Count + Length - *Reader\Position = *P + *Element\Size - ProcedureReturn #True - - ReadFailed: - *Reader\Failed = #True - ProcedureReturn #False -EndProcedure - - -; Reads the next element, which must have Tag, into *Element. -; Returns #False, and the reader fails, otherwise. -Procedure.i BakaShrot_Der_Expect(*Reader.BakaShrot_DerReader, Tag.i, *Element.BakaShrot_DerElement) - If Not BakaShrot_Der_Read(*Reader, *Element) - ProcedureReturn #False - EndIf - If *Element\Tag <> Tag - *Reader\Failed = #True - ProcedureReturn #False - EndIf - ProcedureReturn #True -EndProcedure - - -; #True if *Element's contents are a DER integer: at least a byte, and no -; leading byte that only repeats the sign. Any size. -Procedure.i BakaShrot_Der_IsMinimalInteger(*Element.BakaShrot_DerElement) - Protected *C = *Element\Content - - If *Element\ContentSize < 1 - ProcedureReturn #False - EndIf - If *Element\ContentSize > 1 - If (PeekA(*C) = $00 And PeekA(*C + 1) < $80) Or (PeekA(*C) = $FF And PeekA(*C + 1) >= $80) - ProcedureReturn #False - EndIf - EndIf - ProcedureReturn #True -EndProcedure - - -; An integer of up to 8 bytes into *Value\q (signed). -Procedure.i BakaShrot_Der_GetInteger(*Element.BakaShrot_DerElement, *Value.Quad) - Protected *C = *Element\Content, Value.q, i.i - - If *Element\ContentSize > 8 Or Not BakaShrot_Der_IsMinimalInteger(*Element) - ProcedureReturn #False - EndIf - ; The first byte sign-extended, then the others. - Value = PeekB(*C) - For i = 1 To *Element\ContentSize - 1 - Value = (Value << 8) | PeekA(*C + i) - Next - *Value\q = Value - ProcedureReturn #True -EndProcedure - - -; A BOOLEAN into *Value\i, #True or #False. -Procedure.i BakaShrot_Der_GetBoolean(*Element.BakaShrot_DerElement, *Value.Integer) - If *Element\ContentSize <> 1 - ProcedureReturn #False - EndIf - Select PeekA(*Element\Content) - Case $00 - *Value\i = #False - Case $FF - *Value\i = #True - Default - ProcedureReturn #False - EndSelect - ProcedureReturn #True -EndProcedure - - -; A BIT STRING of whole bytes (keys, signatures): *Bytes\i points to them in -; the element, *Size\i is how many. -Procedure.i BakaShrot_Der_GetBitStringBytes(*Element.BakaShrot_DerElement, *Bytes.Integer, *Size.Integer) - If *Element\ContentSize < 1 Or PeekA(*Element\Content) <> 0 - ProcedureReturn #False - EndIf - *Bytes\i = *Element\Content + 1 - *Size\i = *Element\ContentSize - 1 - ProcedureReturn #True -EndProcedure - - -; A BIT STRING of named bits (KeyUsage) as flags: bit n of the string, the -; first one being 0, is 1 << n. Up to 32 bits. -Procedure.i BakaShrot_Der_GetBitFlags(*Element.BakaShrot_DerElement, *Flags.Integer) - Protected *C = *Element\Content, Size.i = *Element\ContentSize, Unused.i, Flags.i, i.i, Bit.i, Byte.i - - If Size < 1 Or Size > 5 - ProcedureReturn #False - EndIf - Unused = PeekA(*C) - If Unused > 7 Or (Size = 1 And Unused <> 0) - ProcedureReturn #False - EndIf - ; The unused bits of the last byte must be zero. - If Size > 1 And (PeekA(*C + Size - 1) & ((1 << Unused) - 1)) <> 0 - ProcedureReturn #False - EndIf - For i = 1 To Size - 1 - Byte = PeekA(*C + i) - For Bit = 0 To 7 - If Byte & ($80 >> Bit) - Flags = Flags | (1 << ((i - 1) * 8 + Bit)) - EndIf - Next - Next - *Flags\i = Flags - ProcedureReturn #True -EndProcedure - - -;- OIDs - -; #True if Text is one or more digits, without a leading zero (but "0"). -Procedure.i BakaShrot_Der_IsDecimal(Text.s) - Protected i.i, c.i - - If Text = "" Or Len(Text) > #BakaShrot_Der_MaxArcDigits Or (Len(Text) > 1 And Left(Text, 1) = "0") - 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 - - -; The arc in Count bytes of base-128 groups at *P, in decimal. -Procedure.s BakaShrot_Der_ArcToDecimal(*P, Count.i) - Protected Dim Digits.a(63) - Protected Length.i = 1, i.i, j.i, Carry.i, x.i, Text.s - - ; Digits(), least significant first: times 128 plus the group, per group. - For i = 0 To Count - 1 - Carry = PeekA(*P + i) & $7F - For j = 0 To Length - 1 - x = Digits(j) * 128 + Carry - Digits(j) = x % 10 - Carry = x / 10 - Next - While Carry - Digits(Length) = Carry % 10 - Carry = Carry / 10 - Length + 1 - Wend - Next - For j = Length - 1 To 0 Step -1 - Text + Chr('0' + Digits(j)) - Next - ProcedureReturn Text -EndProcedure - - -; Writes the arc Decimal (BakaShrot_Der_IsDecimal()) as base-128 groups at -; *Out (#BakaShrot_Der_MaxArcBytes bytes), the high bit on all but the last. -; Returns how many bytes, 0 if it takes more than #BakaShrot_Der_MaxArcBytes. -Procedure.i BakaShrot_Der_DecimalToArc(Decimal.s, *Out) - Protected Dim Groups.a(#BakaShrot_Der_MaxArcBytes) - Protected Count.i, Quotient.s, Remainder.i, Current.i, Digit.i, i.i - - ; Divides by 128 until nothing's left, the remainders least significant first. - Repeat - Quotient = "" - Remainder = 0 - For i = 1 To Len(Decimal) - Current = Remainder * 10 + (Asc(Mid(Decimal, i, 1)) - '0') - Digit = Current / 128 - Remainder = Current % 128 - If Digit > 0 Or Quotient <> "" - Quotient + Chr('0' + Digit) - EndIf - Next - If Count >= #BakaShrot_Der_MaxArcBytes - ProcedureReturn 0 - EndIf - Groups(Count) = Remainder - Count + 1 - Decimal = Quotient - Until Decimal = "" - - For i = 0 To Count - 1 - If i < Count - 1 - PokeA(*Out + i, Groups(Count - 1 - i) | $80) - Else - PokeA(*Out + i, Groups(Count - 1 - i)) - EndIf - Next - ProcedureReturn Count -EndProcedure - - -; Writes the DER contents of the OID Oid ("1.3.101.112") at *Out, OutSize -; bytes. Returns their size, 0 if Oid isn't a valid OID or doesn't fit. -; Valid: two arcs or more, each digits without a leading zero, the first 0, -; 1 or 2, the second under 40 after a 0 or 1. -Procedure.i BakaShrot_Der_EncodeOid(Oid.s, *Out, OutSize.i) - Protected Count.i, i.i, Arc.s, First.q, Second.q, Size.i, Written.i - Protected Dim ArcBytes.a(#BakaShrot_Der_MaxArcBytes) - - Count = CountString(Oid, ".") + 1 - If Count < 2 - ProcedureReturn 0 - EndIf - For i = 1 To Count - If Not BakaShrot_Der_IsDecimal(StringField(Oid, i, ".")) - ProcedureReturn 0 - EndIf - Next - - ; The first two arcs share one: 40 * First + Second, kept within a quad. - First = Val(StringField(Oid, 1, ".")) - Arc = StringField(Oid, 2, ".") - If First > 2 Or Len(Arc) > 17 - ProcedureReturn 0 - EndIf - Second = Val(Arc) - If First < 2 And Second >= 40 - ProcedureReturn 0 - EndIf - - For i = 2 To Count - If i = 2 - Arc = Str(40 * First + Second) - Else - Arc = StringField(Oid, i, ".") - EndIf - Written = BakaShrot_Der_DecimalToArc(Arc, @ArcBytes(0)) - If Written = 0 Or Size + Written > OutSize - ProcedureReturn 0 - EndIf - CopyMemory(@ArcBytes(0), *Out + Size, Written) - Size + Written - Next - ProcedureReturn Size -EndProcedure - - -; #True if Oid is a valid OID's dotted text, see BakaShrot_Der_EncodeOid(). -Procedure.i BakaShrot_Der_IsValidOid(Oid.s) - Protected *Buffer, Size.i - - *Buffer = AllocateMemory((CountString(Oid, ".") + 1) * #BakaShrot_Der_MaxArcBytes) - If Not *Buffer - ProcedureReturn #False - EndIf - Size = BakaShrot_Der_EncodeOid(Oid, *Buffer, MemorySize(*Buffer)) - FreeMemory(*Buffer) - ProcedureReturn Bool(Size > 0) -EndProcedure - - -; An OBJECT IDENTIFIER's dotted text, "" if it isn't a valid one. -Procedure.s BakaShrot_Der_GetOid(*Element.BakaShrot_DerElement) - Protected *C = *Element\Content, Size.i = *Element\ContentSize - Protected i.i, Start.i, Text.s, First.q - - ; Each arc: base-128 groups, the high bit on all of them but the last, - ; no padding group ($80) first. - If Size < 1 Or (PeekA(*C + Size - 1) & $80) <> 0 - ProcedureReturn "" - EndIf - For i = 0 To Size - 1 - If i = Start And PeekA(*C + i) = $80 - ProcedureReturn "" - EndIf - If (PeekA(*C + i) & $80) = 0 - If i - Start + 1 > #BakaShrot_Der_MaxArcBytes - ProcedureReturn "" - EndIf - If Start = 0 - ; The first two arcs, 40 * X + Y: kept within a quad (8 groups). - If i + 1 > 8 - ProcedureReturn "" - EndIf - First = Val(BakaShrot_Der_ArcToDecimal(*C, i + 1)) - If First < 40 - Text = "0." + Str(First) - ElseIf First < 80 - Text = "1." + Str(First - 40) - Else - Text = "2." + Str(First - 80) - EndIf - Else - Text + "." + BakaShrot_Der_ArcToDecimal(*C + Start, i - Start + 1) - EndIf - Start = i + 1 - EndIf - Next - ProcedureReturn Text -EndProcedure - - -;- Times - -; Days since 1970-01-01 of a date of the proleptic Gregorian calendar -; (Howard Hinnant's days_from_civil), any time zone or locale aside. -Procedure.q BakaShrot_Der_DaysFromCivil(Year.q, Month.q, Day.q) - Protected Era.q, YearOfEra.q, DayOfYear.q, DayOfEra.q, M.q - - If Month <= 2 - Year - 1 - M = Month + 9 - Else - M = Month - 3 - EndIf - If Year >= 0 - Era = Year / 400 - Else - Era = (Year - 399) / 400 - EndIf - YearOfEra = Year - Era * 400 - DayOfYear = (153 * M + 2) / 5 + Day - 1 - DayOfEra = YearOfEra * 365 + YearOfEra / 4 - YearOfEra / 100 + DayOfYear - ProcedureReturn Era * 146097 + DayOfEra - 719468 -EndProcedure - - -; The date of Days since 1970-01-01, the other way (civil_from_days). -Procedure BakaShrot_Der_CivilFromDays(Days.q, *Year.Quad, *Month.Quad, *Day.Quad) - Protected Era.q, DayOfEra.q, YearOfEra.q, DayOfYear.q, Mp.q, Year.q, Month.q - - Days + 719468 - If Days >= 0 - Era = Days / 146097 - Else - Era = (Days - 146096) / 146097 - EndIf - DayOfEra = Days - Era * 146097 - YearOfEra = (DayOfEra - DayOfEra / 1460 + DayOfEra / 36524 - DayOfEra / 146096) / 365 - Year = YearOfEra + Era * 400 - DayOfYear = DayOfEra - (365 * YearOfEra + YearOfEra / 4 - YearOfEra / 100) - Mp = (5 * DayOfYear + 2) / 153 - *Day\q = DayOfYear - (153 * Mp + 2) / 5 + 1 - If Mp < 10 - Month = Mp + 3 - Else - Month = Mp - 9 - EndIf - If Month <= 2 - Year + 1 - EndIf - *Year\q = Year - *Month\q = Month -EndProcedure - - -; The number written by Count digits at *P, -1 if one isn't a digit. -Procedure.i BakaShrot_Der_ReadDigits(*P, Count.i) - Protected i.i, c.i, Value.i - - For i = 0 To Count - 1 - c = PeekA(*P + i) - If c < '0' Or c > '9' - ProcedureReturn -1 - EndIf - Value = Value * 10 + (c - '0') - Next - ProcedureReturn Value -EndProcedure - - -; A UTCTime or a GeneralizedTime into *Seconds\q, since 1970 UTC. -; UTCTime's years: 50-99 are 1950-1999, 00-49 are 2000-2049 (RFC 5280). -Procedure.i BakaShrot_Der_GetTime(*Element.BakaShrot_DerElement, *Seconds.Quad) - Protected *C = *Element\Content, Year.q, Month.q, Day.q, Hour.i, Minute.i, Second.i, Days.q - Protected CheckYear.q, CheckMonth.q, CheckDay.q - - If *Element\Tag = #BakaShrot_Der_UtcTime And *Element\ContentSize = 13 - Year = BakaShrot_Der_ReadDigits(*C, 2) - If Year < 0 - ProcedureReturn #False - ElseIf Year >= 50 - Year + 1900 - Else - Year + 2000 - EndIf - *C + 2 - ElseIf *Element\Tag = #BakaShrot_Der_GeneralizedTime And *Element\ContentSize = 15 - Year = BakaShrot_Der_ReadDigits(*C, 4) - If Year < 0 - ProcedureReturn #False - EndIf - *C + 4 - Else - ProcedureReturn #False - EndIf - - Month = BakaShrot_Der_ReadDigits(*C, 2) - Day = BakaShrot_Der_ReadDigits(*C + 2, 2) - Hour = BakaShrot_Der_ReadDigits(*C + 4, 2) - Minute = BakaShrot_Der_ReadDigits(*C + 6, 2) - Second = BakaShrot_Der_ReadDigits(*C + 8, 2) - If PeekA(*C + 10) <> 'Z' Or Month < 1 Or Month > 12 Or Day < 1 Or Day > 31 Or Hour < 0 Or Hour > 23 Or Minute < 0 Or Minute > 59 Or Second < 0 Or Second > 59 - ProcedureReturn #False - EndIf - - ; A real date: no 30th of February. - Days = BakaShrot_Der_DaysFromCivil(Year, Month, Day) - BakaShrot_Der_CivilFromDays(Days, @CheckYear, @CheckMonth, @CheckDay) - If CheckYear <> Year Or CheckMonth <> Month Or CheckDay <> Day - ProcedureReturn #False - EndIf - - *Seconds\q = Days * 86400 + Hour * 3600 + Minute * 60 + Second - ProcedureReturn #True -EndProcedure - - -;- Strings - -; A string's text into *Text\s: UTF8String, PrintableString, IA5String, -; T61String (taken as Latin-1) or BMPString (UTF-16BE). #False for another -; type, a NUL in it, or a PrintableString or IA5String that isn't ASCII. -Procedure.i BakaShrot_Der_GetText(*Element.BakaShrot_DerElement, *Text.String) - Protected *C = *Element\Content, Size.i = *Element\ContentSize, i.i, c.i, Text.s - - Select *Element\Tag - Case #BakaShrot_Der_Utf8String - For i = 0 To Size - 1 - If PeekA(*C + i) = 0 - ProcedureReturn #False - EndIf - Next - If Size > 0 - Text = PeekS(*C, Size, #PB_UTF8 | #PB_ByteLength) - EndIf - - Case #BakaShrot_Der_PrintableString, #BakaShrot_Der_Ia5String - For i = 0 To Size - 1 - c = PeekA(*C + i) - If c = 0 Or c > 127 - ProcedureReturn #False - EndIf - Next - If Size > 0 - Text = PeekS(*C, Size, #PB_Ascii) - EndIf - - Case #BakaShrot_Der_T61String - For i = 0 To Size - 1 - c = PeekA(*C + i) - If c = 0 - ProcedureReturn #False - EndIf - Text + Chr(c) - Next - - Case #BakaShrot_Der_BmpString - If Size % 2 - ProcedureReturn #False - EndIf - For i = 0 To Size - 2 Step 2 - c = (PeekA(*C + i) << 8) | PeekA(*C + i + 1) - If c = 0 - ProcedureReturn #False - EndIf - Text + Chr(c) - Next - - Default - ProcedureReturn #False - EndSelect - - *Text\s = Text - ProcedureReturn #True -EndProcedure - - -; #True if Text may be a PrintableString: A-Z a-z 0-9 space ' ( ) + , - . / : = ? -Procedure.i BakaShrot_Der_IsPrintable(Text.s) - Protected i.i, c.i - - For i = 1 To Len(Text) - c = Asc(Mid(Text, i, 1)) - If Not ((c >= 'a' And c <= 'z') Or (c >= 'A' And c <= 'Z') Or (c >= '0' And c <= '9') Or FindString(" '()+,-./:=?", Chr(c))) - ProcedureReturn #False - EndIf - Next - ProcedureReturn #True -EndProcedure - - -;- Writing - -Procedure BakaShrot_Der_InitWriter(*Writer.BakaShrot_DerWriter) - *Writer\Buffer = 0 - *Writer\Capacity = 0 - *Writer\Size = 0 - *Writer\Depth = 0 - *Writer\Failed = #False -EndProcedure - - -; Frees what *Writer wrote, for when it's abandoned (BakaShrot_Der_Finish() -; does it otherwise). Zeroed first: it may have held a private key. -Procedure BakaShrot_Der_FreeWriter(*Writer.BakaShrot_DerWriter) - If *Writer\Buffer - FillMemory(*Writer\Buffer, *Writer\Capacity, 0) - FreeMemory(*Writer\Buffer) - EndIf - BakaShrot_Der_InitWriter(*Writer) - *Writer\Failed = #True -EndProcedure - - -; Room for Count more bytes. #False, and the writer fails, without memory or -; past #BakaShrot_Der_MaxSize. -Procedure.i BakaShrot_Der_Reserve(*Writer.BakaShrot_DerWriter, Count.i) - Protected Capacity.i, *Buffer - - If *Writer\Failed - ProcedureReturn #False - EndIf - If Count < 0 Or *Writer\Size + Count > #BakaShrot_Der_MaxSize + 64 - *Writer\Failed = #True - ProcedureReturn #False - EndIf - If *Writer\Size + Count <= *Writer\Capacity - ProcedureReturn #True - EndIf - - Capacity = *Writer\Capacity * 2 - If Capacity < 256 - Capacity = 256 - EndIf - While Capacity < *Writer\Size + Count - Capacity = Capacity * 2 - Wend - If *Writer\Buffer - *Buffer = ReAllocateMemory(*Writer\Buffer, Capacity) - Else - *Buffer = AllocateMemory(Capacity) - EndIf - If Not *Buffer - *Writer\Failed = #True - ProcedureReturn #False - EndIf - *Writer\Buffer = *Buffer - *Writer\Capacity = Capacity - ProcedureReturn #True -EndProcedure - - -; The size of the header (tag and length) of Length bytes of contents. -Procedure.i BakaShrot_Der_HeaderSize(Length.i) - If Length < $80 - ProcedureReturn 2 - ElseIf Length <= $FF - ProcedureReturn 3 - ElseIf Length <= $FFFF - ProcedureReturn 4 - ElseIf Length <= $FFFFFF - ProcedureReturn 5 - EndIf - ProcedureReturn 6 -EndProcedure - - -; Writes the header of Tag with Length bytes of contents at *P. -Procedure BakaShrot_Der_PokeHeader(*P, Tag.i, Length.i) - Protected Count.i = BakaShrot_Der_HeaderSize(Length) - 2, i.i - - PokeA(*P, Tag) - If Count = 0 - PokeA(*P + 1, Length) - Else - PokeA(*P + 1, $80 | Count) - For i = 0 To Count - 1 - PokeA(*P + 2 + i, (Length >> ((Count - 1 - i) * 8)) & $FF) - Next - EndIf -EndProcedure - - -; Writes an element: Tag, and Size bytes of contents from *Content. -Procedure.i BakaShrot_Der_WriteElement(*Writer.BakaShrot_DerWriter, Tag.i, *Content, Size.i) - Protected HeaderSize.i = BakaShrot_Der_HeaderSize(Size) - - If Size < 0 Or (Size > 0 And Not *Content) Or Not BakaShrot_Der_Reserve(*Writer, HeaderSize + Size) - *Writer\Failed = #True - ProcedureReturn #False - EndIf - BakaShrot_Der_PokeHeader(*Writer\Buffer + *Writer\Size, Tag, Size) - If Size > 0 - CopyMemory(*Content, *Writer\Buffer + *Writer\Size + HeaderSize, Size) - EndIf - *Writer\Size + HeaderSize + Size - ProcedureReturn #True -EndProcedure - - -; Writes Size bytes of DER as they are (an element encoded elsewhere). -Procedure.i BakaShrot_Der_WriteRaw(*Writer.BakaShrot_DerWriter, *Data, Size.i) - If Size < 1 Or Not *Data Or Not BakaShrot_Der_Reserve(*Writer, Size) - *Writer\Failed = #True - ProcedureReturn #False - EndIf - CopyMemory(*Data, *Writer\Buffer + *Writer\Size, Size) - *Writer\Size + Size - ProcedureReturn #True -EndProcedure - - -; Begins a constructed element with Tag: what's written until its -; BakaShrot_Der_End() is its contents. -Procedure.i BakaShrot_Der_Begin(*Writer.BakaShrot_DerWriter, Tag.i) - If *Writer\Failed Or *Writer\Depth >= #BakaShrot_Der_MaxDepth - *Writer\Failed = #True - ProcedureReturn #False - EndIf - *Writer\Starts[*Writer\Depth] = *Writer\Size - *Writer\Tags[*Writer\Depth] = Tag - *Writer\Depth + 1 - ProcedureReturn #True -EndProcedure - - -; Ends the element begun last: moves its contents to fit its header before. -Procedure.i BakaShrot_Der_End(*Writer.BakaShrot_DerWriter) - Protected Start.i, Length.i, HeaderSize.i - - If *Writer\Failed Or *Writer\Depth = 0 - *Writer\Failed = #True - ProcedureReturn #False - EndIf - *Writer\Depth - 1 - Start = *Writer\Starts[*Writer\Depth] - Length = *Writer\Size - Start - HeaderSize = BakaShrot_Der_HeaderSize(Length) - If Not BakaShrot_Der_Reserve(*Writer, HeaderSize) - ProcedureReturn #False - EndIf - If Length > 0 - MoveMemory(*Writer\Buffer + Start, *Writer\Buffer + Start + HeaderSize, Length) - EndIf - BakaShrot_Der_PokeHeader(*Writer\Buffer + Start, *Writer\Tags[*Writer\Depth], Length) - *Writer\Size + HeaderSize - ProcedureReturn #True -EndProcedure - - -; What *Writer wrote, in a new buffer (free it with FreeMemory), its size in -; *OutSize\i. 0 if a write failed or an element wasn't ended. -; The writer is freed either way. -Procedure.i BakaShrot_Der_Finish(*Writer.BakaShrot_DerWriter, *OutSize.Integer) - Protected *Result = 0 - - If Not *Writer\Failed And *Writer\Depth = 0 And *Writer\Size > 0 - *Result = AllocateMemory(*Writer\Size) - If *Result - CopyMemory(*Writer\Buffer, *Result, *Writer\Size) - *OutSize\i = *Writer\Size - EndIf - EndIf - BakaShrot_Der_FreeWriter(*Writer) - ProcedureReturn *Result -EndProcedure - - -; An INTEGER, in its shortest form. -Procedure.i BakaShrot_Der_WriteInteger(*Writer.BakaShrot_DerWriter, Value.q) - Protected Dim Bytes.a(7) - Protected i.i, Start.i - - For i = 0 To 7 - Bytes(i) = (Value >> ((7 - i) * 8)) & $FF - Next - ; Drops the leading bytes that only repeat the sign. - While Start < 7 And ((Bytes(Start) = $00 And Bytes(Start + 1) < $80) Or (Bytes(Start) = $FF And Bytes(Start + 1) >= $80)) - Start + 1 - Wend - ProcedureReturn BakaShrot_Der_WriteElement(*Writer, #BakaShrot_Der_Integer, @Bytes(Start), 8 - Start) -EndProcedure - - -; An INTEGER of Size unsigned big-endian bytes at *Bytes, any size (a -; serial number): leading zeros dropped, a zero added if the first bit is set. -Procedure.i BakaShrot_Der_WriteUnsigned(*Writer.BakaShrot_DerWriter, *Bytes, Size.i) - Protected *Content, Start.i, Length.i, Result.i - - While Start < Size And PeekA(*Bytes + Start) = 0 - Start + 1 - Wend - *Content = AllocateMemory(Size - Start + 1) - If Not *Content - *Writer\Failed = #True - ProcedureReturn #False - EndIf - If Start = Size - Length = 1 - ElseIf PeekA(*Bytes + Start) >= $80 - CopyMemory(*Bytes + Start, *Content + 1, Size - Start) - Length = Size - Start + 1 - Else - CopyMemory(*Bytes + Start, *Content, Size - Start) - Length = Size - Start - EndIf - Result = BakaShrot_Der_WriteElement(*Writer, #BakaShrot_Der_Integer, *Content, Length) - FreeMemory(*Content) - ProcedureReturn Result -EndProcedure - - -Procedure.i BakaShrot_Der_WriteBoolean(*Writer.BakaShrot_DerWriter, Value.i) - Protected Byte.a = $00 - - If Value - Byte = $FF - EndIf - ProcedureReturn BakaShrot_Der_WriteElement(*Writer, #BakaShrot_Der_Boolean, @Byte, 1) -EndProcedure - - -Procedure.i BakaShrot_Der_WriteNull(*Writer.BakaShrot_DerWriter) - ProcedureReturn BakaShrot_Der_WriteElement(*Writer, #BakaShrot_Der_Null, 0, 0) -EndProcedure - - -; An OBJECT IDENTIFIER from its dotted text. Fails if it isn't valid. -Procedure.i BakaShrot_Der_WriteOid(*Writer.BakaShrot_DerWriter, Oid.s) - Protected *Buffer, Size.i, Result.i - - *Buffer = AllocateMemory((CountString(Oid, ".") + 1) * #BakaShrot_Der_MaxArcBytes) - If Not *Buffer - *Writer\Failed = #True - ProcedureReturn #False - EndIf - Size = BakaShrot_Der_EncodeOid(Oid, *Buffer, MemorySize(*Buffer)) - If Size > 0 - Result = BakaShrot_Der_WriteElement(*Writer, #BakaShrot_Der_Oid, *Buffer, Size) - Else - *Writer\Failed = #True - EndIf - FreeMemory(*Buffer) - ProcedureReturn Result -EndProcedure - - -Procedure.i BakaShrot_Der_WriteOctetString(*Writer.BakaShrot_DerWriter, *Bytes, Size.i) - ProcedureReturn BakaShrot_Der_WriteElement(*Writer, #BakaShrot_Der_OctetString, *Bytes, Size) -EndProcedure - - -; A BIT STRING of Size whole bytes (a key, a signature). -Procedure.i BakaShrot_Der_WriteBitStringBytes(*Writer.BakaShrot_DerWriter, *Bytes, Size.i) - Protected *Content, Result.i - - *Content = AllocateMemory(Size + 1) - If Not *Content - *Writer\Failed = #True - ProcedureReturn #False - EndIf - If Size > 0 - CopyMemory(*Bytes, *Content + 1, Size) - EndIf - Result = BakaShrot_Der_WriteElement(*Writer, #BakaShrot_Der_BitString, *Content, Size + 1) - FreeMemory(*Content) - ProcedureReturn Result -EndProcedure - - -; A BIT STRING of named bits from flags (BakaShrot_Der_GetBitFlags()), up -; to 32 bits, without trailing zero bits as DER wants. -Procedure.i BakaShrot_Der_WriteBitFlags(*Writer.BakaShrot_DerWriter, Flags.i) - Protected Dim Content.a(4) - Protected Highest.i = -1, Bit.i, Count.i - - Flags = Flags & $FFFFFFFF - For Bit = 0 To 31 - If Flags & (1 << Bit) - Highest = Bit - Content(1 + Bit / 8) = Content(1 + Bit / 8) | ($80 >> (Bit % 8)) - EndIf - Next - If Highest < 0 - ProcedureReturn BakaShrot_Der_WriteElement(*Writer, #BakaShrot_Der_BitString, @Content(0), 1) - EndIf - Count = Highest / 8 + 1 - Content(0) = 7 - (Highest % 8) - ProcedureReturn BakaShrot_Der_WriteElement(*Writer, #BakaShrot_Der_BitString, @Content(0), Count + 1) -EndProcedure - - -; A string of type Tag: #BakaShrot_Der_Utf8String, or -; #BakaShrot_Der_PrintableString / #BakaShrot_Der_Ia5String (fails if Text -; doesn't fit them). Fails on a NUL. -Procedure.i BakaShrot_Der_WriteText(*Writer.BakaShrot_DerWriter, Tag.i, Text.s) - Protected *Buffer, Size.i, Result.i, i.i - - If FindString(Text, Chr(0)) - *Writer\Failed = #True - ProcedureReturn #False - EndIf - Select Tag - Case #BakaShrot_Der_Utf8String - Size = StringByteLength(Text, #PB_UTF8) - *Buffer = AllocateMemory(Size + 1) - If *Buffer - PokeS(*Buffer, Text, -1, #PB_UTF8) - EndIf - - Case #BakaShrot_Der_PrintableString, #BakaShrot_Der_Ia5String - For i = 1 To Len(Text) - If Asc(Mid(Text, i, 1)) > 127 - *Writer\Failed = #True - EndIf - Next - If Tag = #BakaShrot_Der_PrintableString And Not BakaShrot_Der_IsPrintable(Text) - *Writer\Failed = #True - EndIf - Size = Len(Text) - *Buffer = AllocateMemory(Size + 1) - If *Buffer - PokeS(*Buffer, Text, -1, #PB_Ascii) - EndIf - - Default - *Writer\Failed = #True - EndSelect - - If *Buffer And Not *Writer\Failed - Result = BakaShrot_Der_WriteElement(*Writer, Tag, *Buffer, Size) - Else - *Writer\Failed = #True - EndIf - If *Buffer - FreeMemory(*Buffer) - EndIf - ProcedureReturn Result -EndProcedure - - -; A time, Seconds since 1970 UTC: a UTCTime from 1950 to 2049, a -; GeneralizedTime otherwise (RFC 5280), years 0000 to 9999. -Procedure.i BakaShrot_Der_WriteTime(*Writer.BakaShrot_DerWriter, Seconds.q) - Protected Days.q, Rest.q, Year.q, Month.q, Day.q, Text.s, Tag.i, *Buffer, Result.i - - Days = Seconds / 86400 - Rest = Seconds % 86400 - If Rest < 0 - Days - 1 - Rest + 86400 - EndIf - BakaShrot_Der_CivilFromDays(Days, @Year, @Month, @Day) - If Year < 0 Or Year > 9999 - *Writer\Failed = #True - ProcedureReturn #False - EndIf - - Text = RSet(Str(Month), 2, "0") + RSet(Str(Day), 2, "0") + RSet(Str(Rest / 3600), 2, "0") + RSet(Str((Rest / 60) % 60), 2, "0") + RSet(Str(Rest % 60), 2, "0") + "Z" - If Year >= 1950 And Year <= 2049 - Tag = #BakaShrot_Der_UtcTime - Text = RSet(Str(Year % 100), 2, "0") + Text - Else - Tag = #BakaShrot_Der_GeneralizedTime - Text = RSet(Str(Year), 4, "0") + Text - EndIf - - *Buffer = AllocateMemory(Len(Text) + 1) - If Not *Buffer - *Writer\Failed = #True - ProcedureReturn #False - EndIf - PokeS(*Buffer, Text, -1, #PB_Ascii) - Result = BakaShrot_Der_WriteElement(*Writer, Tag, *Buffer, Len(Text)) - FreeMemory(*Buffer) - ProcedureReturn Result -EndProcedure diff --git a/OldSource/Commons/Cryptography/Libsodium.pbi b/OldSource/Commons/Cryptography/Libsodium.pbi deleted file mode 100644 index 5d2ba03..0000000 --- a/OldSource/Commons/Cryptography/Libsodium.pbi +++ /dev/null @@ -1,345 +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) - - ; SHA-256 of DataLength bytes at *Data in one go, the 32-byte hash into - ; *Hash. Certificates' fingerprints and key ids (X509.pbi). - crypto_hash_sha256.l(*Hash, *Data, DataLength.q) - - ; Fills *Buffer with Size bytes from the OS's secure generator. - ; Certificates' serial numbers. - randombytes_buf(*Buffer, Size.i) - - ; The Ed25519 key pair of a 32-byte seed, which is what PKCS#8 private - ; key files hold, and the seed of a 64-byte private key. Both return 0. - crypto_sign_seed_keypair.l(*PublicKey, *PrivateKey, *Seed) - crypto_sign_ed25519_sk_to_seed.l(*Seed, *PrivateKey) - - ; Base64 (Variant #BakaShrot_Base64_Original for PEM), constant-time. - ; _encoded_len() is the size *Base64 needs, terminator included. - ; bin2base64 writes a terminated ASCII string, returns *Base64. - ; base642bin skips the characters of the ASCII string *Ignore (" \r\n"), - ; and returns -1 if anything else isn't Base64 or *Binary is too small - ; (*End = 0: all of it must decode). The size it wrote goes in *BinaryLength. - sodium_base64_encoded_len.i(BinaryLength.i, Variant.l) - sodium_bin2base64.i(*Base64, MaxLength.i, *Binary, BinaryLength.i, Variant.l) - sodium_base642bin.l(*Binary, MaxLength.i, *Base64, Base64Length.i, *Ignore, *BinaryLength, *End, Variant.l) - - ; Hex, lowercase, constant-time; same conventions as Base64 above. - sodium_bin2hex.i(*Hex, MaxLength.i, *Binary, BinaryLength.i) - sodium_hex2bin.l(*Binary, MaxLength.i, *Hex, HexLength.i, *Ignore, *BinaryLength, *End) - -EndImport - -; sodium_base64_VARIANT_ORIGINAL: the standard alphabet, with padding. -#BakaShrot_Base64_Original = 1 - - -; Must be called once at startup, before GenerateKeyPair/EncodeData/DecodeData. -; Returns #False if libsodium could not initialize - treat that as fatal, -; there is no safe fallback to running without it. -Procedure.i InitCryptography() - ProcedureReturn Bool(sodium_init() >= 0) -EndProcedure - - -; Generates a new Ed25519 keypair for provisioning a node. -; *PublicKey must point to #BakaShrot_Ed25519_PublicKeySize bytes, -; *PrivateKey to #BakaShrot_Ed25519_PrivateKeySize bytes. -Procedure GenerateKeyPair(*PublicKey, *PrivateKey) - crypto_sign_keypair(*PublicKey, *PrivateKey) -EndProcedure - - -; Fills *PublicKey (#BakaShrot_Ed25519_PublicKeySize bytes) with the public -; key matching *PrivateKey (#BakaShrot_Ed25519_PrivateKeySize bytes), so a -; node only needs its private key in its config. -Procedure GetPublicKeyFromPrivateKey(*PrivateKey, *PublicKey) - crypto_sign_ed25519_sk_to_pk(*PublicKey, *PrivateKey) -EndProcedure - - -; Signs *Data (DataLength bytes) with *PrivateKey (this node's own private -; key, #BakaShrot_Ed25519_PrivateKeySize bytes). -; Writes the signature to *Signature, which must point to -; #BakaShrot_Ed25519_SignatureSize bytes. *Data itself is left untouched. -Procedure.i EncodeData(*Data, DataLength.i, *PrivateKey, *Signature) - Protected SignatureLength.q - ProcedureReturn Bool(crypto_sign_detached(*Signature, @SignatureLength, *Data, DataLength, *PrivateKey) = 0) -EndProcedure - - -; Verifies that *Signature (#BakaShrot_Ed25519_SignatureSize bytes) is a -; valid signature of *Data (DataLength bytes), made by the holder of the -; private key matching *PublicKey (the claimed sender's public key, from -; BakaShrot_PeerConfig\PublicKey). -; Returns #True only if the signature checks out. On #False, reject the -; packet outright - do not process it, do not fall back to trusting it. -Procedure.i DecodeData(*Data, DataLength.i, *PublicKey, *Signature) - ProcedureReturn Bool(crypto_sign_verify_detached(*Signature, *Data, DataLength, *PublicKey) = 0) -EndProcedure - - -; SHA-256 of data given a piece at a time (an attachment's parts): Start, Add -; each piece, then Finish writes the 32-byte hash. -#BakaShrot_Sha256_HashSize = 32 - -Structure BakaShrot_Sha256 - ; crypto_hash_sha256_state is 104 bytes, checked by Start. - State.a[128] -EndStructure - -; Returns #False if libsodium's state doesn't fit (a libsodium change). -Procedure.i BakaShrot_Sha256_Start(*Hash.BakaShrot_Sha256) - If crypto_hash_sha256_statebytes() > SizeOf(BakaShrot_Sha256) - ProcedureReturn #False - EndIf - ProcedureReturn Bool(crypto_hash_sha256_init(*Hash) = 0) -EndProcedure - -Procedure BakaShrot_Sha256_Add(*Hash.BakaShrot_Sha256, *Data, Size.i) - If Size > 0 - crypto_hash_sha256_update(*Hash, *Data, Size) - EndIf -EndProcedure - -Procedure BakaShrot_Sha256_Finish(*Hash.BakaShrot_Sha256, *Out) - crypto_hash_sha256_final(*Hash, *Out) -EndProcedure - - -; Encodes KeySize raw bytes at *Key as a Base64 string, for storing a key in -; the ini file (PrivateKey / PublicKey fields in Config.pbi). -Procedure.s EncodeKeyToString(*Key, KeySize.i) - ProcedureReturn Base64Encoder(*Key, KeySize) -EndProcedure - - -; Decodes KeyString back into KeySize raw bytes at *Key. -; Returns #False (and leaves *Key untouched) if KeyString is not valid -; Base64 or does not decode to exactly KeySize bytes - a malformed or -; truncated key in the config file must never be silently accepted as one -; that's merely different. -Procedure.i DecodeKeyFromString(KeyString.s, *Key, KeySize.i) - ; PureBasic's own docs warn the output buffer must have some slack over - ; the exact decoded size or the decoder can overflow it - at least 25% - ; extra and never under 64 bytes, hence the margin below. - Protected *Buffer, BufferSize.i, DecodedSize.i - - BufferSize = (KeySize * 5) / 4 + 64 - *Buffer = AllocateMemory(BufferSize) - DecodedSize = Base64Decoder(KeyString, *Buffer, BufferSize) - If DecodedSize = KeySize - CopyMemory(*Buffer, *Key, KeySize) - EndIf - FreeMemory(*Buffer) - - ProcedureReturn Bool(DecodedSize = KeySize) -EndProcedure - - -; Usage example. Only compiled when this file is run directly (F5 in the -; IDE), not when it's included as a module by the rest of the project. -CompilerIf #PB_Compiler_IsMainFile - - If Not InitCryptography() - Debug "Failed to initialize libsodium." - Else - Define *PublicKey = AllocateMemory(#BakaShrot_Ed25519_PublicKeySize) - Define *PrivateKey = AllocateMemory(#BakaShrot_Ed25519_PrivateKeySize) - Define *Signature = AllocateMemory(#BakaShrot_Ed25519_SignatureSize) - Define Message.s = ~"{\"messageData\": {\"MsgType\": \"hello\"}}" - Define MessageLength = StringByteLength(Message, #PB_Ascii) - Define *MessageBytes = AllocateMemory(MessageLength) - - PokeS(*MessageBytes, Message, -1, #PB_Ascii) - - GenerateKeyPair(*PublicKey, *PrivateKey) - Debug "PublicKey: " + EncodeKeyToString(*PublicKey, #BakaShrot_Ed25519_PublicKeySize) - Debug "PrivateKey: " + EncodeKeyToString(*PrivateKey, #BakaShrot_Ed25519_PrivateKeySize) - - If EncodeData(*MessageBytes, MessageLength, *PrivateKey, *Signature) - Debug "Signed ok. Signature: " + EncodeKeyToString(*Signature, #BakaShrot_Ed25519_SignatureSize) - - If DecodeData(*MessageBytes, MessageLength, *PublicKey, *Signature) - Debug "Verified ok, as expected." - Else - Debug "FAILED to verify a genuine signature - something is broken." - EndIf - - ; Tamper with one byte and make sure verification then rejects it. - PokeB(*MessageBytes, PeekB(*MessageBytes) ! 1) - If DecodeData(*MessageBytes, MessageLength, *PublicKey, *Signature) - Debug "FAILED: tampered data was accepted as genuine." - Else - Debug "Tampered data correctly rejected." - EndIf - Else - Debug "Failed to sign data." - EndIf - - FreeMemory(*PublicKey) - FreeMemory(*PrivateKey) - FreeMemory(*Signature) - FreeMemory(*MessageBytes) - EndIf - -CompilerEndIf diff --git a/OldSource/Commons/Cryptography/Session.pbi b/OldSource/Commons/Cryptography/Session.pbi deleted file mode 100644 index 8041c97..0000000 --- a/OldSource/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/OldSource/Commons/Cryptography/X509.pbi b/OldSource/Commons/Cryptography/X509.pbi deleted file mode 100644 index f509c06..0000000 --- a/OldSource/Commons/Cryptography/X509.pbi +++ /dev/null @@ -1,1712 +0,0 @@ -;{- Code Header -; ==- Basic Info -================================ -; Name: X509.pbi -; Version: 0.0.1 -; Author: Herwin Bozet (NibblePoker) -; -; ==- Compatibility -============================= -; Tested compiler versions: -; * PureBasic 5.73 LTS (Windows x64) -; * PureBasic 6.40 C Backend (Windows x64) -; -; ==- Links -===================================== -; GitHub: https://github.com/aziascreations/BakaShrot -;} - -; ============================================================================ -; BakaShrot X.509 certificates -; -; Reading, issuing and checking X.509 v3 certificates (RFC 5280) with -; Ed25519 keys (RFC 8410), the same identity keys as the rest of BakaShrot. -; The same code on Windows and Linux: DER is read and written by Der.pbi, -; every bit of cryptography is libsodium's (Libsodium.pbi): signatures, -; SHA-256, random serial numbers, Base64 and hex. -; Not the OS's certificate APIs: Windows' CryptoAPI can't check Ed25519 -; certificates, and OpenSSL would be another library to ship. The -; certificates are standard all the same: OpenSSL reads and checks them, -; and they're checked against it (Tests/X509-Test.ps1). -; -; Reading: BakaShrot_X509_Parse() (DER), _ParsePem(), _Load() (a file, PEM -; or DER) give a BakaShrot_X509Certificate, freed with BakaShrot_X509_Free(). -; Any certificate is read (RSA, ECDSA...), its fields and extensions are -; there, but only Ed25519 ones can be checked or issue others. -; -; Issuing: fill a BakaShrot_X509Template (subject, validity, the subject's -; public key, CA or not, key usage, custom extensions), then -; BakaShrot_X509_Issue() with the issuer's certificate and private key, or -; none for a self-signed one. BakaShrot_X509_ClearTemplate() once done. -; -; Checking: BakaShrot_X509_CheckIssuedBy() for one link, _VerifyChain() -; from a leaf up to a trusted root, _CheckSignature(), _CheckValidity(). -; Each returns a #BakaShrot_X509_* code, #BakaShrot_X509_Ok (0) if it -; holds; BakaShrot_X509_ErrorName() names it. -; -; Custom fields are extensions under #BakaShrot_Oid_Extensions: -; BakaShrot_X509_AddTextExtension() / _AddIntegerExtension() / -; _AddExtension() (any DER) on a template, BakaShrot_X509_GetExtensionText() -; / _GetExtensionInteger() / _FindExtension() on a certificate. Critical -; ones a reader doesn't know make the certificate refused, unless the -; caller says it handles them (the Handled argument of the checks). -; -; Times are seconds since 1970-01-01 00:00:00 UTC (BakaShrot_X509_Now()). -; Hex is lowercase, without separators. -; -; Threads: no globals. A parsed certificate is only read once parsed, its -; names and extensions are arrays, not lists: any number of threads may -; read and check one at once (the server's CA, say). -; ============================================================================ - -XIncludeFile "Libsodium.pbi" -XIncludeFile "Der.pbi" - - -;- OIDs - -#BakaShrot_Oid_Ed25519 = "1.3.101.112" - -; Name attributes. BakaShrot_X509_NameAdd() also takes their short names. -#BakaShrot_Oid_CommonName = "2.5.4.3" -#BakaShrot_Oid_SerialNumber = "2.5.4.5" -#BakaShrot_Oid_Country = "2.5.4.6" -#BakaShrot_Oid_Locality = "2.5.4.7" -#BakaShrot_Oid_State = "2.5.4.8" -#BakaShrot_Oid_Organization = "2.5.4.10" -#BakaShrot_Oid_OrganizationalUnit = "2.5.4.11" -#BakaShrot_Oid_EmailAddress = "1.2.840.113549.1.9.1" -#BakaShrot_Oid_DomainComponent = "0.9.2342.19200300.100.1.25" -#BakaShrot_Oid_UserId = "0.9.2342.19200300.100.1.1" - -; The extensions this file reads and writes itself. -#BakaShrot_Oid_SubjectKeyId = "2.5.29.14" -#BakaShrot_Oid_KeyUsage = "2.5.29.15" -#BakaShrot_Oid_BasicConstraints = "2.5.29.19" -#BakaShrot_Oid_AuthorityKeyId = "2.5.29.35" - -; BakaShrot's own OID arc: a UUID OID (2.25, ITU-T X.667 / RFC 4122), which -; needs no registration. Made 2026-11-13 from the random UUID -; ae8e863a-dae2-47b2-a285-751106c98f65. -#BakaShrot_Oid_Arc = "2.25.232025699926348910519219903487382490981" - -; BakaShrot's custom certificate extensions: #BakaShrot_Oid_Extensions + -; ".", numbered as they're defined, a number never reused. None yet. -; (Tests/X509Test.pb uses .9000 and up.) -#BakaShrot_Oid_Extensions = #BakaShrot_Oid_Arc + ".1" - - -;- Key usage - -; KeyUsage bits as flags (bit n of the extension's BIT STRING is 1 << n). -#BakaShrot_X509_KeyUsage_DigitalSignature = 1 << 0 -#BakaShrot_X509_KeyUsage_NonRepudiation = 1 << 1 -#BakaShrot_X509_KeyUsage_KeyEncipherment = 1 << 2 -#BakaShrot_X509_KeyUsage_DataEncipherment = 1 << 3 -#BakaShrot_X509_KeyUsage_KeyAgreement = 1 << 4 -#BakaShrot_X509_KeyUsage_KeyCertSign = 1 << 5 -#BakaShrot_X509_KeyUsage_CrlSign = 1 << 6 -#BakaShrot_X509_KeyUsage_EncipherOnly = 1 << 7 -#BakaShrot_X509_KeyUsage_DecipherOnly = 1 << 8 - - -;- Results - -Enumeration BakaShrot_X509Results - #BakaShrot_X509_Ok = 0 - ; Not a DER X.509 certificate (or PEM of one), or broken somewhere. - #BakaShrot_X509_Error_Malformed = 1 - ; Not Ed25519: it can be read, not checked nor used to issue. - #BakaShrot_X509_Error_Unsupported = 2 - ; Its signature isn't its issuer's. - #BakaShrot_X509_Error_BadSignature = 3 - ; Checked before its NotBefore, or after its NotAfter. - #BakaShrot_X509_Error_NotYetValid = 4 - #BakaShrot_X509_Error_Expired = 5 - ; It names another issuer (name, or key id) than the one it's checked with. - #BakaShrot_X509_Error_IssuerMismatch = 6 - ; Its issuer isn't a CA (BasicConstraints), or may not sign certificates (KeyUsage). - #BakaShrot_X509_Error_NotCa = 7 - ; More CAs under a CA than its PathLength allows. - #BakaShrot_X509_Error_PathTooLong = 8 - ; A critical extension nobody handles. - #BakaShrot_X509_Error_UnknownCritical = 9 - ; Issuing: the private key isn't the issuer's (or, self-signed, the subject's). - #BakaShrot_X509_Error_KeyMismatch = 10 - ; A missing or invalid argument, a template that can't be issued. - #BakaShrot_X509_Error_InvalidArgument = 11 - ; Out of memory, a file that can't be read. - #BakaShrot_X509_Error_Internal = 12 -EndEnumeration - - -Procedure.s BakaShrot_X509_ErrorName(Code.i) - Select Code - Case #BakaShrot_X509_Ok : ProcedureReturn "Ok" - Case #BakaShrot_X509_Error_Malformed : ProcedureReturn "Malformed" - Case #BakaShrot_X509_Error_Unsupported : ProcedureReturn "Unsupported" - Case #BakaShrot_X509_Error_BadSignature : ProcedureReturn "BadSignature" - Case #BakaShrot_X509_Error_NotYetValid : ProcedureReturn "NotYetValid" - Case #BakaShrot_X509_Error_Expired : ProcedureReturn "Expired" - Case #BakaShrot_X509_Error_IssuerMismatch : ProcedureReturn "IssuerMismatch" - Case #BakaShrot_X509_Error_NotCa : ProcedureReturn "NotCa" - Case #BakaShrot_X509_Error_PathTooLong : ProcedureReturn "PathTooLong" - Case #BakaShrot_X509_Error_UnknownCritical : ProcedureReturn "UnknownCritical" - Case #BakaShrot_X509_Error_KeyMismatch : ProcedureReturn "KeyMismatch" - Case #BakaShrot_X509_Error_InvalidArgument : ProcedureReturn "InvalidArgument" - Case #BakaShrot_X509_Error_Internal : ProcedureReturn "Internal" - EndSelect - ProcedureReturn "Unknown" + Str(Code) -EndProcedure - - -;- Structures - -; Key ids are the first 20 bytes of the SHA-256 of the public key (RFC 7093). -#BakaShrot_X509_KeyIdSize = 20 - -; Random serial numbers, when the template has none. -#BakaShrot_X509_SerialSize = 16 - -; The longest serial number taken (RFC 5280 allows 20 bytes, some write 21). -#BakaShrot_X509_MaxSerialSize = 32 - - -Structure BakaShrot_X509NameAttribute - ; Its type's OID ("2.5.4.3" for CN). - Oid.s - Value.s - ; Read: its DER string type (#BakaShrot_Der_Utf8String...). Issuing: 0 - ; picks the usual one (PrintableString for C, IA5String for emailAddress - ; and DC, UTF8String otherwise). - StringTag.i - ; Read: its RDN's index, attributes of a multi-valued RDN share it. - ; Issuing: each attribute is its own RDN, this is ignored. - Rdn.i -EndStructure - -; A distinguished name, its attributes in the certificate's order. -Structure BakaShrot_X509Name - Count.i - Array Attributes.BakaShrot_X509NameAttribute(0) -EndStructure - - -Structure BakaShrot_X509Extension - Oid.s - Critical.i - ; extnValue's contents: the extension's own DER. Owned by the - ; certificate or template it's in. - *Value - ValueSize.i -EndStructure - - -Structure BakaShrot_X509Certificate - ; The whole certificate, DER, owned. The offsets point into it. - *Der - DerSize.i - ; What the signature covers (tbsCertificate). - TbsOffset.i - TbsSize.i - ; The issuer's and subject's names as encoded: issuers are matched on these. - IssuerOffset.i - IssuerSize.i - SubjectOffset.i - SubjectSize.i - - ; 1 to 3. - Version.i - ; Hex, without the sign byte. - Serial.s - SignatureAlgorithm.s - Issuer.BakaShrot_X509Name - Subject.BakaShrot_X509Name - NotBefore.q - NotAfter.q - KeyAlgorithm.s - - ; Ed25519 only. - HasEd25519Key.i - PublicKey.a[#BakaShrot_Ed25519_PublicKeySize] - HasEd25519Signature.i - Signature.a[#BakaShrot_Ed25519_SignatureSize] - - ; Every extension, in order, the known ones too. - ExtensionCount.i - Array Extensions.BakaShrot_X509Extension(0) - - ; From BasicConstraints. PathLength -1 when there's none. - HasBasicConstraints.i - IsCa.i - PathLength.i - ; From KeyUsage, #BakaShrot_X509_KeyUsage_* flags. - HasKeyUsage.i - KeyUsage.i - ; Hex, "" when absent. - SubjectKeyId.s - AuthorityKeyId.s -EndStructure - - -; What BakaShrot_X509_Issue() makes a certificate of. Set PathLength -1 -; (no limit) or call BakaShrot_X509_InitTemplate() first, and -; BakaShrot_X509_ClearTemplate() once done (it holds the extensions' values). -Structure BakaShrot_X509Template - ; Hex; "" for #BakaShrot_X509_SerialSize random bytes. - Serial.s - Subject.BakaShrot_X509Name - NotBefore.q - NotAfter.q - ; The subject's Ed25519 public key. - PublicKey.a[#BakaShrot_Ed25519_PublicKeySize] - ; BasicConstraints, always written (critical). PathLength: CAs only, the - ; most CAs under this one, -1 for no limit. - IsCa.i - PathLength.i - ; KeyUsage (critical), #BakaShrot_X509_KeyUsage_* flags. 0: none written. - KeyUsage.i - ; Added with BakaShrot_X509_Add*Extension(), written after the standard ones. - ExtensionCount.i - Array Extensions.BakaShrot_X509Extension(0) -EndStructure - - -;- Helpers - -; Now, in seconds since 1970 UTC, for the checks. -CompilerIf #PB_Compiler_OS <> #PB_OS_Windows - ImportC "" - BakaShrot_X509_GetTimeOfDay.l(*TimeVal, *TimeZone) As "gettimeofday" - EndImport -CompilerEndIf - -Procedure.q BakaShrot_X509_Now() - CompilerIf #PB_Compiler_OS = #PB_OS_Windows - ; 100 ns intervals since 1601-01-01 UTC. - Protected FileTime.q - GetSystemTimeAsFileTime_(@FileTime) - ProcedureReturn (FileTime - 116444736000000000) / 10000000 - CompilerElse - Protected Dim TimeVal.q(1) - BakaShrot_X509_GetTimeOfDay(@TimeVal(0), 0) - ProcedureReturn TimeVal(0) - CompilerEndIf -EndProcedure - - -; Size bytes at *Data in lowercase hex. -Procedure.s BakaShrot_X509_Hex(*Data, Size.i) - Protected *Text, Text.s - - If Size < 1 - ProcedureReturn "" - EndIf - *Text = AllocateMemory(Size * 2 + 1) - If Not *Text - ProcedureReturn "" - EndIf - sodium_bin2hex(*Text, Size * 2 + 1, *Data, Size) - Text = PeekS(*Text, Size * 2, #PB_Ascii) - FreeMemory(*Text) - ProcedureReturn Text -EndProcedure - - -; Text as a new buffer of ASCII, its size (without the terminator) in -; *Size\i. 0 if it isn't ASCII. Free it with FreeMemory. -Procedure.i BakaShrot_X509_Ascii(Text.s, *Size.Integer) - Protected *Buffer, i.i - - For i = 1 To Len(Text) - If Asc(Mid(Text, i, 1)) > 127 - ProcedureReturn 0 - EndIf - Next - *Buffer = AllocateMemory(Len(Text) + 1) - If *Buffer - PokeS(*Buffer, Text, -1, #PB_Ascii) - *Size\i = Len(Text) - EndIf - ProcedureReturn *Buffer -EndProcedure - - -; Hex (any case) into *Out, at most MaxSize bytes. Returns how many, -1 if -; it isn't hex or doesn't fit. -Procedure.i BakaShrot_X509_FromHex(Hex.s, *Out, MaxSize.i) - Protected *Text, TextSize.Integer, Size.Integer, Result.i = -1 - - *Text = BakaShrot_X509_Ascii(Hex, @TextSize) - If *Text - If sodium_hex2bin(*Out, MaxSize, *Text, TextSize\i, 0, @Size, 0) = 0 - Result = Size\i - EndIf - FreeMemory(*Text) - EndIf - ProcedureReturn Result -EndProcedure - - -; The key id of an Ed25519 public key into *Out (#BakaShrot_X509_KeyIdSize -; bytes): the first 20 bytes of its SHA-256 (RFC 7093, method 1). -Procedure BakaShrot_X509_KeyId(*PublicKey, *Out) - Protected Dim Hash.a(#BakaShrot_Sha256_HashSize - 1) - - crypto_hash_sha256(@Hash(0), *PublicKey, #BakaShrot_Ed25519_PublicKeySize) - CopyMemory(@Hash(0), *Out, #BakaShrot_X509_KeyIdSize) -EndProcedure - - -;- Names - -; The OID of an attribute type: a short name (CN, O, OU, C, L, ST, -; serialNumber, emailAddress, DC, UID, any case) or an OID as is. "" if -; neither. -Procedure.s BakaShrot_X509_NameTypeOid(Type.s) - Select LCase(Type) - Case "cn" : ProcedureReturn #BakaShrot_Oid_CommonName - Case "serialnumber" : ProcedureReturn #BakaShrot_Oid_SerialNumber - Case "c" : ProcedureReturn #BakaShrot_Oid_Country - Case "l" : ProcedureReturn #BakaShrot_Oid_Locality - Case "st" : ProcedureReturn #BakaShrot_Oid_State - Case "o" : ProcedureReturn #BakaShrot_Oid_Organization - Case "ou" : ProcedureReturn #BakaShrot_Oid_OrganizationalUnit - Case "emailaddress" : ProcedureReturn #BakaShrot_Oid_EmailAddress - Case "dc" : ProcedureReturn #BakaShrot_Oid_DomainComponent - Case "uid" : ProcedureReturn #BakaShrot_Oid_UserId - EndSelect - If BakaShrot_Der_IsValidOid(Type) - ProcedureReturn Type - EndIf - ProcedureReturn "" -EndProcedure - - -; The short name of an attribute type's OID, the OID itself if it has none. -Procedure.s BakaShrot_X509_NameTypeShort(Oid.s) - Select Oid - Case #BakaShrot_Oid_CommonName : ProcedureReturn "CN" - Case #BakaShrot_Oid_SerialNumber : ProcedureReturn "serialNumber" - Case #BakaShrot_Oid_Country : ProcedureReturn "C" - Case #BakaShrot_Oid_Locality : ProcedureReturn "L" - Case #BakaShrot_Oid_State : ProcedureReturn "ST" - Case #BakaShrot_Oid_Organization : ProcedureReturn "O" - Case #BakaShrot_Oid_OrganizationalUnit : ProcedureReturn "OU" - Case #BakaShrot_Oid_EmailAddress : ProcedureReturn "emailAddress" - Case #BakaShrot_Oid_DomainComponent : ProcedureReturn "DC" - Case #BakaShrot_Oid_UserId : ProcedureReturn "UID" - EndSelect - ProcedureReturn Oid -EndProcedure - - -; Adds an attribute at the end of *Name. Type: a short name or an OID, see -; BakaShrot_X509_NameTypeOid(). StringTag: see BakaShrot_X509NameAttribute. -; Returns #False if Type is neither. -Procedure.i BakaShrot_X509_NameAdd(*Name.BakaShrot_X509Name, Type.s, Value.s, StringTag.i = 0, Rdn.i = -1) - Protected Oid.s = BakaShrot_X509_NameTypeOid(Type) - - If Oid = "" - ProcedureReturn #False - EndIf - If *Name\Count > ArraySize(*Name\Attributes()) - ReDim *Name\Attributes(*Name\Count * 2 + 3) - EndIf - If Rdn < 0 - Rdn = *Name\Count - EndIf - *Name\Attributes(*Name\Count)\Oid = Oid - *Name\Attributes(*Name\Count)\Value = Value - *Name\Attributes(*Name\Count)\StringTag = StringTag - *Name\Attributes(*Name\Count)\Rdn = Rdn - *Name\Count + 1 - ProcedureReturn #True -EndProcedure - - -; The first value of the attribute Type (a short name or an OID) in *Name, -; "" if it has none. -Procedure.s BakaShrot_X509_NameGet(*Name.BakaShrot_X509Name, Type.s) - Protected Oid.s = BakaShrot_X509_NameTypeOid(Type), i.i - - For i = 0 To *Name\Count - 1 - If *Name\Attributes(i)\Oid = Oid - ProcedureReturn *Name\Attributes(i)\Value - EndIf - Next - ProcedureReturn "" -EndProcedure - - -; *Name as "CN=demo, O=BakaShrot", in the certificate's order, the -; attributes of a multi-valued RDN joined with "+". For people: values -; aren't escaped. -Procedure.s BakaShrot_X509_NameToString(*Name.BakaShrot_X509Name) - Protected i.i, Text.s - - For i = 0 To *Name\Count - 1 - If i > 0 - If *Name\Attributes(i)\Rdn = *Name\Attributes(i - 1)\Rdn - Text + "+" - Else - Text + ", " - EndIf - EndIf - Text + BakaShrot_X509_NameTypeShort(*Name\Attributes(i)\Oid) + "=" + *Name\Attributes(i)\Value - Next - ProcedureReturn Text -EndProcedure - - -;- Reading - -; Frees a certificate from BakaShrot_X509_Parse() and the like. -Procedure BakaShrot_X509_Free(*Cert.BakaShrot_X509Certificate) - Protected i.i - - If Not *Cert - ProcedureReturn - EndIf - For i = 0 To *Cert\ExtensionCount - 1 - If *Cert\Extensions(i)\Value - FreeMemory(*Cert\Extensions(i)\Value) - EndIf - Next - If *Cert\Der - FreeMemory(*Cert\Der) - EndIf - FreeStructure(*Cert) -EndProcedure - - -; An AlgorithmIdentifier: its OID into *Oid\s, and whether it has -; parameters (any) into *HasParameters\i. -Procedure.i BakaShrot_X509_ReadAlgorithm(*Element.BakaShrot_DerElement, *Oid.String, *HasParameters.Integer) - Protected Reader.BakaShrot_DerReader, Item.BakaShrot_DerElement - - BakaShrot_Der_ReaderOf(@Reader, *Element) - If Not BakaShrot_Der_Expect(@Reader, #BakaShrot_Der_Oid, @Item) - ProcedureReturn #False - EndIf - *Oid\s = BakaShrot_Der_GetOid(@Item) - If *Oid\s = "" - ProcedureReturn #False - EndIf - *HasParameters\i = #False - If Not BakaShrot_Der_AtEnd(@Reader) - *HasParameters\i = #True - If Not BakaShrot_Der_Read(@Reader, @Item) - ProcedureReturn #False - EndIf - EndIf - ProcedureReturn BakaShrot_Der_AtEnd(@Reader) -EndProcedure - - -; A Name: a SEQUENCE of RDNs, each a SET of (type, string) pairs. -Procedure.i BakaShrot_X509_ReadName(*Element.BakaShrot_DerElement, *Name.BakaShrot_X509Name) - Protected Names.BakaShrot_DerReader, Rdns.BakaShrot_DerReader, Pair.BakaShrot_DerReader - Protected RdnSet.BakaShrot_DerElement, Attribute.BakaShrot_DerElement, Item.BakaShrot_DerElement - Protected Rdn.i, Oid.s, Value.String - - BakaShrot_Der_ReaderOf(@Names, *Element) - While Not BakaShrot_Der_AtEnd(@Names) - If Not BakaShrot_Der_Expect(@Names, #BakaShrot_Der_Set, @RdnSet) - ProcedureReturn #False - EndIf - BakaShrot_Der_ReaderOf(@Rdns, @RdnSet) - ; An RDN has one attribute at least. - If BakaShrot_Der_AtEnd(@Rdns) - ProcedureReturn #False - EndIf - While Not BakaShrot_Der_AtEnd(@Rdns) - If Not BakaShrot_Der_Expect(@Rdns, #BakaShrot_Der_Sequence, @Attribute) - ProcedureReturn #False - EndIf - BakaShrot_Der_ReaderOf(@Pair, @Attribute) - If Not BakaShrot_Der_Expect(@Pair, #BakaShrot_Der_Oid, @Item) - ProcedureReturn #False - EndIf - Oid = BakaShrot_Der_GetOid(@Item) - If Oid = "" Or Not BakaShrot_Der_Read(@Pair, @Item) Or Not BakaShrot_Der_AtEnd(@Pair) - ProcedureReturn #False - EndIf - If Not BakaShrot_Der_GetText(@Item, @Value) - ProcedureReturn #False - EndIf - BakaShrot_X509_NameAdd(*Name, Oid, Value\s, Item\Tag, Rdn) - Wend - Rdn + 1 - Wend - ProcedureReturn BakaShrot_Der_AtEnd(@Names) -EndProcedure - - -; The known extension *Extension's fields into *Cert. #False if malformed. -Procedure.i BakaShrot_X509_ReadKnownExtension(*Cert.BakaShrot_X509Certificate, *Extension.BakaShrot_X509Extension) - Protected Reader.BakaShrot_DerReader, Inner.BakaShrot_DerReader - Protected Item.BakaShrot_DerElement, Field.BakaShrot_DerElement, Value.q, Flag.i - - BakaShrot_Der_InitReader(@Reader, *Extension\Value, *Extension\ValueSize) - Select *Extension\Oid - - Case #BakaShrot_Oid_BasicConstraints - ; SEQUENCE { cA BOOLEAN DEFAULT FALSE, pathLenConstraint INTEGER OPTIONAL } - If Not BakaShrot_Der_Expect(@Reader, #BakaShrot_Der_Sequence, @Item) - ProcedureReturn #False - EndIf - BakaShrot_Der_ReaderOf(@Inner, @Item) - If BakaShrot_Der_PeekTag(@Inner) = #BakaShrot_Der_Boolean - If Not BakaShrot_Der_Read(@Inner, @Field) Or Not BakaShrot_Der_GetBoolean(@Field, @Flag) - ProcedureReturn #False - EndIf - *Cert\IsCa = Flag - EndIf - If BakaShrot_Der_PeekTag(@Inner) = #BakaShrot_Der_Integer - If Not BakaShrot_Der_Read(@Inner, @Field) Or Not BakaShrot_Der_GetInteger(@Field, @Value) Or Value < 0 Or Value > 255 - ProcedureReturn #False - EndIf - *Cert\PathLength = Value - EndIf - If Not BakaShrot_Der_AtEnd(@Inner) - ProcedureReturn #False - EndIf - *Cert\HasBasicConstraints = #True - - Case #BakaShrot_Oid_KeyUsage - If Not BakaShrot_Der_Expect(@Reader, #BakaShrot_Der_BitString, @Item) Or Not BakaShrot_Der_GetBitFlags(@Item, @Flag) - ProcedureReturn #False - EndIf - *Cert\KeyUsage = Flag - *Cert\HasKeyUsage = #True - - Case #BakaShrot_Oid_SubjectKeyId - If Not BakaShrot_Der_Expect(@Reader, #BakaShrot_Der_OctetString, @Item) Or Item\ContentSize < 1 - ProcedureReturn #False - EndIf - *Cert\SubjectKeyId = BakaShrot_X509_Hex(Item\Content, Item\ContentSize) - - Case #BakaShrot_Oid_AuthorityKeyId - ; SEQUENCE { keyIdentifier [0] OPTIONAL, authorityCertIssuer [1] OPTIONAL, authorityCertSerialNumber [2] OPTIONAL } - If Not BakaShrot_Der_Expect(@Reader, #BakaShrot_Der_Sequence, @Item) - ProcedureReturn #False - EndIf - BakaShrot_Der_ReaderOf(@Inner, @Item) - If BakaShrot_Der_PeekTag(@Inner) = #BakaShrot_Der_Context | 0 - If Not BakaShrot_Der_Read(@Inner, @Field) Or Field\ContentSize < 1 - ProcedureReturn #False - EndIf - *Cert\AuthorityKeyId = BakaShrot_X509_Hex(Field\Content, Field\ContentSize) - EndIf - If BakaShrot_Der_PeekTag(@Inner) = #BakaShrot_Der_ContextConstructed | 1 - BakaShrot_Der_Read(@Inner, @Field) - EndIf - If BakaShrot_Der_PeekTag(@Inner) = #BakaShrot_Der_Context | 2 - BakaShrot_Der_Read(@Inner, @Field) - EndIf - If Not BakaShrot_Der_AtEnd(@Inner) - ProcedureReturn #False - EndIf - - Default - ProcedureReturn #True - EndSelect - - ProcedureReturn BakaShrot_Der_AtEnd(@Reader) -EndProcedure - - -; Extensions: a SEQUENCE of one or more SEQUENCE { extnID OID, critical -; BOOLEAN DEFAULT FALSE, extnValue OCTET STRING }, each OID once at most. -Procedure.i BakaShrot_X509_ReadExtensions(*Element.BakaShrot_DerElement, *Cert.BakaShrot_X509Certificate) - Protected Items.BakaShrot_DerReader, Fields.BakaShrot_DerReader, Check.BakaShrot_DerReader - Protected Extension.BakaShrot_DerElement, Item.BakaShrot_DerElement - Protected Oid.s, Critical.i, i.i, Index.i - - BakaShrot_Der_ReaderOf(@Items, *Element) - If BakaShrot_Der_AtEnd(@Items) - ProcedureReturn #False - EndIf - While Not BakaShrot_Der_AtEnd(@Items) - If Not BakaShrot_Der_Expect(@Items, #BakaShrot_Der_Sequence, @Extension) - ProcedureReturn #False - EndIf - BakaShrot_Der_ReaderOf(@Fields, @Extension) - If Not BakaShrot_Der_Expect(@Fields, #BakaShrot_Der_Oid, @Item) - ProcedureReturn #False - EndIf - Oid = BakaShrot_Der_GetOid(@Item) - If Oid = "" - ProcedureReturn #False - EndIf - For i = 0 To *Cert\ExtensionCount - 1 - If *Cert\Extensions(i)\Oid = Oid - ProcedureReturn #False - EndIf - Next - Critical = #False - If BakaShrot_Der_PeekTag(@Fields) = #BakaShrot_Der_Boolean - If Not BakaShrot_Der_Read(@Fields, @Item) Or Not BakaShrot_Der_GetBoolean(@Item, @Critical) - ProcedureReturn #False - EndIf - EndIf - If Not BakaShrot_Der_Expect(@Fields, #BakaShrot_Der_OctetString, @Item) Or Not BakaShrot_Der_AtEnd(@Fields) - ProcedureReturn #False - EndIf - ; extnValue holds one DER element. - BakaShrot_Der_ReaderOf(@Check, @Item) - If Not BakaShrot_Der_Read(@Check, @Extension) Or Not BakaShrot_Der_AtEnd(@Check) - ProcedureReturn #False - EndIf - - Index = *Cert\ExtensionCount - If Index > ArraySize(*Cert\Extensions()) - ReDim *Cert\Extensions(Index * 2 + 3) - EndIf - *Cert\Extensions(Index)\Oid = Oid - *Cert\Extensions(Index)\Critical = Critical - *Cert\Extensions(Index)\ValueSize = Item\ContentSize - *Cert\Extensions(Index)\Value = AllocateMemory(Item\ContentSize) - If Not *Cert\Extensions(Index)\Value - ProcedureReturn #False - EndIf - CopyMemory(Item\Content, *Cert\Extensions(Index)\Value, Item\ContentSize) - *Cert\ExtensionCount + 1 - - If Not BakaShrot_X509_ReadKnownExtension(*Cert, @*Cert\Extensions(Index)) - ProcedureReturn #False - EndIf - Wend - ProcedureReturn #True -EndProcedure - - -; Reads a DER certificate, Size bytes at *Der (copied: it may be freed after). -; Returns a new BakaShrot_X509Certificate (free it with BakaShrot_X509_Free()), -; or 0 with *Error\l set (#BakaShrot_X509_Error_Malformed...), if given. -; Any algorithm is read; for Ed25519 the key and signature must be right. -; Nothing may follow the certificate. -Procedure.i BakaShrot_X509_Parse(*Der, Size.i, *Error.Long = 0) - Protected *Cert.BakaShrot_X509Certificate, Code.i = #BakaShrot_X509_Error_Malformed - Protected Top.BakaShrot_DerReader, Outer.BakaShrot_DerReader, Tbs.BakaShrot_DerReader, Inner.BakaShrot_DerReader - Protected CertElement.BakaShrot_DerElement, TbsElement.BakaShrot_DerElement, OuterAlgorithm.BakaShrot_DerElement - Protected SignatureElement.BakaShrot_DerElement, Item.BakaShrot_DerElement, Field.BakaShrot_DerElement - Protected Value.q, Oid.String, HasParameters.i, *Bytes, BytesSize.i - - If Not *Der Or Size < 1 Or Size > #BakaShrot_Der_MaxSize - Code = #BakaShrot_X509_Error_InvalidArgument - Goto ParseFailed - EndIf - *Cert = AllocateStructure(BakaShrot_X509Certificate) - If *Cert - *Cert\Der = AllocateMemory(Size) - EndIf - If Not *Cert Or Not *Cert\Der - Code = #BakaShrot_X509_Error_Internal - Goto ParseFailed - EndIf - CopyMemory(*Der, *Cert\Der, Size) - *Cert\DerSize = Size - *Cert\PathLength = -1 - - ; Certificate ::= SEQUENCE { tbsCertificate, signatureAlgorithm, signatureValue } - BakaShrot_Der_InitReader(@Top, *Cert\Der, Size) - If Not BakaShrot_Der_Expect(@Top, #BakaShrot_Der_Sequence, @CertElement) Or Not BakaShrot_Der_AtEnd(@Top) - Goto ParseFailed - EndIf - BakaShrot_Der_ReaderOf(@Outer, @CertElement) - If Not BakaShrot_Der_Expect(@Outer, #BakaShrot_Der_Sequence, @TbsElement) - Goto ParseFailed - EndIf - If Not BakaShrot_Der_Expect(@Outer, #BakaShrot_Der_Sequence, @OuterAlgorithm) - Goto ParseFailed - EndIf - If Not BakaShrot_Der_Expect(@Outer, #BakaShrot_Der_BitString, @SignatureElement) Or Not BakaShrot_Der_AtEnd(@Outer) - Goto ParseFailed - EndIf - *Cert\TbsOffset = TbsElement\Start - *Cert\Der - *Cert\TbsSize = TbsElement\Size - - BakaShrot_Der_ReaderOf(@Tbs, @TbsElement) - - ; version [0] EXPLICIT INTEGER DEFAULT v1: v1 is never written. - *Cert\Version = 1 - If BakaShrot_Der_PeekTag(@Tbs) = #BakaShrot_Der_ContextConstructed | 0 - BakaShrot_Der_Read(@Tbs, @Item) - BakaShrot_Der_ReaderOf(@Inner, @Item) - If Not BakaShrot_Der_Expect(@Inner, #BakaShrot_Der_Integer, @Field) Or Not BakaShrot_Der_AtEnd(@Inner) - Goto ParseFailed - EndIf - If Not BakaShrot_Der_GetInteger(@Field, @Value) Or Value < 1 Or Value > 2 - Goto ParseFailed - EndIf - *Cert\Version = Value + 1 - EndIf - - ; serialNumber - If Not BakaShrot_Der_Expect(@Tbs, #BakaShrot_Der_Integer, @Item) Or Not BakaShrot_Der_IsMinimalInteger(@Item) Or Item\ContentSize > #BakaShrot_X509_MaxSerialSize - Goto ParseFailed - EndIf - If Item\ContentSize > 1 And PeekA(Item\Content) = 0 - *Cert\Serial = BakaShrot_X509_Hex(Item\Content + 1, Item\ContentSize - 1) - Else - *Cert\Serial = BakaShrot_X509_Hex(Item\Content, Item\ContentSize) - EndIf - - ; signature: the same AlgorithmIdentifier as the outer one, byte for byte. - If Not BakaShrot_Der_Expect(@Tbs, #BakaShrot_Der_Sequence, @Item) - Goto ParseFailed - EndIf - If Item\Size <> OuterAlgorithm\Size Or Not CompareMemory(Item\Start, OuterAlgorithm\Start, Item\Size) - Goto ParseFailed - EndIf - If Not BakaShrot_X509_ReadAlgorithm(@Item, @Oid, @HasParameters) - Goto ParseFailed - EndIf - *Cert\SignatureAlgorithm = Oid\s - ; Ed25519 has no parameters (RFC 8410). - If Oid\s = #BakaShrot_Oid_Ed25519 And HasParameters - Goto ParseFailed - EndIf - - ; issuer - If Not BakaShrot_Der_Expect(@Tbs, #BakaShrot_Der_Sequence, @Item) Or Not BakaShrot_X509_ReadName(@Item, @*Cert\Issuer) - Goto ParseFailed - EndIf - *Cert\IssuerOffset = Item\Start - *Cert\Der - *Cert\IssuerSize = Item\Size - - ; validity - If Not BakaShrot_Der_Expect(@Tbs, #BakaShrot_Der_Sequence, @Item) - Goto ParseFailed - EndIf - BakaShrot_Der_ReaderOf(@Inner, @Item) - If Not BakaShrot_Der_Read(@Inner, @Field) Or Not BakaShrot_Der_GetTime(@Field, @*Cert\NotBefore) - Goto ParseFailed - EndIf - If Not BakaShrot_Der_Read(@Inner, @Field) Or Not BakaShrot_Der_GetTime(@Field, @*Cert\NotAfter) Or Not BakaShrot_Der_AtEnd(@Inner) - Goto ParseFailed - EndIf - - ; subject - If Not BakaShrot_Der_Expect(@Tbs, #BakaShrot_Der_Sequence, @Item) Or Not BakaShrot_X509_ReadName(@Item, @*Cert\Subject) - Goto ParseFailed - EndIf - *Cert\SubjectOffset = Item\Start - *Cert\Der - *Cert\SubjectSize = Item\Size - - ; subjectPublicKeyInfo ::= SEQUENCE { algorithm, subjectPublicKey BIT STRING } - If Not BakaShrot_Der_Expect(@Tbs, #BakaShrot_Der_Sequence, @Item) - Goto ParseFailed - EndIf - BakaShrot_Der_ReaderOf(@Inner, @Item) - If Not BakaShrot_Der_Expect(@Inner, #BakaShrot_Der_Sequence, @Field) Or Not BakaShrot_X509_ReadAlgorithm(@Field, @Oid, @HasParameters) - Goto ParseFailed - EndIf - *Cert\KeyAlgorithm = Oid\s - If Not BakaShrot_Der_Expect(@Inner, #BakaShrot_Der_BitString, @Field) Or Not BakaShrot_Der_AtEnd(@Inner) - Goto ParseFailed - EndIf - If Oid\s = #BakaShrot_Oid_Ed25519 - If HasParameters Or Not BakaShrot_Der_GetBitStringBytes(@Field, @*Bytes, @BytesSize) Or BytesSize <> #BakaShrot_Ed25519_PublicKeySize - Goto ParseFailed - EndIf - CopyMemory(*Bytes, @*Cert\PublicKey[0], #BakaShrot_Ed25519_PublicKeySize) - *Cert\HasEd25519Key = #True - EndIf - - ; issuerUniqueID [1], subjectUniqueID [2]: v2 and v3 only, skipped. - If BakaShrot_Der_PeekTag(@Tbs) = #BakaShrot_Der_Context | 1 - If *Cert\Version < 2 Or Not BakaShrot_Der_Read(@Tbs, @Item) - Goto ParseFailed - EndIf - EndIf - If BakaShrot_Der_PeekTag(@Tbs) = #BakaShrot_Der_Context | 2 - If *Cert\Version < 2 Or Not BakaShrot_Der_Read(@Tbs, @Item) - Goto ParseFailed - EndIf - EndIf - - ; extensions [3] EXPLICIT, v3 only. - If BakaShrot_Der_PeekTag(@Tbs) = #BakaShrot_Der_ContextConstructed | 3 - If *Cert\Version <> 3 - Goto ParseFailed - EndIf - BakaShrot_Der_Read(@Tbs, @Item) - BakaShrot_Der_ReaderOf(@Inner, @Item) - If Not BakaShrot_Der_Expect(@Inner, #BakaShrot_Der_Sequence, @Field) Or Not BakaShrot_Der_AtEnd(@Inner) - Goto ParseFailed - EndIf - If Not BakaShrot_X509_ReadExtensions(@Field, *Cert) - Goto ParseFailed - EndIf - EndIf - If Not BakaShrot_Der_AtEnd(@Tbs) - Goto ParseFailed - EndIf - - ; signatureValue - If Not BakaShrot_Der_GetBitStringBytes(@SignatureElement, @*Bytes, @BytesSize) - Goto ParseFailed - EndIf - If *Cert\SignatureAlgorithm = #BakaShrot_Oid_Ed25519 - If BytesSize <> #BakaShrot_Ed25519_SignatureSize - Goto ParseFailed - EndIf - CopyMemory(*Bytes, @*Cert\Signature[0], #BakaShrot_Ed25519_SignatureSize) - *Cert\HasEd25519Signature = #True - EndIf - - If *Error - *Error\l = #BakaShrot_X509_Ok - EndIf - ProcedureReturn *Cert - - ParseFailed: - BakaShrot_X509_Free(*Cert) - If *Error - *Error\l = Code - EndIf - ProcedureReturn 0 -EndProcedure - - -; The index of the extension Oid in *Cert, -1 if it has none. -Procedure.i BakaShrot_X509_FindExtension(*Cert.BakaShrot_X509Certificate, Oid.s) - Protected i.i - - For i = 0 To *Cert\ExtensionCount - 1 - If *Cert\Extensions(i)\Oid = Oid - ProcedureReturn i - EndIf - Next - ProcedureReturn -1 -EndProcedure - - -; The text of the extension Oid, a single DER string (see -; BakaShrot_Der_GetText()), into *Text\s. #False if *Cert has none, or it -; isn't a string. -Procedure.i BakaShrot_X509_GetExtensionText(*Cert.BakaShrot_X509Certificate, Oid.s, *Text.String) - Protected Index.i = BakaShrot_X509_FindExtension(*Cert, Oid) - Protected Reader.BakaShrot_DerReader, Item.BakaShrot_DerElement - - If Index < 0 - ProcedureReturn #False - EndIf - BakaShrot_Der_InitReader(@Reader, *Cert\Extensions(Index)\Value, *Cert\Extensions(Index)\ValueSize) - If Not BakaShrot_Der_Read(@Reader, @Item) Or Not BakaShrot_Der_AtEnd(@Reader) - ProcedureReturn #False - EndIf - ProcedureReturn BakaShrot_Der_GetText(@Item, *Text) -EndProcedure - - -; The value of the extension Oid, a single INTEGER of up to 8 bytes, into -; *Value\q. #False if *Cert has none, or it isn't one. -Procedure.i BakaShrot_X509_GetExtensionInteger(*Cert.BakaShrot_X509Certificate, Oid.s, *Value.Quad) - Protected Index.i = BakaShrot_X509_FindExtension(*Cert, Oid) - Protected Reader.BakaShrot_DerReader, Item.BakaShrot_DerElement - - If Index < 0 - ProcedureReturn #False - EndIf - BakaShrot_Der_InitReader(@Reader, *Cert\Extensions(Index)\Value, *Cert\Extensions(Index)\ValueSize) - If Not BakaShrot_Der_Expect(@Reader, #BakaShrot_Der_Integer, @Item) Or Not BakaShrot_Der_AtEnd(@Reader) - ProcedureReturn #False - EndIf - ProcedureReturn BakaShrot_Der_GetInteger(@Item, *Value) -EndProcedure - - -; SHA-256 of the whole certificate, in hex: what `openssl x509 -fingerprint -; -sha256` shows (without its colons). -Procedure.s BakaShrot_X509_Fingerprint(*Cert.BakaShrot_X509Certificate) - Protected Dim Hash.a(#BakaShrot_Sha256_HashSize - 1) - - crypto_hash_sha256(@Hash(0), *Cert\Der, *Cert\DerSize) - ProcedureReturn BakaShrot_X509_Hex(@Hash(0), #BakaShrot_Sha256_HashSize) -EndProcedure - - -; A UTC time as "2026-11-13 14:03:59Z". -Procedure.s BakaShrot_X509_FormatTime(Seconds.q) - Protected Days.q, Rest.q, Year.q, Month.q, Day.q - - Days = Seconds / 86400 - Rest = Seconds % 86400 - If Rest < 0 - Days - 1 - Rest + 86400 - EndIf - BakaShrot_Der_CivilFromDays(Days, @Year, @Month, @Day) - ProcedureReturn RSet(Str(Year), 4, "0") + "-" + RSet(Str(Month), 2, "0") + "-" + RSet(Str(Day), 2, "0") + " " + - RSet(Str(Rest / 3600), 2, "0") + ":" + RSet(Str((Rest / 60) % 60), 2, "0") + ":" + RSet(Str(Rest % 60), 2, "0") + "Z" -EndProcedure - - -; *Cert described in a few lines, for people (tools, logs). -Procedure.s BakaShrot_X509_Describe(*Cert.BakaShrot_X509Certificate) - Protected Text.s, i.i, Flags.s - - Text = "Subject: " + BakaShrot_X509_NameToString(@*Cert\Subject) + #LF$ + - "Issuer: " + BakaShrot_X509_NameToString(@*Cert\Issuer) + #LF$ + - "Serial: " + *Cert\Serial + #LF$ + - "Valid: " + BakaShrot_X509_FormatTime(*Cert\NotBefore) + " to " + BakaShrot_X509_FormatTime(*Cert\NotAfter) + #LF$ - If *Cert\HasEd25519Key - Text + "Key: Ed25519 " + EncodeKeyToString(@*Cert\PublicKey[0], #BakaShrot_Ed25519_PublicKeySize) + #LF$ - Else - Text + "Key: " + *Cert\KeyAlgorithm + " (not Ed25519)" + #LF$ - EndIf - If *Cert\HasBasicConstraints And *Cert\IsCa - If *Cert\PathLength >= 0 - Text + "CA: yes, path length " + Str(*Cert\PathLength) + #LF$ - Else - Text + "CA: yes" + #LF$ - EndIf - Else - Text + "CA: no" + #LF$ - EndIf - If *Cert\HasKeyUsage - Text + "Key usage: $" + Hex(*Cert\KeyUsage) + #LF$ - EndIf - For i = 0 To *Cert\ExtensionCount - 1 - Flags = "" - If *Cert\Extensions(i)\Critical - Flags = " (critical)" - EndIf - Text + "Extension: " + *Cert\Extensions(i)\Oid + Flags + ", " + Str(*Cert\Extensions(i)\ValueSize) + " bytes" + #LF$ - Next - Text + "SHA-256: " + BakaShrot_X509_Fingerprint(*Cert) - ProcedureReturn Text -EndProcedure - - -;- PEM - -; Size bytes at *Data as a PEM block: "-----BEGIN